Advertisement
Guest User

Untitled

a guest
Dec 13th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.24 KB | None | 0 0
  1. function startApp() {
  2. sessionStorage.clear();
  3.  
  4. $(document).on('ajaxStart', function () {
  5. $("#loadingBox").show()
  6. });
  7. $(document).on('ajaxStop', function () {
  8. $("#loadingBox").hide()
  9. });
  10.  
  11. function showInfo(message) {
  12. $("#infoBox > span").text(message);
  13. $("#infoBox").show();
  14. setTimeout(function () {
  15. $("#infoBox").hide()
  16. }, 3000)
  17. }
  18.  
  19. function attachBoxesEvents() {
  20. $('#errorBox').on('click', function () {
  21. $(this).hide()
  22. });
  23. $('#infoBox').on('click', function () {
  24. $(this).hide()
  25. })
  26. }
  27.  
  28. function showError(message) {
  29. $("#errorBox > span").text(message)
  30. $("#errorBox").show();
  31. setTimeout(function () {
  32. $("#errorBox").hide()
  33. }, 3000)
  34. }
  35.  
  36. function handleAjaxError(response) {
  37. let errorMessage = JSON.stringify(response);
  38.  
  39. if (response.readyState === 0) {
  40. let errorMessage = 'Cannot connect due to network error.'
  41. }
  42. if (response.responseJSON && response.responseJSON.description) {
  43. errorMessage = response.responseJSON.description;
  44. }
  45.  
  46. showError(errorMessage);
  47. }
  48.  
  49. const BASE_URL = 'https://baas.kinvey.com/';
  50. const APP_KEY = 'kid_Bk9LMjklE';
  51. const APP_SECRET = 'ba8a5b60c0224fceb24f93c1eeebf36a';
  52. const AUTH_HEADERS = {'Authorization': "Basic " + btoa(APP_KEY + ":" + APP_SECRET)};
  53.  
  54. function saveAuthInSession(userInfo) {
  55. sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
  56. sessionStorage.setItem('userId', userInfo._id);
  57. sessionStorage.setItem('userName', userInfo.username);
  58. }
  59.  
  60. function signInUser(res, message) {
  61. saveAuthInSession(res);
  62. showInfo(message);
  63. showHome();
  64. }
  65.  
  66. $('form').submit(function (event) {
  67. event.preventDefault();
  68. });
  69.  
  70. showHome();
  71. attachBoxesEvents();
  72.  
  73. $('#home').on('click', showHome);
  74. $('#showLogin').on('click', showLogin);
  75. $('#signIn').on('click', showLogin);
  76. $('#showRegister').on('click', showRegister);
  77. $('#signUp').on('click', showRegister);
  78. $('#submitRegister').on('click', submitRegister);
  79. $('#submitLogin').on('click', submitLogin);
  80. $('#logout').on('click', logout);
  81. $('#allListings').on('click', showCarListings);
  82. $('#createListing').on('click', showCreateListing);
  83. $('#submitListing').on('click', submitListing);
  84. $('#myListings').on('click', showMyListings);
  85.  
  86. function hideAllViews() {
  87. $('#allListings').hide();
  88. $('#myListings').hide();
  89. $('#createListing').hide();
  90. $('#profile').hide();
  91. $('#main').hide();
  92. $('#login').hide();
  93. $('#register').hide();
  94. $('#car-listings').hide();
  95. $('#create-listing').hide();
  96. $('#edit-listing').hide();
  97. $('#myCarListings').hide();
  98. $('#listingDetails').hide();
  99. }
  100.  
  101. function showHideLinks() {
  102. hideAllViews();
  103.  
  104. if (sessionStorage.getItem('authToken')){
  105. $('#allListings').show();
  106. $('#myListings').show();
  107. $('#createListing').show();
  108. $('#profile').show();
  109. $('#greeting').text(`Welcome, ${sessionStorage.getItem('userName')}`);
  110. }
  111. }
  112.  
  113. function showHome() {
  114. showHideLinks();
  115.  
  116. if (sessionStorage.getItem('authToken')){
  117. showCarListings();
  118. } else {
  119. $('#main').show();
  120. }
  121. }
  122.  
  123. function showLogin() {
  124. showHideLinks();
  125.  
  126. $('#login').show();
  127. }
  128.  
  129. function showRegister() {
  130. showHideLinks();
  131.  
  132. $('#register').show();
  133. }
  134.  
  135. function submitRegister() {
  136. let username = $('#usernameRegisterInput').val().trim();
  137. let password = $('#passwordRegisterInput').val().trim();
  138. let repeatPassword = $('#repeatPasswordRegisterInput').val().trim();
  139.  
  140. let usernameRegex = /[A-Za-z]{3,}$/;
  141. let passwordRegex = /[A-Za-z0-9]{6,}$/;
  142.  
  143. if (!usernameRegex.test(username.toString())) {
  144. showError('Username should be at least 3 characters long and contain only English alphabet letters.');
  145. } else if (!passwordRegex.test(password.toString())) {
  146. showError('Password should be at least 6 characters long and contain only English alphabet letters and digits.')
  147. } else if (password !== repeatPassword) {
  148. showError('Passwords do not match.')
  149. } else {
  150. $.ajax({
  151. method: "POST",
  152. url: BASE_URL + 'user/' + APP_KEY + '/',
  153. headers: AUTH_HEADERS,
  154. data: {username, password}
  155. }).then(function (res) {
  156. signInUser(res, 'Registration successful.');
  157. $('#formRegister').trigger('reset')
  158. }).catch(handleAjaxError);
  159. }
  160. }
  161.  
  162. function submitLogin() {
  163. let username = $('#usernameLoginInput').val().trim();
  164. let password = $('#passwordLoginInput').val().trim();
  165.  
  166. $.ajax({
  167. method: 'POST',
  168. url: BASE_URL + 'user/' + APP_KEY + '/login',
  169. headers: AUTH_HEADERS,
  170. data: {username, password}
  171. }).then(function (res) {
  172. signInUser(res, 'Login successful.');
  173. $('#formLogin').trigger('reset')
  174. }).catch(handleAjaxError)
  175. }
  176.  
  177. function logout() {
  178. $.ajax({
  179. method: 'POST',
  180. url: BASE_URL + 'user/' + APP_KEY + '/_logout',
  181. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')}
  182. }).catch(function (err) {
  183. console.log(err)
  184. });
  185.  
  186. sessionStorage.clear();
  187. showHome();
  188. showInfo("Logout successful");
  189. }
  190.  
  191. function showCarListings() {
  192. showHideLinks();
  193.  
  194. $.ajax({
  195. method: 'GET',
  196. url: BASE_URL + 'appdata/' + APP_KEY + '/cars?query={}&sort={"_kmd.ect": -1}',
  197. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
  198. }).then(function (res) {
  199. listResponse(res);
  200. }).catch(handleAjaxError);
  201.  
  202. function listResponse(res) {
  203. $('#listings').empty();
  204.  
  205. if (res.length === 0){
  206. $('#listings').append($('<p class="no-cars">No cars in database.</p>'));
  207. } else {
  208. for (const car of res) {
  209. let bigDiv = $('<div class="listing"></div>');
  210.  
  211. bigDiv.append($(`<p>${car.title}</p>
  212. <img src="${car.imageUrl}">
  213. <h2>Brand: ${car.brand}</h2>`));
  214.  
  215. let infoDiv = $('<div class="info"></div>');
  216. infoDiv.append($(`<div id="data-info">
  217. <h3>Seller: ${car.seller}</h3>
  218. <h3>Fuel: ${car.fuel}</h3>
  219. <h3>Year: ${car.year}</h3>
  220. <h3>Price: ${car.price} $</h3>
  221. </div>`));
  222.  
  223. let dataButtons = $('<div id="data-buttons"></div>');
  224. let ul = $('<ul></ul>');
  225.  
  226. let detailsButton = $('<li class="action"><a href="#" class="button-carDetails" id="detailsButton">Details</a></li>')
  227. .on('click', function () {
  228. showDetails(car);
  229. });
  230. let editButton = $('<li class="action"><a href="#" class="button-carDetails" id="editButton">edit</a></li>')
  231. .on('click', function () {
  232. showEditListing(car);;
  233. });
  234. let deleteButton = $('<li class="action"><a href="#" class="button-carDetails" id="deleteButton">delete</a></li>')
  235. .on('click', function () {
  236. deleteListing(car);
  237. });
  238.  
  239. if (sessionStorage.getItem('userName') === car.seller){
  240. ul.append(detailsButton);
  241. ul.append(editButton);
  242. ul.append(deleteButton);
  243. } else {
  244. ul.append(detailsButton);
  245. }
  246.  
  247. dataButtons.append(ul);
  248. infoDiv.append(dataButtons);
  249. bigDiv.append(infoDiv);
  250.  
  251. $('#listings').append(bigDiv);
  252. }
  253. }
  254.  
  255. $('#car-listings').show();
  256. }
  257. }
  258.  
  259. function showCreateListing() {
  260. showHideLinks();
  261.  
  262. $('#create-listing').show();
  263. }
  264.  
  265. function showMyListings() {
  266. showHideLinks();
  267. $('#myCars').empty();
  268.  
  269. $.ajax({
  270. method: 'GET',
  271. url: BASE_URL + 'appdata/' + APP_KEY + `/cars?query={"_acl.creator":"${sessionStorage.getItem("userId")}"}`,
  272. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
  273. }).then(function (res) {
  274. listResponse(res);
  275. }).catch(handleAjaxError);
  276.  
  277. function listResponse(res) {
  278. if (res.length === 0){
  279. $('#myCars').append('<p class="no-cars"> No cars in database.</p>');
  280. } else {
  281. for (const car of res) {
  282. let bigDiv = $('<div class="my-listing"></div>');
  283.  
  284. bigDiv.append($(`<p id="listing-title">${car.title}</p>
  285. <img src="${car.imageUrl}">
  286. <div class="listing-props">
  287. <h2>Brand: ${car.brand}</h2>
  288. <h3>Model: ${car.model}</h3>
  289. <h3>Year: ${car.year}</h3>
  290. <h3>Price: ${car.price}$</h3>
  291. </div>`));
  292.  
  293. let buttons = $('<div class="my-listing-buttons"></div>');
  294.  
  295. let detailsButton = $('<a href="#" class="my-button-list">Details</a>')
  296. .on('click', function () {
  297. showDetails(car);
  298. });
  299. let editButton = $('<a href="#" class="my-button-list">Edit</a>')
  300. .on('click', function () {
  301. showEditListing(car);
  302. });
  303. let deleteButton = $('<a href="#" class="my-button-list">Delete</a>')
  304. .on('click', function () {
  305. deleteListing(car);
  306. });
  307.  
  308. buttons.append(detailsButton);
  309. buttons.append(editButton);
  310. buttons.append(deleteButton);
  311.  
  312. bigDiv.append(buttons);
  313.  
  314. $('#myCars').append(bigDiv);
  315. }
  316. }
  317.  
  318. $('#myCarListings').show();
  319. }
  320. }
  321.  
  322. function showDetails(car) {
  323. showHideLinks();
  324.  
  325. $('#listingDetails').empty();
  326.  
  327. let bigDiv = $('<div class="my-listing-details">');
  328.  
  329. bigDiv.append($(`<p id="listing-title">${car.title}</p>
  330. <img src="${car.imageUrl}">
  331. <div class="listing-props">
  332. <h2>Brand: ${car.brand}</h2>
  333. <h3>Model: ${car.model}</h3>
  334. <h3>Year: ${car.year}</h3>
  335. <h3>Price: ${car.price}$</h3>
  336. </div>`));
  337.  
  338. if (car.seller === sessionStorage.getItem('userName')){
  339. let buttons = $('<div class="listings-buttons"></div>');
  340.  
  341. let editButton = $('<a href="#" class="button-list">Edit</a>')
  342. .on('click', function () {
  343. showEditListing(car);
  344. });
  345. let deleteButton = $('<a href="#" class="button-list">Delete</a>')
  346. .on('click', function () {
  347. deleteListing(car)
  348. });
  349.  
  350. buttons.append(editButton);
  351. buttons.append(deleteButton);
  352.  
  353. bigDiv.append(buttons);
  354. }
  355.  
  356. bigDiv.append($(`<p id="description-title">Description:</p>
  357. <p id="description-para">${car.description}</p>`));
  358.  
  359. $('#listingDetails').append(bigDiv);
  360. $('#listingDetails').show();
  361. }
  362.  
  363. function submitListing() {
  364. let seller = sessionStorage.getItem('userName');
  365. let title = $('#titleAdd').val();
  366. let description = $('#descriptionAdd').val();
  367. let imageUrl = $('#urlAdd').val();
  368. let brand = $('#brandAdd').val();
  369. let model = $('#modelAdd').val();
  370. let fuel = $('#fuelAdd').val();
  371. let year = $('#yearAdd').val();
  372. let price = $('#priceAdd').val();
  373.  
  374. $.ajax({
  375. method: 'POST',
  376. url: BASE_URL + 'appdata/' + APP_KEY + '/cars',
  377. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
  378. data: {seller, title, description, imageUrl, brand, model, fuel, year, price}
  379. }).then(function (event) {
  380. event.preventDefault();
  381. $('form #createForm').trigger("reset");
  382. showHome();
  383. showInfo("Listing created!");
  384. }).catch(handleAjaxError)
  385. }
  386.  
  387. function showEditListing(car) {
  388. showHideLinks();
  389.  
  390. $('#titleEdit').val(car.title);
  391. $('#descriptionEdit').val(car.description);
  392. $('#urlEdit').val(car.imageUrl);
  393. $('#brandEdit').val(car.brand);
  394. $('#modelEdit').val(car.model);
  395. $('#fuelEdit').val(car.fuel);
  396. $('#yearEdit').val(car.year);
  397. $('#priceEdit').val(car.price);
  398.  
  399. $('#edit-listing').show();
  400.  
  401. $('#editListingSubmit').on('click', function (event) {
  402. event.preventDefault();
  403. submitEditListing(car);
  404. });
  405. }
  406.  
  407. function submitEditListing(car) {
  408. let seller = sessionStorage.getItem('userName');
  409. let title = $('#titleEdit').val();
  410. let description = $('#descriptionEdit').val();
  411. let imageUrl = $('#urlEdit').val();
  412. let brand = $('#brandEdit').val();
  413. let model = $('#modelEdit').val();
  414. let fuel = $('#fuelEdit').val();
  415. let year = $('#yearEdit').val();
  416. let price = $('#priceEdit').val();
  417. let id = car._id;
  418.  
  419. $.ajax({
  420. method: 'PUT',
  421. url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + id,
  422. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
  423. data: {seller, title, description, imageUrl, brand, model, fuel, year, price}
  424. }).then(function (res) {
  425. showInfo("Successfully edited car.");
  426. $('#editForm').trigger("reset");
  427. showHome();
  428. }).catch(handleAjaxError)
  429. }
  430.  
  431. function deleteListing(car) {
  432. let id = car._id;
  433.  
  434. $.ajax({
  435. method: 'DELETE',
  436. url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + id,
  437. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authToken')},
  438. }).then(function () {
  439. showInfo("Car deleted.");
  440. showHome();
  441. }).catch(handleAjaxError)
  442. }
  443. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement