Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var isLoggedIn = false;
- var searchBoolean = 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
- //This code is called when the body element has been loaded and the application starts
- updateStockList();
- /**
- * Laver en ny bruger og disabler knappen så du ikke kan lave flere brugere
- * Du kan derefter logge in.
- */
- $("#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 = false;
- });
- /**
- * Logger dig ind og fjerner div efter.
- */
- $("#login-button").on("click", function () {
- loginCustomer();
- makeLoginDivDisappear();
- });
- /**
- * Viser din kurv ved tryk og hvis du trykker på den igen slider den up.
- */
- $('a#show-quick-cart').click(function () {
- if ($('div#cart').css("display") == 'none') {
- $('div#cart').slideDown(500);
- } else {
- $('div#cart').slideUp(500);
- $("#buy-items-message").text("");
- }
- return false;
- });
- /**
- * Får login div frem og hvis du trykker på den igen forsvinder den.
- */
- $('a#login').click(function () {
- if ($('div.login-div').css("display") == 'none') {
- $('div.login-div').slideDown(500);
- } else {
- $('div.login-div').slideUp(500);
- }
- return false;
- });
- //ONLOAD FUNCTIONS
- buyItemsInCart();
- makeSearchEnter();
- myOrdersLogInFirst();
- goHome();
- hideFormerBought();
- };
- /**
- * Får login div til at slideup når musen forlader div'en.
- */
- function makeLoginDivDisappear() {
- $('div.login-div').mouseleave(function () {
- $('div.login-div').slideUp(500);
- });
- }
- /**
- * Når du søger efter noget og trykker på enter bliver search kaldt.
- */
- function makeSearchEnter() {
- $(document).on('keyup', "#searchField", function (e) {
- if (e.keyCode == 13) {
- searchForItems();
- }
- });
- }
- /**
- * Vores søge funktion, den ser hvilken shop du kigger på nu.
- * Og søger derefter det og viser det på siden.
- */
- function searchForItems() {
- var search = document.getElementById("searchField").value;
- var shop = document.getElementById("mySelect").value;
- console.log(search.length);
- if (search.length != 0){
- $('#searchField').val('');
- $('#searchField').attr("placeholder",'Searching...');
- }else {
- $('#searchField').attr("placeholder",'Please type in text');
- }
- $.post("/rest/shop/search", {search: search, shopID: shop}, function (response) {
- var items = JSON.parse(response);
- addItemsToTable(items);
- searchBoolean = true;
- $('#searchField').attr("placeholder",'Done! Enter new Word');
- });
- }
- /**
- * Laver en customer og ser om det er udfyldt korrekt.
- * Giver besked tilbage til brugeren, hvis det ikke lykkes.
- */
- 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");
- create.disabled = true;
- login.disabled = false;
- } else {
- errorMessage("We could not create you. Username is taken");
- login.disabled = false;
- create.disabled = false;
- }
- });
- }
- }
- /**
- * Logger din bruger ind og sætter boolean: isLoggedIn til true.
- */
- 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;
- } else {
- errorMessage("We could not log you in. Did you type your username & Password correct?");
- }
- });
- }
- }
- /**
- * Se mine tidligere ordre. Skjuler nuværende items og viser dine købte.
- */
- 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();
- showFormerBought();
- }
- });
- }
- /**
- * Til at vise brugeren, hvis det ikke lykkes at logge ind eller create customer.
- */
- function errorMessage(name) {
- $("#login-message-error-area").text(name);
- }
- /**
- * Hvis det ikke lykkes at købe tingene i kurven.
- * Eller hvis det lykkes giver den besked.
- */
- function buyMessage(text) {
- $("#buy-items-message").text(text);
- }
- /**
- * Bliver kaldt når siden loades og laver selecter.
- */
- 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();
- });
- }
- /**
- * Bliver kaldt for at opdatere itemsList.
- */
- 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);
- });
- }
- /**
- * Opdaterer itemsList med det shopID som Selecteren har.
- */
- function updateStockListWithOtherShopID() {
- var shopID = $('#mySelect').val();
- console.log(shopID);
- 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);
- hideFormerBought();
- showTable();
- });
- }
- /**
- * Funktion der gør det muligt at købe det der er i cart.
- */
- function buyItemsInCart() {
- $(document).on("click", "#buy-items-in-shopping-bag", function () {
- if (isLoggedIn == false) {
- buyMessage("You need to login to buy your items");
- } else {
- buyMessage("");
- $.post("/rest/shop/buyItemsInCart", null, function (response) {
- console.log("We got response");
- buyMessage(response);
- updateStockListWithOutSelect();
- var shoppingBag = document.getElementById("quickCart-products");
- //FIXME
- /*
- var $length = $('#quickCart-products').find('div').length;
- console.log("length is " + $length);
- if ($length >= 1) {
- for(i = 0; i<$length; i++){
- console.log(i);
- console.log(shoppingBag);
- console.log(shoppingBag.childNodes[i]);
- shoppingBag.removeChild(shoppingBag.childNodes[i]);
- }
- }
- */
- var price = document.getElementById("total-price");
- price.innerHTML = "0 kr.";
- updateStockListWithOtherShopID();
- var noItems = document.getElementById("no-items");
- noItems.style.display = "block";
- });
- }
- });
- }
- /**
- * //FIXME
- */
- function addToCartIfLoggedIn(itemID, itemStock) {
- if (itemStock > 0) {
- $.post("/rest/shop/addToCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- }
- }
- function removeFromCartIfLoggedIn(itemID) {
- $.post("/rest/shop/removeFromCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- }
- 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();
- console.log($nameText);
- var $thisName = '.' + $nameText.toString();
- console.log($thisName);
- 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";
- }
- }
- });
- }
- /**
- * Moving items to cart from table.
- */
- function addToQuickCart(itemName, itemPrice, itemURL) {
- // DIV
- var divToAdd = document.createElement("div");
- divToAdd.className = "divProductWithItem";
- // IMG
- var image = document.createElement('img');
- image.className = "fishPictures";
- image.src = itemURL;
- image.alt = "FAIL";
- divToAdd.appendChild(image);
- // NAME
- var para = document.createElement("p");
- para.textContent = itemName;
- para.className = itemName;
- divToAdd.appendChild(para);
- // PRICE
- var price = document.createElement("p");
- price.textContent = itemPrice + ' kr.';
- price.className = "itemPriceQuickCart";
- divToAdd.appendChild(price);
- $('.quickCart-products').prepend(divToAdd);
- var noItems = document.getElementById("no-items");
- noItems.style.display = "none";
- }
- function getShopNames() {
- sendRequest("GET", "rest/shop/getShopNames", null, function (shopNames) {
- var shops = JSON.parse(shopNames);
- viewShops(shops);
- });
- }
- 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);
- if (shop.shopName == "Fish Shop") {
- option.setAttribute("selected", "selected");
- }
- var shoptext = document.createTextNode(shopName);
- option.appendChild(shoptext);
- select.appendChild(option);
- }(i));
- }
- selectList();
- }
- function goHome() {
- $(document).on('click', '#home-button', function () {
- showTable();
- hideFormerBought();
- if (searchBoolean == true){
- updateStockListWithOtherShopID();
- searchBoolean = false;
- }
- });
- $(document).on('click', '#logo', function () {
- showTable();
- hideFormerBought();
- if (searchBoolean == true){
- updateStockListWithOtherShopID();
- searchBoolean = false;
- }
- });
- }
- function showFormerBought() {
- var list = document.getElementById("my-orders");
- list.style.display = "table";
- list.style.visibility = "visible";
- list.style.width = "100%";
- list.style.marginTop = "0px";
- }
- function hideFormerBought() {
- var list = document.getElementById("my-orders");
- list.style.display = "none";
- list.style.visibility = "hidden";
- list.style.marginTop = "150px";
- }
- function hideTable() {
- var table = document.getElementById("table-div");
- table.style.display = "none";
- table.style.visibility = "hidden";
- }
- function showTable() {
- var table = document.getElementById("table-div");
- table.style.display = "table";
- table.style.visibility = "visible";
- table.style.width = "100%";
- }
- function getFormerBought() {
- sendRequest("GET", "rest/shop/itemsBought", null, function (shopNames) {
- var shops = JSON.parse(shopNames);
- viewBoughtItems(shops);
- });
- }
- 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()];
- var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
- var date = timeStamp.getDate();
- var day = days[timeStamp.getDay()];
- var hours = timeStamp.getHours();
- var minutes = timeStamp.getMinutes();
- var seconds = timeStamp.getSeconds();
- //+ " at " +hours+ ":" + minutes + ":" + seconds
- dateCell.textContent = day + ", " + month + " " + date + ", " + year;
- 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);
- }
- 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);
- hideFormerBought();
- showTable();
- });
- });
- }
- 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);
- }
- 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, item.itemPrice, item.itemURL);
- 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