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
- //This code is called when the body element has been loaded and the application starts
- updateStockList();
- //Register an event listener for button clicks
- 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);
- });
- });
- $("#create-customer-submit-button").click(function () {
- var login = document.getElementById("login-customer-submit-button");
- var create = document.getElementById("create-customer-submit-button");
- createCustomer();
- create.disabled = true;
- login.disabled = true;
- });
- $("#login-customer-submit-button").on("click", function () {
- loginCustomer();
- });
- $('a#show-quick-cart').mouseenter(function () {
- $('div#cart').slideDown(500);
- return false;
- });
- $('div#pardiv').mouseleave(function () {
- $('div#cart').slideUp(500);
- return false;
- })
- $('a#login').click(function () {
- if ($('div.login-div').css("display") == 'none') {
- $('div.login-div').slideDown(500);
- } else {
- $('div.login-div').slideUp(500);
- }
- return false;
- })
- };
- 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;
- }
- });
- }
- }
- 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-customer-submit-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;
- getShopNames();
- buyItemsInCart();
- showFormerBought();
- } else {
- errorMessage("We could not log you in. Did you type your username & Password correct?");
- }
- });
- }
- }
- function errorMessage(name) {
- $("#login-message-error-area").text(name);
- }
- function buyMessage(text) {
- $("#buy-items-message").text(text);
- }
- /**
- * FIX ME !!!!!
- */
- function addToCartIfLoggedIn(itemID, itemStock) {
- if (isLoggedIn == true) {
- if (itemStock > 0) {
- $.post("/rest/shop/addToCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- }else {
- //DO WHAT?
- }
- }
- }
- function removeFromCartIfLoggedIn(itemID) {
- if (isLoggedIn == true) {
- $.post("/rest/shop/removeFromCart", {itemID: itemID}, function (response) {
- //Do nothing...
- });
- }
- }
- 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);
- });
- }
- /**
- * Der mangler at når du køber opdatere den stock.
- */
- function buyItemsInCart() {
- $(document).on("click", "#buy-items-in-shopping-bag", function () {
- $.post("/rest/shop/buyItemsInCart", null, function (response) {
- buyMessage(response);
- updateStockList();
- });
- });
- }
- 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();
- });
- }
- function addToQuickCart(itemName) {
- var para = document.createElement("p");
- para.textContent = itemName;
- $('.quickCart-products').prepend(para);
- }
- 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);
- var shoptext = document.createTextNode(shopName);
- option.appendChild(shoptext);
- select.appendChild(option);
- }(i));
- }
- selectList();
- }
- function showFormerBought() {
- $(document).on('click', '#my-orders-button', function () {
- getFormerBought();
- });
- }
- function getFormerBought() {
- sendRequest("GET", "rest/shop/itemsBought", null, function (shopNames) {
- var shops = JSON.parse(shopNames);
- viewBoughtItems(shops);
- });
- }
- function viewBoughtItems(items) {
- var div = document.getElementById("my-orders");
- var totalAmountForCustomer = 0;
- for (i = 0; i < items.length; i++) {
- //GET ITEMS FROM SERVER WITH ID
- (function (i) {
- var itemFormerBought = items[i];
- var divToDiv = document.createElement("div");
- var ul = document.createElement("ul");
- var li = document.createElement("li");
- // FIND ITEMS INFO FROM THAT ITEM ID
- var findItemFromTable = document.getElementById(itemFormerBought.itemID);
- // ITEM URL- PICTURE
- var img = document.createElement("img");
- img.src = findItemFromTable.getElementsByTagName('td')[1].getElementsByTagName('img')[0].getAttribute('src');
- img.alt = "FAIL";
- img.className = "fishPicturesInMyOrders";
- li.appendChild(img);
- // ITEM NAME
- var h3 = document.createElement("h3");
- h3.textContent = findItemFromTable.getElementsByTagName('td')[0].textContent;
- li.appendChild(h3);
- // ITEM PRICE
- var paraItemPrice = document.createElement("p");
- var itemPrice = findItemFromTable.getElementsByTagName('td')[2].textContent;
- paraItemPrice.textContent = "Price is: " + itemPrice;
- li.appendChild(paraItemPrice);
- // ITEM AMOUNT
- var paraItemAmount = document.createElement("p");
- var saleAmount = itemFormerBought.saleAmount;
- paraItemAmount.textContent = "Amount is: " + saleAmount;
- li.appendChild(paraItemAmount);
- // TOTAL FOR THIS ITEM
- var paraItemTotalAmount = document.createElement("p");
- var totalForThisItem = (parseInt(itemPrice * saleAmount));
- totalAmountForCustomer += totalForThisItem;
- paraItemTotalAmount.textContent = "Total price is " + totalForThisItem;
- li.appendChild(paraItemTotalAmount);
- ul.appendChild(li);
- divToDiv.appendChild(ul);
- div.appendChild(divToDiv);
- }(i));
- }
- 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();
- var updateShopButton = document.getElementById("update-itemList");
- addEventListener(updateShopButton, 'click', function () {
- 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);
- });
- });
- });
- }
- 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.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;
- 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 = "inputInCard";
- 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