· 9 years ago · Mar 05, 2017, 11:46 AM
1var isLoggedIn = false;
2//Run this function when we have loaded the HTML document
3window.onload = function () {
4 //Request items from the server. The server expects no request body, so we set it to null
5
6
7 updateStockList();
8
9
10 /**
11 * FIXME
12 * Bruger vi stadig dette?
13 */
14 var updateButton = document.getElementById("update");
15 addEventListener(updateButton, "click", function () {
16 //Same as above, get the items from the server
17 sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
18 //This code is called when the server has sent its data
19 var items = JSON.parse(itemsText);
20 addItemsToTable(items);
21
22 });
23 });
24
25 /**
26 * We create a button that enables the user to create a customer using the method create customer
27 */
28 $("#create-customer-submit-button").click(function () {
29 var login = document.getElementById("login-button");
30 var create = document.getElementById("create-customer-submit-button");
31 createCustomer();
32 create.disabled = true;
33 login.disabled = true;
34
35 });
36
37 /**
38 * Creating a button that can log in a customer
39 */
40 $("#login-button").on("click", function () {
41 loginCustomer();
42 makeLoginDivDisappear();
43
44 });
45
46
47 /**
48 * Creating a logo that can be pressed to show the cart
49 */
50 $('a#show-quick-cart').click(function () {
51 if ($('div#cart').css("display") == 'none') {
52 $('div#cart').slideDown(500);
53 } else{
54 $('div#cart').slideUp(500);
55 }
56 return false;
57 });
58
59 /**
60 * Making the login "page" slide down when needed and up when not needed
61 */
62 $('a#login').click(function () {
63 if ($('div.login-div').css("display") == 'none') {
64 $('div.login-div').slideDown(500);
65 } else {
66 $('div.login-div').slideUp(500);
67 }
68 return false;
69 });
70
71 makeSearchEnter();
72 myOrdersLogInFirst();
73 goHome();
74};
75
76
77/**
78 * When logged in the login "page" slide up by it selv
79 */
80function makeLoginDivDisappear() {
81 $('div.login-div').mouseleave(function () {
82 $('div.login-div').slideUp(500);
83 });
84}
85
86/**
87 * Creating/managing the searchbar
88 */
89function makeSearchEnter() {
90 $(document).on('keyup', "#searchField", function (e) {
91 if (e.keyCode == 13) {
92 searchForItems();
93 }
94 });
95}
96
97/**
98 * In this method we search for items that are placed in the product list. The search is not
99 * constricted by search only by name.
100 */
101function searchForItems() {
102 var search = document.getElementById("searchField").value;
103 var shop = document.getElementById("mySelect").value;
104
105 $.post("/rest/shop/search", {search: search}, function (response) {
106 var items = JSON.parse(response);
107 addItemsToTable(items);
108 });
109
110 console.log(search);
111}
112
113/**
114 * The method creates af new customer, when doing this the method looks to see if both the
115 * createUserName and createUserPassword field are filled out if not is gives a errormessage.
116 * It then checks whether a user with name exists or not.
117 */
118function createCustomer() {
119 var createCustomerName = document.getElementById("createUserName").value;
120 var createCustomerPassword = document.getElementById("createUserPassword").value;
121
122 if (!(createCustomerName.length > 0 && createCustomerPassword.length > 0)) {
123 errorMessage("You must fill in both username and password!");
124 } else {
125 $.post("/rest/shop/createCustomer", {
126 username: createCustomerName,
127 password: createCustomerPassword
128 }, function (name) {
129 var login = document.getElementById("login-customer-submit-button");
130 var create = document.getElementById("create-customer-submit-button");
131 if (name == "true") {
132 errorMessage("Your are now a customer. Please Log in");
133 login.disabled = false;
134 create.disabled = true;
135 } else {
136 errorMessage("We could not create you. Username is taken");
137 login.disabled = false;
138 create.disabled = false;
139 }
140 });
141 }
142
143}
144
145
146/**
147 * The method logs in a existing customer, when doing this the method looks to see if both the
148 * createUserName and createUserPassword field are filled out, if not is gives a errormessage.
149 * It then checks if the name and password are correct if it is so then disables the login and create buttons
150 * and allows the customer to but items by calling the method buyItemsInCart.
151 */
152function loginCustomer() {
153 var customerName = document.getElementById("createUserName").value;
154 var customerPass = document.getElementById("createUserPassword").value;
155
156 if (!(customerName.length > 0 && customerPass.length > 0)) {
157 errorMessage("You must fill in both username and password!");
158 } else {
159 $.post("/rest/shop/loginCustomer", {
160 username: customerName,
161 password: customerPass
162 }, function (name) {
163 var login = document.getElementById("login-button");
164 var create = document.getElementById("create-customer-submit-button");
165 if (name == "true") {
166 errorMessage("You are now logged in.");
167 isLoggedIn = true;
168 create.disabled = true;
169 login.disabled = true;
170
171 buyItemsInCart();
172 } else {
173 errorMessage("We could not log you in. Did you type your username & Password correct?");
174 }
175
176 });
177
178 }
179
180
181}
182
183/**
184 * This method allows the customer to view previously bought items if the customer is logged in.
185 */
186function myOrdersLogInFirst() {
187 $(document).on('click', '#my-orders-button', function () {
188 if(isLoggedIn == false) {
189 alert("You have to log in before you can see your previous orders!");
190 } else{
191 hideTable();
192 getFormerBought();
193 }
194 });
195}
196
197
198function errorMessage(name) {
199 $("#login-message-error-area").text(name);
200}
201
202function buyMessage(text) {
203 $("#buy-items-message").text(text);
204}
205
206/**
207 * FIX ME !!!!!
208 * The method adds items to the cart when pressing the addtocart button, but only if the stock of the
209 * product is more than 0.
210 */
211function addToCartIfLoggedIn(itemID, itemStock) {
212 if (isLoggedIn == true) {
213 if (itemStock > 0) {
214 $.post("/rest/shop/addToCart", {itemID: itemID}, function (response) {
215 //Do nothing...
216 });
217
218 } else {
219 //DO WHAT?
220 }
221
222 }
223}
224
225/**
226 * Allos the customer to remove a certain item from the cart.
227 * @param itemID
228 */
229function removeFromCartIfLoggedIn(itemID) {
230 if (isLoggedIn == true) {
231
232 $.post("/rest/shop/removeFromCart", {itemID: itemID}, function (response) {
233 //Do nothing...
234 });
235
236 }
237}
238
239/**
240 * This method refills the product table, after a product is added to the cart and bought.
241 * This is done my calling the addItemsToTable and getShopNames methods.
242 */
243function updateStockList() {
244 sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
245 //This code is called when the server has sent its data
246 var items = JSON.parse(itemsText);
247 addItemsToTable(items);
248 getShopNames();
249 });
250}
251
252/**
253 * FIXME
254 * HVAD GØR DENNE HER?
255 */
256function updateStockListWithOutSelect() {
257 sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
258 //This code is called when the server has sent its data
259 var items = JSON.parse(itemsText);
260 addItemsToTable(items);
261 });
262}
263
264
265/**
266 * Der mangler at når du køber opdatere den stock.
267 * MANGLER MEGET
268 *
269 * In this method it is made possible to buy the items currently in the cart. When this is done the item
270 * is removed and can be viewed under my orders.
271 */
272function buyItemsInCart() {
273 $(document).on("click", "#buy-items-in-shopping-bag", function () {
274 console.log("Clicked by");
275 $.post("/rest/shop/buyItemsInCart", null, function (response) {
276 console.log("We got response");
277 buyMessage(response);
278 updateStockList();
279 });
280 });
281}
282
283
284/**
285 * This method depicts the entire proces of adding an item to the cart. The addItemButton increments the
286 * number of a certain product is wanted. This is only possible when the stockvalue of the product is more
287 * than 0, which is controlled by the method eow.
288 * Futhermore there is a remove button that does the opposite of the addbutton, the criteria for the
289 * removebutton is that the current number of items chosen are more than 0 or else it does nothing.
290 * The removebutton also removes the product from the cart it self by using the method removeFromQuickCart.
291 *
292 */
293var stockValue;
294function addToCartChange() {
295
296 $(".addItemButton").click(function () {
297
298 var $this = $(this);
299
300 var $counter = $this.closest('td').next('.itemsInCart').find('span');
301 var $number = parseInt($counter.text());
302 var $numberToAdd = 1;
303 var $stock = $this.closest('td').prev('td');
304 var $stockValue = parseInt($stock.text());
305 stockValue = $stockValue;
306 eow();
307
308 function eow(stockValue) {
309 if ($number < $stockValue || $stockValue > 0) {
310 $number = $number + $numberToAdd;
311 $stockValue--;
312 $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>");
313 $stock.replaceWith("<td>" + $stockValue + "</td>");
314
315
316 } else {
317
318 $number = $stockValue;
319 }
320 }
321
322 price();
323
324 });
325
326 $(".removeItemButton").click(function () {
327
328 var $this = $(this);
329
330 var $counter = $this.closest('td').prev('.itemsInCart').find('span');
331 var $number = parseInt($counter.text());
332 var $numberToRemove = 1;
333 var $stock = $this.closest('td').prev('td').prev('td').prev('td');
334 var $stockValue = parseInt($stock.text());
335
336 if ($number > 0) {
337 $number = $number - $numberToRemove;
338 $stockValue++;
339 $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>")
340 $stock.replaceWith("<td>" + $stockValue + "</td>")
341 } else {
342 $number = 0;
343 }
344
345 price();
346 removeFromQuickCart();
347
348 function removeFromQuickCart() {
349
350 var $name = $this.closest('td').prev('td').prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
351 var $nameText = $name.text();
352
353 var $thisName = '.' + $nameText.toString();
354
355 if($('#quickCart-products').find($thisName).length != 0){
356
357 var elements = $('#quickCart-products').find($thisName);
358 elements[0].parentNode.removeChild(elements[0]);
359 }
360
361 if($('#quickCart-products').find('p').length === 1){
362
363 var noItems = document.getElementById("no-items");
364 noItems.style.display = "block";
365 }
366 }
367
368 });
369
370}
371
372/**
373 * This method adds a given product to the cart.
374 * @param itemName
375 */
376function addToQuickCart(itemName) {
377 var para = document.createElement("p");
378 para.textContent = itemName;
379 para.className = itemName;
380 $('.quickCart-products').prepend(para);
381
382 var noItems = document.getElementById("no-items");
383 noItems.style.display = "none";
384}
385
386/**
387 * This method allows to see the shopnames of other shops
388 */
389function getShopNames() {
390 sendRequest("GET", "rest/shop/getShopNames", null, function (shopNames) {
391 var shops = JSON.parse(shopNames);
392 viewShops(shops);
393 });
394}
395
396/**
397 * This method creates a list containing all the names of shops one the server. It calls the method
398 * selectList which fills the product table with the product from the specific shop.
399 * @param shopNames
400 */
401function viewShops(shopNames) {
402 var scroller = document.getElementById("scroller");
403 var select = document.createElement("SELECT");
404 for (i = 0; i < shopNames.length; i++) {
405 (function (i) {
406 var shop = shopNames[i];
407
408 select.setAttribute("id", "mySelect");
409 scroller.appendChild(select);
410
411 var shopName = shop.shopName;
412 var shopID = shop.ShopID;
413
414 var option = document.createElement("option");
415 option.setAttribute("value", shopID);
416
417 var shoptext = document.createTextNode(shopName);
418 option.appendChild(shoptext);
419 select.appendChild(option);
420 }(i));
421 }
422 selectList();
423}
424
425
426/**
427 * The method returns the user home, meaning the product table is shown. The is possible to do by clicking the
428 * homeicon or the logo.
429 */
430function goHome() {
431 $(document).on('click', '#home-button', function () {
432 showTable();
433 hideFormerBought();
434 //updateStockListWithOutSelect();
435 });
436
437 $(document).on('click', '#logo', function () {
438
439 showTable();
440 hideFormerBought();
441 //updateStockListWithOutSelect();
442 });
443
444}
445
446/**
447 * FIXME
448 * ARBEJDER VI OS VÆK FRA DEN
449 *
450 * The method hides myOrders
451 */
452function hideFormerBought() {
453 var list = document.getElementById("my-orders");
454 list.style.display = "none";
455 list.style.visibility = "hidden";
456 list.style.marginTop = "150px";
457}
458
459/**
460 * FIXME
461 * ARBEJDER VI OS VÆK FRA DEN
462 *
463 * The method hides the product table
464 */
465function hideTable() {
466 var table = document.getElementById("table-div");
467 table.style.display = "none";
468 table.style.visibility = "hidden";
469}
470
471/**
472 * FIXME
473 * ARBEJDER VI OS VÆK FRA DEN
474 *
475 * The method shows the product table
476 */
477function showTable() {
478 var table = document.getElementById("table-div");
479 table.style.display = "table";
480 table.style.visibility = "visible";
481 table.style.width = "100%";
482}
483
484/**
485 * The method here shows the customers previously bought items.
486 */
487function getFormerBought() {
488 sendRequest("GET", "rest/shop/itemsBought", null, function (shopNames) {
489 var shops = JSON.parse(shopNames);
490 viewBoughtItems(shops);
491 });
492}
493
494/**
495 * In this method we fill the table containing the product that have been bought earlier. This is done by looping through
496 * all of the items and placing one item in each row and the itemID, itemName and so on in their respective table cells.
497 * @param items
498 */
499function viewBoughtItems(items) {
500 //Get the table body we we can add items to it
501 var tableBody = document.getElementById("itemTableBody-my-orders");
502 //Remove all contents of the table body (if any exist)
503 tableBody.innerHTML = "";
504
505
506 var totalAmountForCustomer = 0;
507 for (i = 0; i < items.length; i++) {
508 //GET ITEMS FROM SERVER WITH ID
509 (function (i) {
510 var itemFormerBought = items[i];
511
512 var tr = document.createElement("tr");
513
514 //TIME BOUGHT
515 var dateCell = document.createElement("td");
516 var timeStamp = new Date(parseInt(itemFormerBought.saleTime));
517 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
518 var year = timeStamp.getFullYear();
519 var month = months[timeStamp.getMonth() - 1];
520 var date = timeStamp.getDate();
521 var hours = timeStamp.getHours();
522 var minutes = timeStamp.getMinutes();
523 dateCell.textContent = date + ". " + month + ". " + hours + ": " + minutes;
524 tr.appendChild(dateCell);
525
526
527 // ITEM NAME
528 var nameCell = document.createElement("td");
529 nameCell.className = "itemName";
530 nameCell.textContent = itemFormerBought.item.itemName;
531 tr.appendChild(nameCell);
532
533 // ITEM URL / PICTURE
534 var picturecell = document.createElement("td");
535 var image = document.createElement('img');
536 image.className = "fishPictures";
537 image.src = itemFormerBought.item.itemURL;
538 image.alt = "FAIL";
539 picturecell.appendChild(image);
540 tr.appendChild(picturecell);
541
542
543 //ITEM DESCRIPTION
544 var htmlItemDescription = itemFormerBought.item.itemDescription;
545 var htmlConverter = document.createElement("td");
546 htmlConverter.innerHTML = htmlItemDescription;
547 tr.appendChild(htmlConverter);
548
549
550 // ITEM AMOUNT
551 var itemAmount = document.createElement("td");
552 var saleAmount = itemFormerBought.saleAmount;
553 itemAmount.textContent = saleAmount;
554 tr.appendChild(itemAmount);
555
556
557 // ITEM PRICE
558 var paraItemPrice = document.createElement("td");
559 var itemPrice = itemFormerBought.item.itemPrice;
560 paraItemPrice.textContent = itemPrice + " kr.";
561 tr.appendChild(paraItemPrice);
562
563
564 // TOTAL FOR THIS ITEM
565 var paraItemTotalAmount = document.createElement("td");
566 var totalForThisItem = (parseInt(itemPrice * saleAmount));
567 totalAmountForCustomer += totalForThisItem;
568 paraItemTotalAmount.textContent = totalForThisItem + " kr.";
569 tr.appendChild(paraItemTotalAmount);
570
571
572 //Append
573 tableBody.appendChild(tr);
574
575
576 }(i));
577 }
578
579 var div = document.getElementById("result-my-orders");
580 div.innerHTML ="";
581 var totalPricePara = document.createElement("p");
582 totalPricePara.textContent = "Total price for all your buys is " + totalAmountForCustomer;
583 div.appendChild(totalPricePara);
584}
585
586
587
588/**
589 * This method dictate which shops product table will be shown.
590 */
591function selectList() {
592 $('#mySelect').change(function () {
593 var shopID = $(this).val();
594 sendRequest("GET", "rest/shop/items/" + shopID, null, function (itemsText) {
595 //This code is called when the server has sent its data
596 var items = JSON.parse(itemsText);
597 addItemsToTable(items);
598 });
599
600 });
601}
602
603
604/**
605 * The method finds the sum of all the product currently in the cart.
606 */
607function price() {
608 var totalPriceSpan = document.getElementById("total-price"),
609 $totalPriceSpan = totalPriceSpan,
610 amount = document.getElementsByClassName("inputInCart"),
611 price = document.getElementsByClassName("price"),
612 parent = totalPriceSpan.parentNode,
613 tempDiv = document.createElement('div');
614
615 var totalPrice = 0;
616
617 for (var i = 0; i < amount.length; i++) {
618
619
620 var amountOfItem = parseInt(amount[i].innerText);
621 var priceOfEach = parseInt(price[i].innerText);
622
623 var priceOfAll = amountOfItem * priceOfEach;
624 var oldString = totalPrice.toString() + "kr.";
625
626 totalPrice += priceOfAll;
627 var totalPriceString = totalPrice.toString() + "kr.";
628 }
629
630 tempDiv.innerHTML = "<b class='total-price' id='total-price'>" + totalPriceString + "</b>";
631
632 var input = tempDiv.childNodes[0];
633
634 parent.replaceChild(input, totalPriceSpan);
635
636}
637
638
639/**
640 * In this method we fill the table containing our products. This is done by looping through
641 * all of the items and placing one item in each row and the itemID, itemName and so on in their respective table cells.
642 * @param items
643 */
644function addItemsToTable(items) {
645 //Get the table body we we can add items to it
646 var tableBody = document.getElementById("itemtablebody");
647 //Remove all contents of the table body (if any exist)
648 tableBody.innerHTML = "";
649
650 //Loop through the items from the server
651 for (var i = 0; i < items.length; i++) {
652 (function (i) {
653 var item = items[i];
654 //Create a new line for this item
655 var tr = document.createElement("tr");
656 tr.id = item.itemID;
657
658
659 // ITEM NAME
660 var nameCell = document.createElement("td");
661 nameCell.className = "itemName";
662 nameCell.textContent = item.itemName;
663 tr.appendChild(nameCell);
664
665 //Item URL / ITEM PICTURE
666 var picturecell = document.createElement("td");
667 var image = document.createElement('img');
668 image.className = "fishPictures";
669 image.src = item.itemURL;
670 image.alt = "FAIL";
671 picturecell.appendChild(image);
672 tr.appendChild(picturecell);
673
674 // ITEM PRICE
675 var priceCell = document.createElement("td");
676 priceCell.textContent = item.itemPrice;
677 priceCell.className = "price";
678 tr.appendChild(priceCell);
679
680 //ITEM DESCRIPTION
681 var htmlItemDescription = item.itemDescription;
682 var htmlConverter = document.createElement("td");
683 htmlConverter.innerHTML = htmlItemDescription;
684 tr.appendChild(htmlConverter);
685
686 // ITEM STOCK
687 var itemStock = document.createElement("td");
688 itemStock.textContent = item.itemStock;
689 tr.appendChild(itemStock);
690
691
692 // ADD TO CART
693 var addToCart = document.createElement("td");
694 var addToCartButton = document.createElement("BUTTON");
695 addToCartButton.className = "addItemButton";
696 var buttonText = document.createTextNode(" + ");
697 addToCartButton.appendChild(buttonText);
698 addToCart.appendChild(addToCartButton);
699 tr.appendChild(addToCart);
700
701 // ADD TO CART - FUNCTION
702 $(addToCartButton).click(function () {
703 addToQuickCart(item.itemName);
704 addToCartIfLoggedIn(item.itemID, item.itemStock);
705 });
706
707 // IN CART
708 var itemsInCart = document.createElement("td");
709 itemsInCart.className = "inCart";
710 var inputField = document.createElement("span");
711 inputField.textContent = "0";
712 inputField.className = "inputInCart";
713 itemsInCart.appendChild(inputField);
714 itemsInCart.className = "itemsInCart";
715 tr.appendChild(itemsInCart);
716
717 //REMOVE FROM CART
718 var removeFromCart = document.createElement("td");
719 var removeFromCartButton = document.createElement("BUTTON");
720 removeFromCartButton.className = "removeItemButton";
721 var buttonText = document.createTextNode(" - ");
722 removeFromCartButton.appendChild(buttonText);
723 removeFromCart.appendChild(removeFromCartButton);
724 tr.appendChild(removeFromCart);
725
726 // REMOVE FROM CART - BUTTON
727 $(removeFromCartButton).click(function () {
728 removeFromCartIfLoggedIn(item.itemID);
729 });
730
731
732 // ITEM ID
733 var itemID = document.createElement("td");
734 itemID.textContent = item.itemID;
735 tr.appendChild(itemID);
736
737 tableBody.appendChild(tr);
738 })(i);
739 }
740
741 addToCartChange();
742
743}
744
745
746/////////////////////////////////////////////////////
747// Code from slides
748/////////////////////////////////////////////////////
749
750/**
751 * A function that can add event listeners in any browser
752 */
753function addEventListener(myNode, eventType, myHandlerFunc) {
754 if (myNode.addEventListener)
755 myNode.addEventListener(eventType, myHandlerFunc, false);
756 else
757 myNode.attachEvent("on" + eventType,
758 function (event) {
759 myHandlerFunc.call(myNode, event);
760 });
761}
762
763var http;
764if (!XMLHttpRequest)
765 http = new ActiveXObject("Microsoft.XMLHTTP");
766else
767 http = new XMLHttpRequest();
768
769function sendRequest(httpMethod, url, body, responseHandler) {
770 http.open(httpMethod, url);
771 if (httpMethod == "POST") {
772 http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
773 }
774 http.onreadystatechange = function () {
775 if (http.readyState == 4 && http.status == 200) {
776 responseHandler(http.responseText);
777 }
778 };
779 http.send(body);
780}