-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
497 lines (416 loc) · 14.9 KB
/
scripts.js
File metadata and controls
497 lines (416 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
const maxSliderResults = 21; // max number of movies per slider
const imgPerSection = 7; // number of images per slider section
const maxResultPages = 4; // max fetch-result pages
const categoryOrder = "r"; // (a)lphabetic / (r)andom
const catPerLoad = 3; // number of categories at start
// ---------------------------------------------------------------------
// Setup Top Movie Head
// ---------------------------------------------------------------------
function createTopMovieHead(movieId) {
/**
* Creates the Head Section for the Top Rated Movie.
*/
movieEndPoint = `titles/${movieId}`;
fetchData(movieEndPoint).then((movieObject) => {
let imageContainer = document.createElement("img");
imageContainer.id = "movieImage";
imageContainer.src = movieObject.image_url;
let movieTitle = document.createElement("h1");
movieTitle.innerText = movieObject.title;
let playButton = document.createElement("a");
playButton.href = "#/";
playButton.innerHTML = '<p id="playButton">Play</p>';
let description = document.createElement("p");
description.id = "description";
description.innerText = movieObject.description;
let topMovieBox = document.querySelector(".movieTitleBox");
topMovieBox.append(imageContainer, movieTitle, playButton, description);
});
}
// ---------------------------------------------------------------------
// Setup Imagesliders
// ---------------------------------------------------------------------
// preventing the window from scrolling to the Position of the link-tag.
let winX = null;
let winY = null;
window.addEventListener("scroll", function () {
if (winX !== null && winY !== null) {
window.scrollTo(winX, winY);
winX = null;
winY = null;
}
});
function disableWindowScroll() {
winX = window.scrollX;
winY = window.scrollY;
}
// ------------------ creator for a new imageslider -------------------
function createImageSlider(title, movieObjectList, containerId) {
/**
* Takes two Arguments, Creates a new Imageslider,
* and appends it at the end of the <div> with the id: sliderArea.
*
* Args:
* title: String
* movieObjectlist: array - array of movie-objects in json format.
*/
const titleNoSpaces = title.replaceAll(" ", "_");
let numberOfSections = Math.ceil(movieObjectList.length / imgPerSection);
let movieListChunks = sliceIntoChunks(movieObjectList, imgPerSection);
let newHeader = document.createElement("h2");
newHeader.className = "sectionHeader";
newHeader.innerText = title;
let sectionIndicator = document.createElement("ul");
sectionIndicator.className = "sectionIndicator";
sectionIndicator.id = titleNoSpaces;
sectionIndicator.style.visibility = "hidden";
for (let i = 0; i < numberOfSections; i++) {
let li = document.createElement("li");
li.className = "";
sectionIndicator.appendChild(li);
}
sectionIndicator.firstElementChild.className = "active";
let sliderHeadline = document.createElement("div");
sliderHeadline.className = "flexProperties";
sliderHeadline.appendChild(newHeader);
sliderHeadline.appendChild(sectionIndicator);
let divScrollbar = document.createElement("div");
divScrollbar.classList.add("categoryScrollbar");
divScrollbar.style.gridTemplateColumns = `repeat(${numberOfSections}, 100%)`;
divScrollbar.addEventListener("mouseover", function () {
document.getElementById(titleNoSpaces).style.visibility = "visible";
});
divScrollbar.addEventListener("mouseout", function () {
document.getElementById(titleNoSpaces).style.visibility = "hidden";
});
let sectionNumber = 1;
for (const chunk of movieListChunks) {
window["section" + sectionNumber] = document.createElement("section");
let section = window["section" + sectionNumber];
section.id = `section${sectionNumber}${title}`;
section.style.gridTemplateColumns = `repeat(${imgPerSection}, auto)`;
// if a section is incomplete the thumbnails will be aligned left to right
// else they will have an even space in between
if (chunk.length < imgPerSection) {
section.style.justifyContent = "flex-start";
} else {
section.style.justifyContent = "space-between";
}
let arrowLeft = document.createElement("a");
arrowLeft.textContent = "‹";
arrowLeft.onmousedown = function () {
disableWindowScroll();
const newContent = highlightLastSectionIndicator(
document.querySelectorAll(`#${titleNoSpaces} li`)
);
let ul = document.getElementById(`${titleNoSpaces}`);
ul.innerHTML = "";
for (const li of newContent) {
ul.appendChild(li);
}
};
arrowLeft.href = `#section${lastSectionNumber(
sectionNumber,
numberOfSections
)}${title}`;
arrowLeft.classList.add("arrowButton", "leftArrow");
section.appendChild(arrowLeft);
for (const movieObject of chunk) {
let thumbnail = document.createElement("div");
thumbnail.classList.add("movieImages");
let link = document.createElement("a");
link.href = "#/";
link.addEventListener("click", () => displayModal(movieObject.id));
let img = document.createElement("img");
img.src = movieObject.image_url;
img.onload = () => link.appendChild(img);
img.onerror = () => {
let titleText = document.createElement("h3");
titleText.className = "noImageTitle";
titleText.innerText = movieObject.title;
let infoText = document.createElement("h4");
infoText.className = "noImageTitle";
infoText.innerText = "No image\navailable";
link.append(titleText, infoText);
link.id = "noThumbnail";
};
thumbnail.appendChild(link);
section.appendChild(thumbnail);
}
let arrowRight = document.createElement("a");
arrowRight.textContent = "›";
arrowRight.onmousedown = function () {
disableWindowScroll();
const newContent = highlightNextSectionIndicator(
document.querySelectorAll(`#${titleNoSpaces} li`)
);
let ul = document.getElementById(`${titleNoSpaces}`);
ul.innerHTML = "";
for (const li of newContent) {
ul.appendChild(li);
}
};
arrowRight.href = `#section${nextSectionNumber(
sectionNumber,
numberOfSections
)}${title}`;
arrowRight.classList.add("arrowButton", "rightArrow");
section.appendChild(arrowRight);
divScrollbar.appendChild(section);
sectionNumber += 1;
}
let newSlider = document.getElementById(containerId);
newSlider.appendChild(sliderHeadline);
newSlider.appendChild(divScrollbar);
// document.getElementById(containerId).appendChild(newSlider);
}
function nextSectionNumber(sectionNumber, numberOfSections) {
if (sectionNumber == numberOfSections) {
return 1;
} else {
return sectionNumber + 1;
}
}
function lastSectionNumber(sectionNumber, numberOfSections) {
if (sectionNumber == 1) {
return numberOfSections;
} else {
return sectionNumber - 1;
}
}
function highlightNextSectionIndicator(nodeListElements) {
let listElements = Array.from(nodeListElements);
listElements.unshift(listElements.pop());
return listElements;
}
function highlightLastSectionIndicator(nodeListElements) {
let listElements = Array.from(nodeListElements);
listElements.push(listElements.shift());
return listElements;
}
// ---------------------------------------------------------------------
// Get Data from the Api
// ---------------------------------------------------------------------
const baseUrl = "http://localhost:8000/api/v1/";
async function fetchData(endpoint) {
/**
* Takes an endpoint as an argurment, and returns the response data
* in a json format.
*
* If an error occures, it will be loged in the Console.
*/
data = await fetch(baseUrl + endpoint)
.then((response) => response.json())
.catch((error) => console.log("An error has occurred!", error));
return data;
}
// ---------------------------------------------------------------------
// Fetch all categories
// ---------------------------------------------------------------------
let categoryNames = ["Top Rated Movies"];
let endPoint = "genres/";
function fetchAllCategories() {
fetchCategoryNames(endPoint);
fetchData(endPoint).then((data) => {
if (data.next) {
endPoint = data.next.split("v1/")[1];
fetchAllCategories();
} else {
createNextSlider();
if (categoryOrder == "r") {
categoryNames.sort((a, b) => 0.5 - Math.random());
}
for (let i = 0; i < catPerLoad; i++) {
createNextSlider();
}
}
});
}
function fetchCategoryNames(categoryPage) {
fetchData(categoryPage).then((data) => {
for (const result of data.results) {
categoryNames.push(result.name);
}
});
}
// ---------------------------------------------------------------------
// Creator Top Rated Movies and the next available Category
// ---------------------------------------------------------------------
class CategorySlider {
constructor(categoryName, id) {
this.movieObjects = [];
this.pagesChecked = 0;
this.categoryName = categoryName;
this.id = id;
if (this.categoryName == "Top Rated Movies") {
this.endPoint = `titles?sort_by=-imdb_score`;
} else {
this.endPoint = `titles?genre=${this.categoryName}&sort_by=-imdb_score`;
}
this.fetchCategory();
}
fetchCategory() {
this.fetchMovieObjects(this.endPoint);
fetchData(this.endPoint).then((data) => {
if (data.next && this.pagesChecked <= maxResultPages) {
this.endPoint = data.next.split("v1/")[1];
this.fetchCategory();
this.pagesChecked += 1;
} else {
if (this.movieObjects.length >= imgPerSection) {
this.movieObjects = this.movieObjects.splice(0, maxSliderResults);
createImageSlider(this.categoryName, this.movieObjects, this.id);
}
}
});
}
fetchMovieObjects(currentCategoryPage) {
fetchData(currentCategoryPage)
.then((data) => data.results)
.then((results) => {
if (this.categoryName == "Top Rated Movies" && this.pagesChecked == 0) {
createTopMovieHead(results[0].id);
}
for (const result of results) {
this.movieObjects.push(result);
}
});
}
}
idNumber = 0;
function createNextSlider() {
idNumber += 1;
let newSlider = document.createElement("div");
newSlider.className = "imageSlider";
const id = `imageSlider_${idNumber}`;
newSlider.id = id;
document.getElementById("sliderArea").appendChild(newSlider);
new CategorySlider(categoryNames.shift(), id);
}
fetchAllCategories();
// add new category slider if user reached end of page
window.onscroll = function () {
if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {
for (let i = 0; i < catPerLoad; i++) {
if (categoryNames) {
createNextSlider();
}
}
}
};
// ---------------------------------------------------------------------
// Setup Modal Window
// ---------------------------------------------------------------------
// key = gets Displayed at the left side of th detail section.
// value = key the respective detail within the Api.
const detailsToDisplay = {
Genres: "genres",
"Release date": "date_published",
"MPAA rating": "rated",
"IMDb score": "imdb_score",
Director: "directors",
"List of actors": "actors",
Duration: "duration",
"Country of origin": "countries",
"Box Office result": "worldwide_gross_income",
"Movie summary": "long_description",
};
function displayModal(movieId) {
/**
* Takes a movie-ID and displayes the modal window
* with detailed information to the movie.
*/
setupModalContent(movieId);
let modalWindow = document.getElementById("modalWindow");
modalWindow.style.visibility = "visible";
}
function setupModalContent(movieId) {
/**
* Takes a movie-ID and creates the content inside the modal window.
*/
const endPoint = `titles/${movieId}`;
fetchData(endPoint).then((data) => {
let contentArea = document.querySelector(".modal");
let modalImage = document.createElement("img");
modalImage.src = data.image_url;
modalImage.onload = () => contentArea.appendChild(modalImage);
modalImage.onerror = () => {
let infoText = document.createElement("h3");
infoText.id = "noImageInfo";
infoText.innerText = "No image\navailable";
contentArea.appendChild(infoText);
};
let modalTitle = document.createElement("h1");
modalTitle.innerText = data.title;
let modalOriginalTitle = document.createElement("h2");
modalOriginalTitle.innerText = `(${data.original_title})`;
contentArea.append(modalTitle, modalOriginalTitle);
for (const key in detailsToDisplay) {
let container = document.createElement("div");
let p1 = document.createElement("p");
let p2 = document.createElement("p");
let detail = data[detailsToDisplay[key]];
if (!detail) {
detail = "Not available";
}
p1.innerText = `${key}: `;
if (key == "Duration") {
detail = minutesToHHMM(detail);
}
if (key == "Box Office result" && detail != "Not available") {
detail = detail.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (data.budget_currency) {
detail = detail + " " + data.budget_currency;
} else {
detail = detail + " USD";
}
}
p2.innerText = `${detail}`;
container.appendChild(p1);
container.appendChild(p2);
contentArea.appendChild(container);
}
let closeButton = document.createElement("a");
closeButton.href = "#/";
closeButton.id = "closeModal";
closeButton.innerText = "X";
closeButton.addEventListener("click", () => closeModal());
contentArea.appendChild(closeButton);
});
}
// Modal window also closes by click outside of it
let outsideModal = document.getElementById("modalWindow");
let modalArea = document.querySelector(".modal");
outsideModal.addEventListener("click", (event) => {
let isClickInside = modalArea.contains(event.target);
if (!isClickInside) {
closeModal();
}
});
function closeModal() {
/**
* Hides the modal window and clears it's content.
*/
document.getElementById("modalWindow").style.visibility = "hidden";
document.querySelector(".modal").innerHTML = "";
}
// ---------------------------------------------------------------------
// Helper Functions
// ---------------------------------------------------------------------
function sliceIntoChunks(arr, chunkSize) {
const res = [];
for (let i = 0; i < arr.length; i += chunkSize) {
const chunk = arr.slice(i, i + chunkSize);
res.push(chunk);
}
return res;
}
function minutesToHHMM(totalMinutes) {
let minutes = totalMinutes % 60;
minutes = minutes.toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
});
let hours = (totalMinutes - minutes) / 60;
return `${hours}h ${minutes}m`;
}