Advertisement
Guest User

Untitled

a guest
Aug 11th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.04 KB | None | 0 0
  1. function startApp() {
  2. const BASE_URL = 'https://baas.kinvey.com/';
  3. const APP_KEY = 'kid_ByxOPaqHQ';
  4. const APP_SECRET = '97e14cdfdb594cc68c391e21f8424583';
  5. const AUTH_HEADERS = {'Authorization': "Basic " + btoa(APP_KEY + ":" + APP_SECRET)};
  6.  
  7.  
  8. //NOTIFICATIONS
  9. $( document ).on('ajaxStart', function() {
  10. $("#loadingBox").show()
  11. });
  12. $( document ).on('ajaxStop', function() {
  13. $("#loadingBox").hide()
  14. });
  15.  
  16. function showInfo(message) {
  17. $("#infoBox > span").text(message);
  18. $("#infoBox").show();
  19. setTimeout(function () {
  20. $("#infoBox").hide()
  21. }, 3000)
  22. }
  23.  
  24. function attachBoxesEvents() {
  25. $('#errorBox').on('click', function () {
  26. $(this).hide()
  27. });
  28. $('#infoBox').on('click', function () {
  29. $(this).hide()
  30. })
  31. }
  32.  
  33. function showError(message) {
  34. $("#errorBox > span").text(message);
  35. $("#errorBox").show();
  36. // setTimeout(function () {
  37. // $("#errorBox").hide()
  38. // }, 3000)
  39. }
  40.  
  41.  
  42. attachBoxesEvents();
  43.  
  44. //VIEWS
  45. function hideAllViews() {
  46. $('#main').hide();
  47. $('#login').hide();
  48. $('#registerForm').hide();
  49. $('#createCars').hide();
  50. $('#editCars').hide();
  51. $('#myCarListings').hide();
  52. $('#myCars').hide();
  53. $('#listDetails').hide();
  54. $('#car-listings').hide();
  55. $('#carListings').hide();
  56. }
  57.  
  58. function showHideLinks() {
  59. hideAllViews();
  60. if (sessionStorage.getItem('authtoken') === null){
  61. $('#main').show();
  62. $('#allListings').hide();
  63. $('#carListings').hide();
  64. $('#createListings').hide();
  65. $('#car-listings').hide();
  66. $('#profile').hide();
  67. $('#myListings').hide();
  68. } else {
  69. $('#main').hide();
  70. $('#allListings').show();
  71. $('#carListings').hide();
  72. $('#car-listings').show();
  73. $('#createListings').show();
  74. $('#profile').show();
  75. $('#myListings').show();
  76. $('#welcm').text(`Welcome ${sessionStorage.getItem('username')}`);
  77. listCars();
  78. }
  79. }
  80.  
  81. //USER FUNCTIONS
  82. function signInUser(res, message) {
  83. saveAuthInSession(res);
  84. showHideLinks();
  85. showInfo(message)
  86. }
  87.  
  88. function saveAuthInSession(userInfo) {
  89. sessionStorage.setItem('authtoken', userInfo._kmd.authtoken);
  90. sessionStorage.setItem('username', userInfo.username);
  91. sessionStorage.setItem('userId', userInfo._id);
  92. sessionStorage.setItem('acl', userInfo._acl.creator);
  93. console.log(userInfo._acl.creator);
  94. }
  95.  
  96. //ATTACH EVENTS
  97. function attachEvents() {
  98. $('#home').on('click', function (event) {
  99. event.preventDefault();
  100. hideAllViews();
  101. showHideLinks();
  102. });
  103.  
  104. $('#loginButton').on('click', function (event) {
  105. event.preventDefault();
  106. hideAllViews();
  107. $('#login').show();
  108. });
  109.  
  110. $('#registerButton').on('click', function (event) {
  111. event.preventDefault();
  112. hideAllViews();
  113. $('#registerForm').show();
  114. });
  115.  
  116. $('#registerUser').on('click', function (event) {
  117. event.preventDefault();
  118. registerUser();
  119. });
  120.  
  121. $('#signUpBtn').on('click', function (event) {
  122. event.preventDefault();
  123. hideAllViews();
  124. $('#registerForm').show();
  125. });
  126.  
  127. $('#signInBtn').on('click', function (event) {
  128. event.preventDefault();
  129. hideAllViews();
  130. $('#login').show();
  131. });
  132.  
  133. $('#logout').on('click', function (event) {
  134. event.preventDefault();
  135. logout();
  136. });
  137.  
  138. $('#logUserBtn').on('click', function (event) {
  139. event.preventDefault();
  140. login();
  141. });
  142.  
  143. $('#allListings').on('click', function (event) {
  144. event.preventDefault();
  145. hideAllViews();
  146. $('#car-listings').show();
  147. listCars();
  148. });
  149.  
  150. $('#createListings').on('click', function (event) {
  151. event.preventDefault();
  152. hideAllViews();
  153. $('#createCars').show();
  154. });
  155.  
  156. $('#createBtn').on('click', function (event) {
  157. event.preventDefault();
  158. createCar();
  159. });
  160.  
  161. $('#editHome').on('click', function (event) {
  162. event.preventDefault();
  163. editCar();
  164. });
  165.  
  166. $('#detailsEdit').on('click', function (event) {
  167. event.preventDefault();
  168. loadEditCar();
  169. });
  170.  
  171. $('#myListings').on('click', function (event) {
  172. event.preventDefault();
  173. hideAllViews();
  174. $('#carListings').show();
  175. getMyCarListing();
  176. })
  177. }
  178.  
  179. //AJAX
  180. function registerUser() {
  181. let username = $('#registerForm input[name="username"]').val();
  182. let password = $('#registerForm input[name="password"]').val();
  183. let checkPass = $('#registerForm input[name="repeatPass"]').val();
  184. let regexUsername = /([a-zA-Z])+/;
  185. let passwordRegex = /([a-zA-Z0-9]){6,}/;
  186.  
  187. if(username.length >= 3 && regexUsername.exec(username) && password.length >= 6 && passwordRegex.exec(password) && password === checkPass) {
  188. $.ajax({
  189. method: "POST",
  190. url: BASE_URL + 'user/' + APP_KEY + '/',
  191. headers: AUTH_HEADERS,
  192. data: {username, password}
  193. }).then(function (res) {
  194. $('#registerForm').trigger('reset');
  195. signInUser(res, 'User registration successful.');
  196. }).catch(handleAjaxError)
  197. } else if (username.length < 3){
  198. showError('Username should be at least 3 characters long.')
  199. } else if (!regexUsername.exec(username)){
  200. showError('Username should contain only english alphabet letters.')
  201. } else if (!passwordRegex.exec(password)){
  202. showError('Password should contain only english letters and digits.')
  203. } else if(password.length < 6){
  204. showError('Password should be at least 6 characters long.')
  205. } else if(password !== checkPass){
  206. showError('Passwords do not match!')
  207. }
  208. }
  209.  
  210. function login() {
  211. let username = $('#formLogin input[name="username"]').val();
  212. let password = $('#formLogin input[name="password"]').val();
  213.  
  214. $.ajax({
  215. method: 'POST',
  216. url: BASE_URL + 'user/' + APP_KEY + '/login',
  217. headers: AUTH_HEADERS,
  218. data: {username, password}
  219. }).then(function (res) {
  220. signInUser(res, 'Login successful.');
  221. $('#formLogin').trigger('reset')
  222. }).catch(handleAjaxError);
  223.  
  224. }
  225.  
  226.  
  227. function logout() {
  228. $.ajax({
  229. method: 'POST',
  230. url: BASE_URL + 'user/' + APP_KEY + '/_logout',
  231. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')}
  232. }).catch(handleAjaxError);
  233. sessionStorage.clear();
  234. showInfo("Logout successful");
  235. showHideLinks();
  236. }
  237.  
  238. function listCars() {
  239. $('#listings').empty();
  240. $.ajax({
  241. method: 'GET',
  242. url: BASE_URL + 'appdata/' + APP_KEY + '/cars?query={}&sort={"_kmd.ect": -1}',
  243. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')}
  244. }).then(function (res) {
  245. displayCars(res)
  246. }).catch(handleAjaxError);
  247. }
  248.  
  249. function handleAjaxError(response) {
  250. console.log(response);
  251. let errorMsg = JSON.stringify(response);
  252. if (response.readyState === 0)
  253. errorMsg = "Cannot connect due to network error.";
  254. if (response.responseJSON && response.responseJSON.description)
  255. errorMsg = response.responseJSON.description;
  256. showError(errorMsg)
  257. }
  258.  
  259. function displayCars(cars) {
  260. if(cars.length === 0){
  261. $('.no-cars').show();
  262. } else {
  263. $('.no-cars').hide();
  264. for (let car of cars) {
  265. let div = $('<div class="listing">');
  266. div.append($('<p>').text(`${car.title}`));
  267. div.append($('<img>').attr('src', `${car.imageUrl}`));
  268. div.append($('<h2>').text(`Brand: ${car.brand}`));
  269. let classInfo = ($('<div class="info">'));
  270. classInfo.append($('<div id="data-info">').append($('<h3>').text(`Seller: ${car.seller}`)).append($('<h3>').text(`Fuel: ${car.fuel}`)).append($(`<h3>`).text(`Year: ${car.year}`)).append($('<h3>').text(`Price: ${car.price}$`)));
  271. let dataButtons = $('<div id="data-buttons">');
  272. if(car._acl.creator === sessionStorage.getItem('acl')){
  273. let ul = $('<ul>');
  274. ul.append($('<li class="action">').append($('<a href="#" class="button-carDetails">').text('Details').on('click', function (event) {
  275. event.preventDefault();
  276. viewDetails(car);
  277. })));
  278. ul.append($('<li class="action">').append($('<a href="#" class="button-carDetails">').text('Edit').on('click', function (event) {
  279. event.preventDefault();
  280. loadEditCar(car);
  281. })));
  282. ul.append($('<li class="action">').append($('<a href="#" class="button-carDetails">').text('Delete').on('click', function (event) {
  283. event.preventDefault();
  284. removeCarFromHomePage(car);
  285. })));
  286. dataButtons.append(ul);
  287. classInfo.append(dataButtons);
  288. } else {
  289. classInfo.append(dataButtons);
  290. classInfo.append($('<div id="data-buttons">').append($('<ul>').append($('<li class="action">').append($('<a href="#" class="button-carDetails">').text('Details').on('click', function (event) {
  291. event.preventDefault();
  292. viewDetails(car);
  293. })))))
  294. }
  295. div.append(classInfo);
  296. $('#listings').append(div);
  297. }
  298. }
  299. }
  300.  
  301. function viewDetails(car) {
  302. hideAllViews();
  303. $('#listDetails').show();
  304. $('#listDetails').empty();
  305. let div = $('<div class="my-listing-details">');
  306. div.append($('<p id="auto-title">').text(`${car.title}`));
  307. div.append($('<img>').attr('src', `${car.imageUrl}`));
  308.  
  309. let secondDiv = $('<div class="listing-props">');
  310. secondDiv.append($('<h2>').text(`Brand: ${car.brand}`));
  311. secondDiv.append($('<h2>').text(`Model: ${car.model}`));
  312. secondDiv.append($('<h2>').text(`Year: ${car.year}`));
  313. secondDiv.append($('<h2>').text(`Fuel: ${car.fuel}`));
  314. secondDiv.append($('<h2>').text(`Price: ${car.price}$`));
  315. div.append(secondDiv);
  316. if(car._acl.creator === sessionStorage.getItem('acl')){
  317. let thirdDiv = $('<div class="listings-buttons">');
  318. thirdDiv.append($('<a href="#" class="button-list">').text('Edit').on('click', function (event) {
  319. event.preventDefault();
  320. loadEditCar(car);
  321. }));
  322. thirdDiv.append($('<a href="#" class="button-list">').text('Delete').on('click', function (event) {
  323. event.preventDefault();
  324. removeCarFromHomePage(car);
  325. }));
  326. div.append(thirdDiv);
  327. }
  328. div.append($('<p id="description-title">').text('Description'));
  329. div.append($('<p id="description-para">').text(`${car.description}`));
  330. $('#listDetails').append(div);
  331. }
  332.  
  333. function createCar() {
  334. let title = $('#createCars input[name="title"]').val();
  335. let description = $('#createCars input[name="description"]').val();
  336. let brand = $('#createCars input[name="brand"]').val();
  337. let model = $('#createCars input[name="model"]').val();
  338. let year = $('#createCars input[name="year"]').val();
  339. let imageUrl = $('#createCars input[name="imageUrl"]').val();
  340. let fuel = $('#createCars input[name="fuelType"]').val();
  341. let price = $('#createCars input[name="price"]').val();
  342. let seller = sessionStorage.getItem('username');
  343.  
  344. if(title.length > 33 || !title){
  345. showError('The title is required but its length must not exceed 33 characters!')
  346. } else if(description.length > 450 || description < 30){
  347. showError('The description length must not exceed 450 characters and should be at least 30!')
  348. } else if(brand.length > 11 || !brand){
  349. showError('The brand is required but its length must not exceed 11 characters!')
  350. } else if(fuel.length > 11 || !fuel){
  351. showError('The fuel is required but its length must not exceed 11 characters!')
  352. } else if(model.length > 11 || !model){
  353. showError('The model is required but its length must not exceed 11 characters!')
  354. } else if(year.length !== 4){
  355. showError('The year must be only 4 chars long!')
  356. } else if(price > 1000000 || !price){
  357. showError('The price cannot be null or more than 1000000$!')
  358. } else if(!imageUrl.startsWith('http') || !imageUrl){
  359. showError('There should be image and its url should always start with “http”')
  360. } else {
  361. $.ajax({
  362. method: "POST",
  363. url: BASE_URL + 'appdata/' + APP_KEY + '/cars',
  364. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')},
  365. data: {title, description, brand, model, year, imageUrl, fuel, price, seller}
  366. }).then(function (res) {
  367. showInfo('Listing created.');
  368. showHideLinks();
  369. $('#createCars').trigger('reset');
  370. }).catch(handleAjaxError)
  371. }
  372. }
  373.  
  374. function loadEditCar(car) {
  375. hideAllViews();
  376. $('#editCars').show();
  377. $('#editCars input[name="carId"]').val(car._id);
  378. $('#editCars input[name="title"]').val(car.title);
  379. $('#editCars input[name="description"]').val(car.description);
  380. $('#editCars input[name="brand"]').val(car.brand);
  381. $('#editCars input[name="model"]').val(car.model);
  382. $('#editCars input[name="year"]').val(car.year);
  383. $('#editCars input[name="imageUrl"]').val(car.imageUrl);
  384. $('#editCars input[name="fuelType"]').val(car.fuel);
  385. $('#editCars input[name="price"]').val(car.price);
  386. }
  387.  
  388. function editCar() {
  389. let title = $('#editCars input[name="title"]').val();
  390. let description = $('#editCars input[name="description"]').val();
  391. let brand = $('#editCars input[name="brand"]').val();
  392. let model = $('#editCars input[name="model"]').val();
  393. let year = $('#editCars input[name="year"]').val();
  394. let imageUrl = $('#editCars input[name="imageUrl"]').val();
  395. let fuel = $('#editCars input[name="fuelType"]').val();
  396. let price = $('#editCars input[name="price"]').val();
  397. let seller = sessionStorage.getItem('username');
  398. let id = $('#editCars input[name="carId"]').val();
  399.  
  400. if(title.length > 33 || !title){
  401. showError('The title is required but its length must not exceed 33 characters!')
  402. } else if(description.length > 450 || description < 30){
  403. showError('The description length must not exceed 450 characters and should be at least 30!')
  404. } else if(brand.length > 11 || !brand){
  405. showError('The brand is required but its length must not exceed 11 characters!')
  406. } else if(fuel.length > 11 || !fuel){
  407. showError('The fuel is required but its length must not exceed 11 characters!')
  408. } else if(model.length > 11 || !model){
  409. showError('The model is required but its length must not exceed 11 characters!')
  410. } else if(year.length !== 4){
  411. showError('The year must be only 4 chars long!')
  412. } else if(price > 1000000 || !price){
  413. showError('The price cannot be null or more than 1000000$!')
  414. } else if(!imageUrl.startsWith('http') || !imageUrl){
  415. showError('There should be image and its url should always start with “http”')
  416. } else {
  417. $.ajax({
  418. method: 'PUT',
  419. url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + id,
  420. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')},
  421. data: {title, description, brand, model, year, imageUrl, fuel, price, seller}
  422. }).then(function (res) {
  423. showInfo(`Listing ${title} updated.`);
  424. showHideLinks();
  425. }).catch(handleAjaxError)
  426. }
  427. }
  428.  
  429. function removeCarFromHomePage(car) {
  430. $.ajax({
  431. method: "DELETE",
  432. url: BASE_URL + 'appdata/' + APP_KEY + '/cars/' + car._id,
  433. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')},
  434. }).then(function (res) {
  435. showInfo('Car deleted.');
  436. showHideLinks();
  437. }).catch(handleAjaxError)
  438. }
  439.  
  440.  
  441. function getMyCarListing() {
  442. $.ajax({
  443. method: 'GET',
  444. url: BASE_URL + 'appdata/' + APP_KEY + `/cars?query={"seller":"${sessionStorage.getItem('username')}"}&sort={"_kmd.ect": -1}`,
  445. headers: {Authorization: 'Kinvey ' + sessionStorage.getItem('authtoken')},
  446. }).then(function (res) {
  447. hideAllViews();
  448. appendMyCars(res);
  449. }).catch(handleAjaxError)
  450. }
  451.  
  452. function appendMyCars(cars) {
  453. $('#carListings').show();
  454. $('#myCars').empty();
  455. if(cars.length === 0){
  456. $('#myCars').append($('<p class="no-cars">').text(" No cars in database."))
  457. } else {
  458.  
  459. for (let car of cars) {
  460. let div = $('<div class="my-listing">');
  461. div.append($('<p id="listing-title">').text(`${car.title}`));
  462. div.append($('<img>').attr('src', `${car.imageUrl}`));
  463.  
  464. let secondDiv = $('<div class="listing-props">');
  465. secondDiv.append($('<h2>').text(`Brand: ${car.brand}`));
  466. secondDiv.append($('<h3>').text(`Model: ${car.model}`));
  467. secondDiv.append($('<h3>').text(`Year: ${car.year}`));
  468. secondDiv.append($('<h3>').text(`Price: ${car.price}`));
  469.  
  470. let thirdDiv = $('<div class="my-listing-buttons">');
  471. thirdDiv.append($('<a href="#" class="my-button-list">').text('Details').on('click', function () {
  472. viewDetails(car);
  473. }));
  474. thirdDiv.append($('<a href="#" class="my-button-list">').text('Edit').on('click', function () {
  475. loadEditCar(car);
  476. }));
  477. thirdDiv.append($('<a href="#" class="my-button-list">').text('Delete').on('click', function () {
  478. removeCarFromHomePage(car);
  479. }));
  480. div.append(secondDiv);
  481. div.append(thirdDiv);
  482. $('#myCars').append(div);
  483. }
  484. }
  485. $('#myCars').show();
  486. }
  487.  
  488. showHideLinks();
  489. attachEvents();
  490. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement