Advertisement
Guest User

Untitled

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