Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var isLoggedIn = false;
- //Run this function when we have loaded the HTML document
- window.onload = function () {
- //Request items from the server. The server expects no request body, so we set it to null
- updateStockList();
- /**
- * FIXME
- * Bruger vi stadig dette?
- */
- var updateButton = document.getElementById("update");
- addEventListener(updateButton, "click", function () {
- //Same as above, get the items from the server
- sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
- //This code is called when the server has sent its data
- var items = JSON.parse(itemsText);
- addItemsToTable(items);
- });
- });
- /**
- * We create a button that enables the user to create a customer using the method create customer
- */
- $("#create-customer-submit-button").click(function () {
- var login = document.getElementById("login-button");
- var create = document.getElementById("create-customer-submit-button");
- createCustomer();
- create.disabled = true;
- login.disabled = true;
- });
- /**
- * Creating a button that can log in a customer
- */
- $("#login-button").on("click", function () {
- loginCustomer();
- makeLoginDivDisappear();
- });
- /**
- * Creating a logo that can be pressed to show the cart
- */
- $('a#show-quick-cart').click(function () {
- if ($('div#cart').css("display") == 'none') {
- $('div#cart').slideDown(500);
- } else{
- $('div#cart').slideUp(500);
- }
- return false;
- });
- /**
- * Making the login "page" slide down when needed and up when not needed
- */
- $('a#login').click(function () {
- if ($('div.login-div').css("display") == 'none') {
- $('div.login-div').slideDown(500);
- } else {
- $('div.login-div').slideUp(500);
- }
- return false;
- });
- makeSearchEnter();
- myOrdersLogInFirst();
- goHome();
- };
- /**
- * When logged in the login "page" slide up by it selv
- */
- function makeLoginDivDisappear() {
- $('div.login-div').mouseleave(function () {
- $('div.login-div').slideUp(500);
- });
- }
- /**
- * Creating/managing the searchbar
- */
- function makeSearchEnter() {
- $(document).on('keyup', "#searchField", function (e) {
- if (e.keyCode == 13) {
- searchForItems();
- }
- });
- }
- /**
- * In this method we search for items that are placed in the product list. The search is not
- * constricted by search only by name.
- */
- function searchForItems() {
- var search = document.getElementById("searchField").value;
- var shop = document.getElementById("mySelect").value;
- $.post("/rest/shop/search", {search: search}, function (response) {
- var items = JSON.parse(response);
- addItemsToTable(items);
- });
- console.log(search);
- }
- /**
- * The method creates af new customer, when doing this the method looks to see if both the
- * createUserName and createUserPassword field are filled out if not is gives a errormessage.
- * It then checks whether a user with name exists or not.
- */
- function createCustomer() {
- var createCustomerName = document.getElementById("createUserName").value;
- var createCustomerPassword = document.getElementById("createUserPassword").value;
- if (!(createCustomerName.length > 0 && createCustomerPassword.length > 0)) {
- errorMessage("You must fill in both username and password!");
- } else {
- $.post("/rest/shop/createCustomer", {
- username: createCustomerName,
- password: createCustomerPassword
- }, function (name) {
- var login = document.getElementById("login-customer-submit-button");
- var create = document.getElementById("create-customer-submit-button");
- if (name == "true") {
- errorMessage("Your are now a customer. Please Log in");
- login.disabled = false;
- create.disabled = true;
- } else {
- errorMessage("We could not create you. Username is taken");
- login.disabled = false;
- create.disabled = false;
- }
- });
- }
- }
- /**
- * The method logs in a existing customer, when doing this the method looks to see if both the
- * createUserName and createUserPassword field are filled out, if not is gives a errormessage.
- * It then checks if the name and password are correct if it is so then disables the login and create buttons
- * and allows the customer to but items by calling the method buyItemsInCart.
- */
- function loginCustomer() {
- var customerName = document.getElementById("createUserName").value;
- var customerPass = document.getElementById("createUserPassword").value;
- if (!(customerName.length > 0 && customerPass.length > 0)) {
- errorMessage("You must fill in both username and password!");
- } else {
- $.post("/rest/shop/loginCustomer", {
- username: customerName,
- password: customerPass
- }, function (name) {
- var login = document.getElementById("login-button");
- var create = document.getElementById("create-customer-submit-button");
- if (name == "true") {
- errorMessage("You are now logged in.");
- isLoggedIn = true;
- create.disabled = true;
- login.disabled = true;
- buyItemsInCart();
- } else {
- errorMessage("We could not log you in. Did you type your username & Password correct?");
- }
- });
- }
- }
- /**
- * This method allows the customer to view previously bought items if the customer is logged in.
- */
- function myOrdersLogInFirst() {
- $(document).on('click', '#my-orders-button', function () {
- if(isLoggedIn == false) {
- alert("You have to log in before you can see your previous orders!");
- } else{
- hideTable();
- getFormerBought();
- }
- });
- }
- function errorMessage(name) {
- $("#login-message-error-area").text(name);
- }
- function buyMessage(text) {
- $("#buy-items-message").text(text);
- }
- /**
- * FIX ME !!!!!
- * The method adds items to the cart when pressing the addtocart button, but only if the stock of the
- * product is more than 0.
- */
- function addToCartIfLoggedIn(itemID, itemStock) {
- if (isLoggedIn == true) {
- if (itemStock > 0) {
- $.post("/rest/shop/addToCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- } else {
- //DO WHAT?
- }
- }
- }
- /**
- * Allos the customer to remove a certain item from the cart.
- * @param itemID
- */
- function removeFromCartIfLoggedIn(itemID) {
- if (isLoggedIn == true) {
- $.post("/rest/shop/removeFromCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- }
- }
- /**
- * This method refills the product table, after a product is added to the cart and bought.
- * This is done my calling the addItemsToTable and getShopNames methods.
- */
- function updateStockList() {
- sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
- //This code is called when the server has sent its data
- var items = JSON.parse(itemsText);
- addItemsToTable(items);
- getShopNames();
- });
- }
- /**
- * FIXME
- * HVAD GØR DENNE HER?
- */
- function updateStockListWithOutSelect() {
- sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
- //This code is called when the server has sent its data
- var items = JSON.parse(itemsText);
- addItemsToTable(items);
- });
- }
- /**
- * Der mangler at når du køber opdatere den stock.
- * MANGLER MEGET
- *
- * In this method it is made possible to buy the items currently in the cart. When this is done the item
- * is removed and can be viewed under my orders.
- */
- function buyItemsInCart() {
- $(document).on("click", "#buy-items-in-shopping-bag", function () {
- console.log("Clicked by");
- $.post("/rest/shop/buyItemsInCart", null, function (response) {
- console.log("We got response");
- buyMessage(response);
- updateStockList();
- });
- });
- }
- /**
- * This method depicts the entire proces of adding an item to the cart. The addItemButton increments the
- * number of a certain product is wanted. This is only possible when the stockvalue of the product is more
- * than 0, which is controlled by the method eow.
- * Futhermore there is a remove button that does the opposite of the addbutton, the criteria for the
- * removebutton is that the current number of items chosen are more than 0 or else it does nothing.
- * The removebutton also removes the product from the cart it self by using the method removeFromQuickCart.
- *
- */
- var stockValue;
- function addToCartChange() {
- $(".addItemButton").click(function () {
- var $this = $(this);
- var $counter = $this.closest('td').next('.itemsInCart').find('span');
- var $number = parseInt($counter.text());
- var $numberToAdd = 1;
- var $stock = $this.closest('td').prev('td');
- var $stockValue = parseInt($stock.text());
- stockValue = $stockValue;
- eow();
- function eow(stockValue) {
- if ($number < $stockValue || $stockValue > 0) {
- $number = $number + $numberToAdd;
- $stockValue--;
- $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>");
- $stock.replaceWith("<td>" + $stockValue + "</td>");
- } else {
- $number = $stockValue;
- }
- }
- price();
- });
- $(".removeItemButton").click(function () {
- var $this = $(this);
- var $counter = $this.closest('td').prev('.itemsInCart').find('span');
- var $number = parseInt($counter.text());
- var $numberToRemove = 1;
- var $stock = $this.closest('td').prev('td').prev('td').prev('td');
- var $stockValue = parseInt($stock.text());
- if ($number > 0) {
- $number = $number - $numberToRemove;
- $stockValue++;
- $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>")
- $stock.replaceWith("<td>" + $stockValue + "</td>")
- } else {
- $number = 0;
- }
- price();
- removeFromQuickCart();
- function removeFromQuickCart() {
- var $name = $this.closest('td').prev('td').prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
- var $nameText = $name.text();
- var $thisName = '.' + $nameText.toString();
- if($('#quickCart-products').find($thisName).length != 0){
- var elements = $('#quickCart-products').find($thisName);
- elements[0].parentNode.removeChild(elements[0]);
- }
- if($('#quickCart-products').find('p').length === 1){
- var noItems = document.getElementById("no-items");
- noItems.style.display = "block";
- }
- }
- });
- }
- /**
- * This method adds a given product to the cart.
- * @param itemName
- */
- function addToQuickCart(itemName) {
- var para = document.createElement("p");
- para.textContent = itemName;
- para.className = itemName;
- $('.quickCart-products').prepend(para);
- var noItems = document.getElementById("no-items");
- noItems.style.display = "none";
- }
- /**
- * This method allows to see the shopnames of other shops
- */
- function getShopNames() {
- sendRequest("GET", "rest/shop/getShopNames", null, function (shopNames) {
- var shops = JSON.parse(shopNames);
- viewShops(shops);
- });
- }
- /**
- * This method creates a list containing all the names of shops one the server. It calls the method
- * selectList which fills the product table with the product from the specific shop.
- * @param shopNames
- */
- function viewShops(shopNames) {
- var scroller = document.getElementById("scroller");
- var select = document.createElement("SELECT");
- for (i = 0; i < shopNames.length; i++) {
- (function (i) {
- var shop = shopNames[i];
- select.setAttribute("id", "mySelect");
- scroller.appendChild(select);
- var shopName = shop.shopName;
- var shopID = shop.ShopID;
- var option = document.createElement("option");
- option.setAttribute("value", shopID);
- var shoptext = document.createTextNode(shopName);
- option.appendChild(shoptext);
- select.appendChild(option);
- }(i));
- }
- selectList();
- }
- /**
- * The method returns the user home, meaning the product table is shown. The is possible to do by clicking the
- * homeicon or the logo.
- */
- function goHome() {
- $(document).on('click', '#home-button', function () {
- showTable();
- hideFormerBought();
- //updateStockListWithOutSelect();
- });
- $(document).on('click', '#logo', function () {
- showTable();
- hideFormerBought();
- //updateStockListWithOutSelect();
- });
- }
- /**
- * FIXME
- * ARBEJDER VI OS VÆK FRA DEN
- *
- * The method hides myOrders
- */
- function hideFormerBought() {
- var list = document.getElementById("my-orders");
- list.style.display = "none";
- list.style.visibility = "hidden";
- list.style.marginTop = "150px";
- }
- /**
- * FIXME
- * ARBEJDER VI OS VÆK FRA DEN
- *
- * The method hides the product table
- */
- function hideTable() {
- var table = document.getElementById("table-div");
- table.style.display = "none";
- table.style.visibility = "hidden";
- }
- /**
- * FIXME
- * ARBEJDER VI OS VÆK FRA DEN
- *
- * The method shows the product table
- */
- function showTable() {
- var table = document.getElementById("table-div");
- table.style.display = "table";
- table.style.visibility = "visible";
- table.style.width = "100%";
- }
- /**
- * The method here shows the customers previously bought items.
- */
- function getFormerBought() {
- sendRequest("GET", "rest/shop/itemsBought", null, function (shopNames) {
- var shops = JSON.parse(shopNames);
- viewBoughtItems(shops);
- });
- }
- /**
- * In this method we fill the table containing the product that have been bought earlier. This is done by looping through
- * all of the items and placing one item in each row and the itemID, itemName and so on in their respective table cells.
- * @param items
- */
- function viewBoughtItems(items) {
- //Get the table body we we can add items to it
- var tableBody = document.getElementById("itemTableBody-my-orders");
- //Remove all contents of the table body (if any exist)
- tableBody.innerHTML = "";
- var totalAmountForCustomer = 0;
- for (i = 0; i < items.length; i++) {
- //GET ITEMS FROM SERVER WITH ID
- (function (i) {
- var itemFormerBought = items[i];
- var tr = document.createElement("tr");
- //TIME BOUGHT
- var dateCell = document.createElement("td");
- var timeStamp = new Date(parseInt(itemFormerBought.saleTime));
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
- var year = timeStamp.getFullYear();
- var month = months[timeStamp.getMonth() - 1];
- var date = timeStamp.getDate();
- var hours = timeStamp.getHours();
- var minutes = timeStamp.getMinutes();
- dateCell.textContent = date + ". " + month + ". " + hours + ": " + minutes;
- tr.appendChild(dateCell);
- // ITEM NAME
- var nameCell = document.createElement("td");
- nameCell.className = "itemName";
- nameCell.textContent = itemFormerBought.item.itemName;
- tr.appendChild(nameCell);
- // ITEM URL / PICTURE
- var picturecell = document.createElement("td");
- var image = document.createElement('img');
- image.className = "fishPictures";
- image.src = itemFormerBought.item.itemURL;
- image.alt = "FAIL";
- picturecell.appendChild(image);
- tr.appendChild(picturecell);
- //ITEM DESCRIPTION
- var htmlItemDescription = itemFormerBought.item.itemDescription;
- var htmlConverter = document.createElement("td");
- htmlConverter.innerHTML = htmlItemDescription;
- tr.appendChild(htmlConverter);
- // ITEM AMOUNT
- var itemAmount = document.createElement("td");
- var saleAmount = itemFormerBought.saleAmount;
- itemAmount.textContent = saleAmount;
- tr.appendChild(itemAmount);
- // ITEM PRICE
- var paraItemPrice = document.createElement("td");
- var itemPrice = itemFormerBought.item.itemPrice;
- paraItemPrice.textContent = itemPrice + " kr.";
- tr.appendChild(paraItemPrice);
- // TOTAL FOR THIS ITEM
- var paraItemTotalAmount = document.createElement("td");
- var totalForThisItem = (parseInt(itemPrice * saleAmount));
- totalAmountForCustomer += totalForThisItem;
- paraItemTotalAmount.textContent = totalForThisItem + " kr.";
- tr.appendChild(paraItemTotalAmount);
- //Append
- tableBody.appendChild(tr);
- }(i));
- }
- var div = document.getElementById("result-my-orders");
- div.innerHTML ="";
- var totalPricePara = document.createElement("p");
- totalPricePara.textContent = "Total price for all your buys is " + totalAmountForCustomer;
- div.appendChild(totalPricePara);
- }
- /**
- * This method dictate which shops product table will be shown.
- */
- function selectList() {
- $('#mySelect').change(function () {
- var shopID = $(this).val();
- sendRequest("GET", "rest/shop/items/" + shopID, null, function (itemsText) {
- //This code is called when the server has sent its data
- var items = JSON.parse(itemsText);
- addItemsToTable(items);
- });
- });
- }
- /**
- * The method finds the sum of all the product currently in the cart.
- */
- function price() {
- var totalPriceSpan = document.getElementById("total-price"),
- $totalPriceSpan = totalPriceSpan,
- amount = document.getElementsByClassName("inputInCart"),
- price = document.getElementsByClassName("price"),
- parent = totalPriceSpan.parentNode,
- tempDiv = document.createElement('div');
- var totalPrice = 0;
- for (var i = 0; i < amount.length; i++) {
- var amountOfItem = parseInt(amount[i].innerText);
- var priceOfEach = parseInt(price[i].innerText);
- var priceOfAll = amountOfItem * priceOfEach;
- var oldString = totalPrice.toString() + "kr.";
- totalPrice += priceOfAll;
- var totalPriceString = totalPrice.toString() + "kr.";
- }
- tempDiv.innerHTML = "<b class='total-price' id='total-price'>" + totalPriceString + "</b>";
- var input = tempDiv.childNodes[0];
- parent.replaceChild(input, totalPriceSpan);
- }
- /**
- * In this method we fill the table containing our products. This is done by looping through
- * all of the items and placing one item in each row and the itemID, itemName and so on in their respective table cells.
- * @param items
- */
- function addItemsToTable(items) {
- //Get the table body we we can add items to it
- var tableBody = document.getElementById("itemtablebody");
- //Remove all contents of the table body (if any exist)
- tableBody.innerHTML = "";
- //Loop through the items from the server
- for (var i = 0; i < items.length; i++) {
- (function (i) {
- var item = items[i];
- //Create a new line for this item
- var tr = document.createElement("tr");
- tr.id = item.itemID;
- // ITEM NAME
- var nameCell = document.createElement("td");
- nameCell.className = "itemName";
- nameCell.textContent = item.itemName;
- tr.appendChild(nameCell);
- //Item URL / ITEM PICTURE
- var picturecell = document.createElement("td");
- var image = document.createElement('img');
- image.className = "fishPictures";
- image.src = item.itemURL;
- image.alt = "FAIL";
- picturecell.appendChild(image);
- tr.appendChild(picturecell);
- // ITEM PRICE
- var priceCell = document.createElement("td");
- priceCell.textContent = item.itemPrice;
- priceCell.className = "price";
- tr.appendChild(priceCell);
- //ITEM DESCRIPTION
- var htmlItemDescription = item.itemDescription;
- var htmlConverter = document.createElement("td");
- htmlConverter.innerHTML = htmlItemDescription;
- tr.appendChild(htmlConverter);
- // ITEM STOCK
- var itemStock = document.createElement("td");
- itemStock.textContent = item.itemStock;
- tr.appendChild(itemStock);
- // ADD TO CART
- var addToCart = document.createElement("td");
- var addToCartButton = document.createElement("BUTTON");
- addToCartButton.className = "addItemButton";
- var buttonText = document.createTextNode(" + ");
- addToCartButton.appendChild(buttonText);
- addToCart.appendChild(addToCartButton);
- tr.appendChild(addToCart);
- // ADD TO CART - FUNCTION
- $(addToCartButton).click(function () {
- addToQuickCart(item.itemName);
- addToCartIfLoggedIn(item.itemID, item.itemStock);
- });
- // IN CART
- var itemsInCart = document.createElement("td");
- itemsInCart.className = "inCart";
- var inputField = document.createElement("span");
- inputField.textContent = "0";
- inputField.className = "inputInCart";
- itemsInCart.appendChild(inputField);
- itemsInCart.className = "itemsInCart";
- tr.appendChild(itemsInCart);
- //REMOVE FROM CART
- var removeFromCart = document.createElement("td");
- var removeFromCartButton = document.createElement("BUTTON");
- removeFromCartButton.className = "removeItemButton";
- var buttonText = document.createTextNode(" - ");
- removeFromCartButton.appendChild(buttonText);
- removeFromCart.appendChild(removeFromCartButton);
- tr.appendChild(removeFromCart);
- // REMOVE FROM CART - BUTTON
- $(removeFromCartButton).click(function () {
- removeFromCartIfLoggedIn(item.itemID);
- });
- // ITEM ID
- var itemID = document.createElement("td");
- itemID.textContent = item.itemID;
- tr.appendChild(itemID);
- tableBody.appendChild(tr);
- })(i);
- }
- addToCartChange();
- }
- /////////////////////////////////////////////////////
- // Code from slides
- /////////////////////////////////////////////////////
- /**
- * A function that can add event listeners in any browser
- */
- function addEventListener(myNode, eventType, myHandlerFunc) {
- if (myNode.addEventListener)
- myNode.addEventListener(eventType, myHandlerFunc, false);
- else
- myNode.attachEvent("on" + eventType,
- function (event) {
- myHandlerFunc.call(myNode, event);
- });
- }
- var http;
- if (!XMLHttpRequest)
- http = new ActiveXObject("Microsoft.XMLHTTP");
- else
- http = new XMLHttpRequest();
- function sendRequest(httpMethod, url, body, responseHandler) {
- http.open(httpMethod, url);
- if (httpMethod == "POST") {
- http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- }
- http.onreadystatechange = function () {
- if (http.readyState == 4 && http.status == 200) {
- responseHandler(http.responseText);
- }
- };
- http.send(body);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement