var LibraryBrowser = (function (window, document, $, screen) {
var pageSizeKey = 'pagesize_v4';
var libraryBrowser = {
getDefaultPageSize: function (key, defaultValue) {
return 100;
var saved = appStorage.getItem(key || pageSizeKey);
if (saved) {
return parseInt(saved);
}
if (defaultValue) {
return defaultValue;
}
return 100;
},
getDefaultItemsView: function (view, mobileView) {
return $.browser.mobile ? mobileView : view;
},
loadSavedQueryValues: function (key, query) {
var values = appStorage.getItem(key + '_' + Dashboard.getCurrentUserId());
if (values) {
values = JSON.parse(values);
return $.extend(query, values);
}
return query;
},
saveQueryValues: function (key, query) {
var values = {};
if (query.SortBy) {
values.SortBy = query.SortBy;
}
if (query.SortOrder) {
values.SortOrder = query.SortOrder;
}
try {
appStorage.setItem(key + '_' + Dashboard.getCurrentUserId(), JSON.stringify(values));
} catch (e) {
}
},
saveViewSetting: function (key, value) {
try {
appStorage.setItem(key + '_' + Dashboard.getCurrentUserId() + '_view', value);
} catch (e) {
}
},
getSavedView: function (key) {
var val = appStorage.getItem(key + '_' + Dashboard.getCurrentUserId() + '_view');
return val;
},
getSavedViewSetting: function (key) {
var deferred = $.Deferred();
var val = LibraryBrowser.getSavedView(key);
deferred.resolveWith(null, [val]);
return deferred.promise();
},
needsRefresh: function (elem) {
var last = parseInt(elem.getAttribute('data-lastrefresh') || '0');
if (!last) {
return true;
}
if (NavHelper.isBack()) {
Logger.log('Not refreshing data because IsBack=true');
return false;
}
var now = new Date().getTime();
var cacheDuration;
if (AppInfo.isNativeApp) {
cacheDuration = 300000;
}
else if ($.browser.ipad || $.browser.iphone || $.browser.android) {
cacheDuration = 10000;
}
else {
cacheDuration = 60000;
}
if ((now - last) < cacheDuration) {
Logger.log('Not refreshing data due to age');
return false;
}
return true;
},
setLastRefreshed: function (elem) {
elem.setAttribute('data-lastrefresh', new Date().getTime());
elem.classList.add('hasrefreshtime');
},
animatePaperTabs: function () {
return !$.browser.safari;
},
configureSwipeTabs: function (ownerpage, tabs, pages) {
if (LibraryBrowser.animatePaperTabs()) {
// Safari doesn't handle the horizontal swiping very well
pages.entryAnimation = 'slide-from-right-animation';
pages.exitAnimation = 'slide-left-animation';
}
var pageCount = pages.querySelectorAll('neon-animatable').length;
function allowSwipeOn(elem) {
if (elem.tagName == 'PAPER-SLIDER') {
return false;
}
if (elem.classList) {
return !elem.classList.contains('hiddenScrollX') && !elem.classList.contains('smoothScrollX');
}
return true;
}
function allowSwipe(e) {
var target = e.target;
var parent = target.parentNode;
while (parent != null) {
if (!allowSwipeOn(parent)) {
return false;
}
parent = parent.parentNode;
}
return true;
}
require(['hammer'], function (Hammer) {
var hammertime = new Hammer(pages);
hammertime.get('swipe').set({ direction: Hammer.DIRECTION_HORIZONTAL });
hammertime.on('swipeleft', function (e) {
if (allowSwipe(e)) {
var selected = parseInt(pages.selected || '0');
if (selected < (pageCount - 1)) {
pages.entryAnimation = 'slide-from-right-animation';
pages.exitAnimation = 'slide-left-animation';
tabs.selectNext();
}
}
});
hammertime.on('swiperight', function (e) {
if (allowSwipe(e)) {
var selected = parseInt(pages.selected || '0');
if (selected > 0) {
pages.entryAnimation = 'slide-from-left-animation';
pages.exitAnimation = 'slide-right-animation';
tabs.selectPrevious();
}
}
});
});
},
enableFullPaperTabs: function () {
return AppInfo.isNativeApp;
},
navigateOnLibraryTabSelect: function () {
return !LibraryBrowser.enableFullPaperTabs();
},
configurePaperLibraryTabs: function (ownerpage, tabs, pages, baseUrl) {
// Causing iron-select to not fire in IE and safari
if ($.browser.chrome) {
tabs.noink = true;
}
if (AppInfo.enableBottomTabs) {
tabs.alignBottom = true;
tabs.classList.add('bottomTabs');
}
if (LibraryBrowser.enableFullPaperTabs()) {
tabs.noSlide = true;
if ($.browser.safari) {
tabs.noBar = true;
}
else {
LibraryBrowser.configureSwipeTabs(ownerpage, tabs, pages);
}
$('.libraryViewNav', ownerpage).addClass('paperLibraryViewNav').removeClass('libraryViewNavWithMinHeight');
} else {
tabs.noSlide = true;
tabs.noBar = true;
var legacyTabs = $('.legacyTabs', ownerpage);
$(pages).on('iron-select', function (e) {
var selected = this.selected;
$('a', legacyTabs).removeClass('ui-btn-active')[selected].classList.add('ui-btn-active');
});
$('.libraryViewNav', ownerpage).removeClass('libraryViewNavWithMinHeight');
}
$(ownerpage).on('pageshowready', LibraryBrowser.onTabbedpagebeforeshow);
pages.addEventListener('iron-select', function () {
// When transition animations are used, add a content loading delay to allow the animations to finish
// Otherwise with both operations happening at the same time, it can cause the animation to not run at full speed.
var pgs = this;
var delay = LibraryBrowser.animatePaperTabs() ? 500 : 0;
setTimeout(function () {
$(pgs).trigger('tabchange');
}, delay);
});
if (!LibraryBrowser.navigateOnLibraryTabSelect()) {
tabs.addEventListener('iron-select', function () {
pages.selected = this.selected;
});
}
},
onTabbedpagebeforeshow: function () {
var page = this;
var delay = 0;
var isFirstLoad = false;
if (!page.getAttribute('data-firstload')) {
delay = 300;
isFirstLoad = true;
page.setAttribute('data-firstload', '1');
}
if (delay) {
setTimeout(function () {
LibraryBrowser.onTabbedpagebeforeshowInternal(page, isFirstLoad);
}, delay);
} else {
LibraryBrowser.onTabbedpagebeforeshowInternal(page, isFirstLoad);
}
},
onTabbedpagebeforeshowInternal: function (page, isFirstLoad) {
if (isFirstLoad) {
Logger.log('selected tab is null, checking query string');
var selected = parseInt(getParameterByName('tab') || '0');
Logger.log('selected tab will be ' + selected);
if (LibraryBrowser.enableFullPaperTabs()) {
page.querySelector('paper-tabs').selected = selected;
} else {
page.querySelector('neon-animated-pages').selected = selected;
}
} else {
var pages = page.querySelector('neon-animated-pages');
// Go back to the first tab
if (LibraryBrowser.enableFullPaperTabs() && !NavHelper.isBack()) {
if (pages.selected) {
var entryAnimation = pages.entryAnimation;
var exitAnimation = pages.exitAnimation;
pages.entryAnimation = null;
pages.exitAnimation = null;
page.querySelector('paper-tabs').selected = 0;
pages.entryAnimation = entryAnimation;
pages.exitAnimation = exitAnimation;
return;
}
}
Events.trigger(pages, 'tabchange');
}
},
showTab: function (url, index) {
if (!LibraryBrowser.enableFullPaperTabs()) {
if (index) {
url = replaceQueryString(url, 'tab', index);
}
Dashboard.navigate(url);
return;
}
var afterNavigate = function () {
if (getWindowUrl().toLowerCase().indexOf(url.toLowerCase()) != -1) {
var pages = this.querySelector('neon-animated-pages');
if (pages) {
var entryAnimation = pages.entryAnimation;
var exitAnimation = pages.exitAnimation;
pages.entryAnimation = null;
pages.exitAnimation = null;
var tabs = this.querySelector('paper-tabs');
var noSlide = tabs.noSlide;
tabs.noSlide = true;
tabs.selected = index;
pages.entryAnimation = entryAnimation;
pages.exitAnimation = exitAnimation;
tabs.noSlide = noSlide;
}
}
};
if (getWindowUrl().toLowerCase().indexOf(url.toLowerCase()) != -1) {
afterNavigate.call($($.mobile.activePage)[0]);
} else {
$(document).one('pageshowready', '.page', afterNavigate);
Dashboard.navigate(url);
}
},
canShare: function (item, user) {
return user.Policy.EnablePublicSharing;
},
getDateParamValue: function (date) {
function formatDigit(i) {
return i < 10 ? "0" + i : i;
}
var d = date;
return "" + d.getFullYear() + formatDigit(d.getMonth() + 1) + formatDigit(d.getDate()) + formatDigit(d.getHours()) + formatDigit(d.getMinutes()) + formatDigit(d.getSeconds());
},
playAllFromHere: function (fn, index) {
fn(index, 100, "MediaSources,Chapters").done(function (result) {
MediaController.play({
items: result.Items
});
});
},
queueAllFromHere: function (query, index) {
fn(index, 100, "MediaSources,Chapters").done(function (result) {
MediaController.queue({
items: result.Items
});
});
},
getItemCountsHtml: function (options, item) {
var counts = [];
var childText;
if (item.Type == 'Playlist') {
childText = '';
if (item.CumulativeRunTimeTicks) {
var minutes = item.CumulativeRunTimeTicks / 600000000;
minutes = minutes || 1;
childText += Globalize.translate('ValueMinutes', Math.round(minutes));
} else {
childText += Globalize.translate('ValueMinutes', 0);
}
counts.push(childText);
}
else if (options.context == "movies") {
if (item.MovieCount) {
childText = item.MovieCount == 1 ?
Globalize.translate('ValueOneMovie') :
Globalize.translate('ValueMovieCount', item.MovieCount);
counts.push(childText);
}
if (item.TrailerCount) {
childText = item.TrailerCount == 1 ?
Globalize.translate('ValueOneTrailer') :
Globalize.translate('ValueTrailerCount', item.TrailerCount);
counts.push(childText);
}
} else if (options.context == "tv") {
if (item.SeriesCount) {
childText = item.SeriesCount == 1 ?
Globalize.translate('ValueOneSeries') :
Globalize.translate('ValueSeriesCount', item.SeriesCount);
counts.push(childText);
}
if (item.EpisodeCount) {
childText = item.EpisodeCount == 1 ?
Globalize.translate('ValueOneEpisode') :
Globalize.translate('ValueEpisodeCount', item.EpisodeCount);
counts.push(childText);
}
} else if (options.context == "games") {
if (item.GameCount) {
childText = item.GameCount == 1 ?
Globalize.translate('ValueOneGame') :
Globalize.translate('ValueGameCount', item.GameCount);
counts.push(childText);
}
} else if (options.context == "music") {
if (item.AlbumCount) {
childText = item.AlbumCount == 1 ?
Globalize.translate('ValueOneAlbum') :
Globalize.translate('ValueAlbumCount', item.AlbumCount);
counts.push(childText);
}
if (item.SongCount) {
childText = item.SongCount == 1 ?
Globalize.translate('ValueOneSong') :
Globalize.translate('ValueSongCount', item.SongCount);
counts.push(childText);
}
if (item.MusicVideoCount) {
childText = item.MusicVideoCount == 1 ?
Globalize.translate('ValueOneMusicVideo') :
Globalize.translate('ValueMusicVideoCount', item.MusicVideoCount);
counts.push(childText);
}
}
return counts.join(' • ');
},
getArtistLinksHtml: function (artists, cssClass) {
var html = [];
for (var i = 0, length = artists.length; i < length; i++) {
var artist = artists[i];
var css = cssClass ? (' class="' + cssClass + '"') : '';
html.push('' + artist.Name + '');
}
html = html.join(' / ');
return html;
},
playInExternalPlayer: function (id) {
Dashboard.loadExternalPlayer().done(function () {
ExternalPlayer.showMenu(id);
});
},
showPlayMenu: function (positionTo, itemId, itemType, isFolder, mediaType, resumePositionTicks) {
var externalPlayers = AppSettings.enableExternalPlayers();
if (!resumePositionTicks && mediaType != "Audio" && !isFolder) {
if (!externalPlayers || mediaType != "Video") {
MediaController.play(itemId);
return;
}
}
var menuItems = [];
if (resumePositionTicks) {
menuItems.push({
name: Globalize.translate('ButtonResume'),
id: 'resume',
ironIcon: 'play-arrow'
});
}
menuItems.push({
name: Globalize.translate('ButtonPlay'),
id: 'play',
ironIcon: 'play-arrow'
});
if (!isFolder && externalPlayers && mediaType != "Audio") {
menuItems.push({
name: Globalize.translate('ButtonPlayExternalPlayer'),
id: 'externalplayer',
ironIcon: 'airplay'
});
}
if (MediaController.canQueueMediaType(mediaType, itemType)) {
menuItems.push({
name: Globalize.translate('ButtonQueue'),
id: 'queue',
ironIcon: 'playlist-add'
});
}
if (itemType == "Audio" || itemType == "MusicAlbum" || itemType == "MusicArtist" || itemType == "MusicGenre") {
menuItems.push({
name: Globalize.translate('ButtonInstantMix'),
id: 'instantmix',
ironIcon: 'shuffle'
});
}
if (isFolder || itemType == "MusicArtist" || itemType == "MusicGenre") {
menuItems.push({
name: Globalize.translate('ButtonShuffle'),
id: 'shuffle',
ironIcon: 'shuffle'
});
}
require(['actionsheet'], function () {
ActionSheetElement.show({
items: menuItems,
positionTo: positionTo,
callback: function (id) {
switch (id) {
case 'play':
MediaController.play(itemId);
break;
case 'externalplayer':
LibraryBrowser.playInExternalPlayer(itemId);
break;
case 'resume':
MediaController.play({
ids: [itemId],
startPositionTicks: resumePositionTicks
});
break;
case 'queue':
MediaController.queue(itemId);
break;
case 'instantmix':
MediaController.instantMix(itemId);
break;
case 'shuffle':
MediaController.shuffle(itemId);
break;
default:
break;
}
}
});
});
},
getMoreCommands: function (item, user) {
var commands = [];
if (BoxSetEditor.supportsAddingToCollection(item)) {
commands.push('addtocollection');
}
if (PlaylistManager.supportsPlaylists(item)) {
commands.push('playlist');
}
if (item.Type == 'BoxSet' || item.Type == 'Playlist') {
commands.push('delete');
}
else if (item.CanDelete) {
commands.push('delete');
}
if (user.Policy.IsAdministrator) {
commands.push('edit');
}
commands.push('refresh');
if (SyncManager.isAvailable(item, user)) {
commands.push('sync');
}
if (item.CanDownload) {
commands.push('download');
}
if (LibraryBrowser.canShare(item, user)) {
commands.push('share');
}
return commands;
},
refreshItem: function (itemId) {
ApiClient.refreshItem(itemId, {
Recursive: true,
ImageRefreshMode: 'FullRefresh',
MetadataRefreshMode: 'FullRefresh',
ReplaceAllImages: false,
ReplaceAllMetadata: true
});
Dashboard.alert(Globalize.translate('MessageRefreshQueued'));
},
deleteItem: function (itemId) {
// The timeout allows the flyout to close
setTimeout(function () {
var msg = Globalize.translate('ConfirmDeleteItem');
Dashboard.confirm(msg, Globalize.translate('HeaderDeleteItem'), function (result) {
if (result) {
ApiClient.deleteItem(itemId);
Events.trigger(LibraryBrowser, 'itemdeleting', [itemId]);
}
});
}, 250);
},
showMoreCommands: function (positionTo, itemId, commands) {
var items = [];
if (commands.indexOf('addtocollection') != -1) {
items.push({
name: Globalize.translate('ButtonAddToCollection'),
id: 'addtocollection',
ironIcon: 'add'
});
}
if (commands.indexOf('playlist') != -1) {
items.push({
name: Globalize.translate('ButtonAddToPlaylist'),
id: 'playlist',
ironIcon: 'playlist-add'
});
}
if (commands.indexOf('delete') != -1) {
items.push({
name: Globalize.translate('ButtonDelete'),
id: 'delete',
ironIcon: 'delete'
});
}
if (commands.indexOf('download') != -1) {
items.push({
name: Globalize.translate('ButtonDownload'),
id: 'download',
ironIcon: 'file-download'
});
}
if (commands.indexOf('edit') != -1) {
items.push({
name: Globalize.translate('ButtonEdit'),
id: 'edit',
ironIcon: 'mode-edit'
});
}
if (commands.indexOf('refresh') != -1) {
items.push({
name: Globalize.translate('ButtonRefresh'),
id: 'refresh',
ironIcon: 'refresh'
});
}
if (commands.indexOf('share') != -1) {
items.push({
name: Globalize.translate('ButtonShare'),
id: 'share',
ironIcon: 'share'
});
}
require(['actionsheet'], function () {
ActionSheetElement.show({
items: items,
positionTo: positionTo,
callback: function (id) {
switch (id) {
case 'share':
require(['sharingmanager'], function () {
SharingManager.showMenu(Dashboard.getCurrentUserId(), itemId);
});
break;
case 'addtocollection':
BoxSetEditor.showPanel([itemId]);
break;
case 'playlist':
PlaylistManager.showPanel([itemId]);
break;
case 'delete':
LibraryBrowser.deleteItem(itemId);
break;
case 'download':
{
var downloadHref = ApiClient.getUrl("Items/" + itemId + "/Download", {
api_key: ApiClient.accessToken()
});
window.location.href = downloadHref;
break;
}
case 'edit':
Dashboard.navigate('edititemmetadata.html?id=' + itemId);
break;
case 'refresh':
ApiClient.refreshItem(itemId, {
Recursive: true,
ImageRefreshMode: 'FullRefresh',
MetadataRefreshMode: 'FullRefresh',
ReplaceAllImages: false,
ReplaceAllMetadata: true
});
break;
default:
break;
}
}
});
});
},
getHref: function (item, context, topParentId) {
var href = LibraryBrowser.getHrefInternal(item, context);
//if (context != 'livetv') {
// if (topParentId == null && context != 'playlists') {
// topParentId = LibraryMenu.getTopParentId();
// }
// if (topParentId) {
// href += href.indexOf('?') == -1 ? "?topParentId=" : "&topParentId=";
// href += topParentId;
// }
//}
return href;
},
getHrefInternal: function (item, context) {
if (!item) {
throw new Error('item cannot be null');
}
if (item.url) {
return item.url;
}
// Handle search hints
var id = item.Id || item.ItemId;
if (item.CollectionType == 'livetv') {
return 'livetv.html';
}
if (item.CollectionType == 'channels') {
return 'channels.html';
}
if (context != 'folders') {
if (item.CollectionType == 'movies') {
return 'movies.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'boxsets') {
return 'collections.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'tvshows') {
return 'tvrecommended.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'music') {
return 'music.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'games') {
return 'gamesrecommended.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'playlists') {
return 'playlists.html?topParentId=' + item.Id;
}
if (item.CollectionType == 'photos') {
return 'photos.html?topParentId=' + item.Id;
}
}
if (item.Type == 'CollectionFolder') {
return 'itemlist.html?topParentId=' + item.Id + '&parentid=' + item.Id;
}
if (item.Type == "PhotoAlbum") {
return "itemlist.html?context=photos&parentId=" + id;
}
if (item.Type == "Playlist") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "TvChannel") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "Channel") {
return "channelitems.html?id=" + id;
}
if (item.Type == "ChannelFolderItem") {
return "channelitems.html?id=" + item.ChannelId + '&folderId=' + item.Id;
}
if (item.Type == "Program") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "BoxSet") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "MusicAlbum") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "GameSystem") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "Genre") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "MusicGenre") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "GameGenre") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "Studio") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "Person") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "Recording") {
return "itemdetails.html?id=" + id;
}
if (item.Type == "MusicArtist") {
return "itemdetails.html?id=" + id;
}
var contextSuffix = context ? ('&context=' + context) : '';
if (item.Type == "Series" || item.Type == "Season" || item.Type == "Episode") {
return "itemdetails.html?id=" + id + contextSuffix;
}
if (item.IsFolder) {
return id ? "itemlist.html?parentId=" + id : "#";
}
return "itemdetails.html?id=" + id;
},
getImageUrl: function (item, type, index, options) {
options = options || {};
options.type = type;
options.index = index;
if (type == 'Backdrop') {
options.tag = item.BackdropImageTags[index];
} else if (type == 'Screenshot') {
options.tag = item.ScreenshotImageTags[index];
} else if (type == 'Primary') {
options.tag = item.PrimaryImageTag || item.ImageTags[type];
} else {
options.tag = item.ImageTags[type];
}
// For search hints
return ApiClient.getScaledImageUrl(item.Id || item.ItemId, options);
},
getListViewIndex: function (item, options) {
if (options.index == 'disc') {
return item.ParentIndexNumber == null ? '' : Globalize.translate('ValueDiscNumber', item.ParentIndexNumber);
}
var sortBy = (options.sortBy || '').toLowerCase();
var code, name;
if (sortBy.indexOf('sortname') == 0) {
if (item.Type == 'Episode') return '';
// SortName
name = (item.SortName || item.Name || '?')[0].toUpperCase();
code = name.charCodeAt(0);
if (code < 65 || code > 90) {
return '#';
}
return name.toUpperCase();
}
if (sortBy.indexOf('officialrating') == 0) {
return item.OfficialRating || Globalize.translate('HeaderUnrated');
}
if (sortBy.indexOf('communityrating') == 0) {
if (item.CommunityRating == null) {
return Globalize.translate('HeaderUnrated');
}
return Math.floor(item.CommunityRating);
}
if (sortBy.indexOf('criticrating') == 0) {
if (item.CriticRating == null) {
return Globalize.translate('HeaderUnrated');
}
return Math.floor(item.CriticRating);
}
if (sortBy.indexOf('metascore') == 0) {
if (item.Metascore == null) {
return Globalize.translate('HeaderUnrated');
}
return Math.floor(item.Metascore);
}
if (sortBy.indexOf('albumartist') == 0) {
// SortName
if (!item.AlbumArtist) return '';
name = item.AlbumArtist[0].toUpperCase();
code = name.charCodeAt(0);
if (code < 65 || code > 90) {
return '#';
}
return name.toUpperCase();
}
return '';
},
getUserDataCssClass: function (key) {
if (!key) return '';
return 'libraryItemUserData' + key.replace(new RegExp(' ', 'g'), '');
},
getListViewHtml: function (options) {
var outerHtml = "";
if (options.title) {
outerHtml += '
';
outerHtml += options.title;
outerHtml += '
';
}
outerHtml += '
';
var index = 0;
var groupTitle = '';
outerHtml += options.items.map(function (item) {
var html = '';
if (options.showIndex !== false) {
var itemGroupTitle = LibraryBrowser.getListViewIndex(item, options);
if (itemGroupTitle != groupTitle) {
outerHtml += '
';
html += '
';
html += itemGroupTitle;
html += '
';
html += '
';
groupTitle = itemGroupTitle;
}
}
var dataAttributes = LibraryBrowser.getItemDataAttributes(item, options, index);
var cssClass = 'listItem';
var href = LibraryBrowser.getHref(item, options.context);
html += '';
var imgUrl;
var downloadWidth = options.smallIcon ? 70 : 80;
// Scaling 400w episode images to 80 doesn't turn out very well
var minScale = item.Type == 'Episode' || item.Type == 'Game' || options.smallIcon ? 2 : 1.5;
if (item.ImageTags.Primary) {
imgUrl = ApiClient.getScaledImageUrl(item.Id, {
width: downloadWidth,
tag: item.ImageTags.Primary,
type: "Primary",
index: 0,
minScale: minScale
});
}
else if (item.AlbumId && item.AlbumPrimaryImageTag) {
imgUrl = ApiClient.getScaledImageUrl(item.AlbumId, {
type: "Primary",
width: downloadWidth,
tag: item.AlbumPrimaryImageTag,
minScale: minScale
});
}
else if (item.AlbumId && item.SeriesPrimaryImageTag) {
imgUrl = ApiClient.getScaledImageUrl(item.SeriesId, {
type: "Primary",
width: downloadWidth,
tag: item.SeriesPrimaryImageTag,
minScale: minScale
});
}
else if (item.ParentPrimaryImageTag) {
imgUrl = ApiClient.getImageUrl(item.ParentPrimaryImageItemId, {
type: "Primary",
width: downloadWidth,
tag: item.ParentPrimaryImageTag,
minScale: minScale
});
}
if (imgUrl) {
var minLazyIndex = 16;
if (options.smallIcon) {
if (index < minLazyIndex) {
html += '';
} else {
html += '';
}
} else {
if (index < minLazyIndex) {
html += '';
} else {
html += '';
}
}
} else {
if (options.smallIcon) {
html += '';
} else {
html += '';
}
}
var textlines = [];
if (item.Type == 'Episode') {
textlines.push(item.SeriesName || ' ');
} else if (item.Type == 'MusicAlbum') {
textlines.push(item.AlbumArtist || ' ');
}
var displayName = LibraryBrowser.getPosterViewDisplayName(item);
if (options.showIndexNumber && item.IndexNumber != null) {
displayName = item.IndexNumber + ". " + displayName;
}
textlines.push(displayName);
if (item.Type == 'Audio') {
textlines.push(item.ArtistItems.map(function (a) {
return a.Name;
}).join(', ') || ' ');
}
if (item.Type == 'Game') {
textlines.push(item.GameSystem || ' ');
}
else if (item.Type == 'MusicGenre') {
textlines.push(' ');
}
else if (item.Type == 'MusicArtist') {
textlines.push(' ');
}
else if (item.Type == 'TvChannel') {
if (item.CurrentProgram) {
textlines.push(LibraryBrowser.getPosterViewDisplayName(item.CurrentProgram));
}
}
else {
textlines.push(LibraryBrowser.getMiscInfoHtml(item));
}
if (textlines.length > 2) {
html += '';
} else {
html += '';
}
var defaultAction = options.defaultAction;
if (defaultAction == 'play' || defaultAction == 'playallfromhere') {
if (item.PlayAccess != 'Full') {
defaultAction = null;
}
}
var defaultActionAttribute = defaultAction ? (' data-action="' + defaultAction + '" class="itemWithAction mediaItem clearLink"') : ' class="mediaItem clearLink"';
html += '';
for (var i = 0, textLinesLength = textlines.length; i < textLinesLength; i++) {
if (i == 0) {
html += '
";
progressHtml = '';
}
// cardContent
html += '';
if (options.overlayPlayButton && !item.IsPlaceHolder && (item.LocationType != 'Virtual' || !item.MediaType || item.Type == 'Program')) {
html += '';
}
if (options.overlayMoreButton) {
html += '';
}
// cardScalable
html += '
';
if (!options.overlayText && !footerOverlayed) {
html += LibraryBrowser.getCardFooterText(item, options, showTitle, imgUrl, forceName, 'cardFooter outerCardFooter', progressHtml);
}
// cardBox
html += '
';
// card
html += "
";
return html;
},
getCardFooterText: function (item, options, showTitle, imgUrl, forceName, footerClass, progressHtml) {
var html = '';
html += '";
return html;
},
getListItemInfo: function (elem) {
var elemWithAttributes = elem;
while (!elemWithAttributes.getAttribute('data-itemid')) {
elemWithAttributes = elemWithAttributes.parentNode;
}
var itemId = elemWithAttributes.getAttribute('data-itemid');
var index = elemWithAttributes.getAttribute('data-index');
var mediaType = elemWithAttributes.getAttribute('data-mediatype');
return {
id: itemId,
index: index,
mediaType: mediaType,
context: elemWithAttributes.getAttribute('data-context')
};
},
getCardTextLines: function (lines, cssClass, forceLines) {
var html = '';
var valid = 0;
var i, length;
for (i = 0, length = lines.length; i < length; i++) {
var text = lines[i];
if (text) {
html += "
";
html += text;
html += "
";
valid++;
}
}
if (forceLines) {
while (valid < length) {
html += "
";
valid++;
}
}
return html;
},
getFutureDateText: function (date) {
var weekday = [];
weekday[0] = Globalize.translate('OptionSunday');
weekday[1] = Globalize.translate('OptionMonday');
weekday[2] = Globalize.translate('OptionTuesday');
weekday[3] = Globalize.translate('OptionWednesday');
weekday[4] = Globalize.translate('OptionThursday');
weekday[5] = Globalize.translate('OptionFriday');
weekday[6] = Globalize.translate('OptionSaturday');
var day = weekday[date.getDay()];
date = date.toLocaleDateString();
if (date.toLowerCase().indexOf(day.toLowerCase()) == -1) {
return day + " " + date;
}
return date;
},
getPremiereDateText: function (item, date) {
if (!date) {
var text = '';
if (item.AirTime) {
text += item.AirTime;
}
if (item.SeriesStudio) {
if (text) {
text += " on " + item.SeriesStudio;
} else {
text += item.SeriesStudio;
}
}
return text;
}
var day = LibraryBrowser.getFutureDateText(date);
if (item.AirTime) {
day += " at " + item.AirTime;
}
if (item.SeriesStudio) {
day += " on " + item.SeriesStudio;
}
return day;
},
getPosterViewDisplayName: function (item, displayAsSpecial, includeParentInfo) {
if (!item) {
throw new Error("null item passed into getPosterViewDisplayName");
}
var name = item.EpisodeTitle || item.Name || '';
if (item.Type == "TvChannel") {
if (item.Number) {
return item.Number + ' ' + name;
}
return name;
}
if (displayAsSpecial && item.Type == "Episode" && item.ParentIndexNumber == 0) {
name = Globalize.translate('ValueSpecialEpisodeName', name);
} else if (item.Type == "Episode" && item.IndexNumber != null && item.ParentIndexNumber != null) {
var displayIndexNumber = item.IndexNumber;
var number = "E" + displayIndexNumber;
if (includeParentInfo !== false) {
number = "S" + item.ParentIndexNumber + ", " + number;
}
if (item.IndexNumberEnd) {
displayIndexNumber = item.IndexNumberEnd;
number += "-" + displayIndexNumber;
}
name = number + " - " + name;
}
return name;
},
getOfflineIndicatorHtml: function (item) {
if (item.LocationType == "Offline") {
return '
' + Globalize.translate('HeaderOffline') + '
';
}
if (item.Type == 'Episode') {
try {
var date = parseISO8601Date(item.PremiereDate, { toLocal: true });
if (item.PremiereDate && (new Date().getTime() < date.getTime())) {
return '
';
}
}
return '';
},
getAveragePrimaryImageAspectRatio: function (items) {
var values = [];
for (var i = 0, length = items.length; i < length; i++) {
var ratio = items[i].PrimaryImageAspectRatio || 0;
if (!ratio) {
continue;
}
values[values.length] = ratio;
}
if (!values.length) {
return null;
}
// Use the median
values.sort(function (a, b) { return a - b; });
var half = Math.floor(values.length / 2);
var result;
if (values.length % 2)
result = values[half];
else
result = (values[half - 1] + values[half]) / 2.0;
// If really close to 2:3 (poster image), just return 2:3
if (Math.abs(0.66666666667 - result) <= .15) {
return 0.66666666667;
}
// If really close to 16:9 (episode image), just return 16:9
if (Math.abs(1.777777778 - result) <= .2) {
return 1.777777778;
}
// If really close to 1 (square image), just return 1
if (Math.abs(1 - result) <= .15) {
return 1;
}
// If really close to 4:3 (poster image), just return 2:3
if (Math.abs(1.33333333333 - result) <= .15) {
return 1.33333333333;
}
return result;
},
metroColors: ["#6FBD45", "#4BB3DD", "#4164A5", "#E12026", "#800080", "#E1B222", "#008040", "#0094FF", "#FF00C7", "#FF870F", "#7F0037"],
getRandomMetroColor: function () {
var index = Math.floor(Math.random() * (LibraryBrowser.metroColors.length - 1));
return LibraryBrowser.metroColors[index];
},
getMetroColor: function (str) {
if (str) {
var character = String(str.substr(0, 1).charCodeAt());
var sum = 0;
for (var i = 0; i < character.length; i++) {
sum += parseInt(character.charAt(i));
}
var index = String(sum).substr(-1);
return LibraryBrowser.metroColors[index];
} else {
return LibraryBrowser.getRandomMetroColor();
}
},
renderName: function (item, nameElem, linkToElement, context) {
var name = LibraryBrowser.getPosterViewDisplayName(item, false, false);
Dashboard.setPageTitle(name);
if (linkToElement) {
nameElem.html('' + name + '').trigger('create');
} else {
nameElem.html(name);
}
},
renderParentName: function (item, parentNameElem, context) {
var html = [];
var contextParam = context ? ('&context=' + context) : '';
if (item.AlbumArtists) {
html.push(LibraryBrowser.getArtistLinksHtml(item.AlbumArtists, "detailPageParentLink"));
} else if (item.ArtistItems && item.ArtistItems.length && item.Type == "MusicVideo") {
html.push(LibraryBrowser.getArtistLinksHtml(item.ArtistItems, "detailPageParentLink"));
} else if (item.SeriesName && item.Type == "Episode") {
html.push('' + item.SeriesName + '');
}
if (item.SeriesName && item.Type == "Season") {
html.push('' + item.SeriesName + '');
} else if (item.ParentIndexNumber != null && item.Type == "Episode") {
html.push('' + item.SeasonName + '');
} else if (item.Album && item.Type == "Audio" && (item.AlbumId || item.ParentId)) {
html.push('' + item.Album + '');
} else if (item.Album && item.Type == "MusicVideo" && item.AlbumId) {
html.push('' + item.Album + '');
} else if (item.Album) {
html.push(item.Album);
} else if (item.Type == 'Program' && item.EpisodeTitle) {
html.push(item.Name);
}
if (html.length) {
parentNameElem.show().html(html.join(' - ')).trigger('create');
} else {
parentNameElem.hide();
}
},
renderLinks: function (linksElem, item) {
var links = [];
if (item.HomePageUrl) {
links.push('' + Globalize.translate('ButtonWebsite') + '');
}
if (item.ExternalUrls) {
for (var i = 0, length = item.ExternalUrls.length; i < length; i++) {
var url = item.ExternalUrls[i];
links.push('' + url.Name + '');
}
}
if (links.length) {
var html = links.join(' / ');
html = Globalize.translate('ValueLinks', html);
linksElem.innerHTML = html;
$(linksElem).trigger('create');
$(linksElem).show();
} else {
$(linksElem).hide();
}
},
getDefaultPageSizeSelections: function () {
return [20, 50, 100, 200, 300, 400, 500];
},
showLayoutMenu: function (button, currentLayout) {
// Add banner and list once all screens support them
var views = button.getAttribute('data-layouts');
views = views ? views.split(',') : ['List', 'Poster', 'PosterCard', 'Thumb', 'ThumbCard'];
var menuItems = views.map(function (v) {
return {
name: Globalize.translate('Option' + v),
id: v,
ironIcon: currentLayout == v ? 'check' : null
};
});
require(['actionsheet'], function () {
ActionSheetElement.show({
items: menuItems,
positionTo: button,
callback: function (id) {
$(button).trigger('layoutchange', [id]);
}
});
});
},
getQueryPagingHtml: function (options) {
var startIndex = options.startIndex;
var limit = options.limit;
var totalRecordCount = options.totalRecordCount;
if (limit && options.updatePageSizeSetting !== false) {
try {
appStorage.setItem(options.pageSizeKey || pageSizeKey, limit);
} catch (e) {
}
}
var html = '';
var recordsEnd = Math.min(startIndex + limit, totalRecordCount);
// 20 is the minimum page size
var showControls = totalRecordCount > 20 || limit < totalRecordCount;
html += '
';
if (showControls) {
html += '';
var startAtDisplay = totalRecordCount ? startIndex + 1 : 0;
html += startAtDisplay + '-' + recordsEnd + ' of ' + totalRecordCount;
html += '';
}
if (showControls || options.viewButton || options.sortButton || options.addLayoutButton || options.addSelectionButton || options.additionalButtonsHtml) {
html += '
';
if (showControls) {
html += '';
html += '= totalRecordCount ? 'disabled' : '') + '>';
}
html += (options.additionalButtonsHtml || '');
if (options.addSelectionButton) {
html += '';
}
if (options.addLayoutButton) {
html += '';
}
if (options.sortButton) {
html += '';
}
if (options.viewButton) {
//html += '';
var viewPanelClass = options.viewPanelClass || 'viewPanel';
var title = options.viewIcon == 'filter-list' ? Globalize.translate('ButtonFilter') : Globalize.translate('ButtonMenu');
html += '';
}
html += '
';
if (showControls && options.showLimit) {
var id = "selectPageSize";
var pageSizes = options.pageSizes || LibraryBrowser.getDefaultPageSizeSelections();
var optionsHtml = pageSizes.map(function (val) {
if (limit == val) {
return '';
} else {
return '';
}
}).join('');
// Add styles to defeat jquery mobile
html += '';
}
}
html += '
';
return html;
},
showSortMenu: function (options) {
var id = 'dlg' + new Date().getTime();
var html = '';
html += '';
// There seems to be a bug with this in safari causing it to immediately roll up to 0 height
var isScrollable = !$.browser.safari;
html += '
';
html += Globalize.translate('HeaderSortBy');
html += '
';
if (isScrollable) {
html += '';
}
html += '';
for (var i = 0, length = options.items.length; i < length; i++) {
var option = options.items[i];
html += '' + option.name + '';
}
html += '';
html += '
';
html += Globalize.translate('HeaderSortOrder');
html += '
';
html += '';
html += '' + Globalize.translate('OptionAscending') + '';
html += '' + Globalize.translate('OptionDescending') + '';
html += '';
if (isScrollable) {
html += '';
}
html += '
';
html += '' + Globalize.translate('ButtonClose') + '';
html += '
';
html += '';
$(document.body).append(html);
setTimeout(function () {
var dlg = document.getElementById(id);
dlg.open();
$(dlg).on('iron-overlay-closed', function () {
$(this).remove();
});
$('.groupSortBy', dlg).on('iron-select', function () {
options.query.SortBy = this.selected.replace('_', ',');
options.query.StartIndex = 0;
if (options.callback) {
options.callback();
}
});
$('.groupSortOrder', dlg).on('iron-select', function () {
options.query.SortOrder = this.selected;
options.query.StartIndex = 0;
if (options.callback) {
options.callback();
}
});
}, 100);
},
getRatingHtml: function (item, metascore) {
var html = "";
if (item.CommunityRating) {
html += "";
html += '
';
html += item.CommunityRating.toFixed(1);
html += '
';
}
if (item.CriticRating != null) {
if (item.CriticRating >= 60) {
html += '';
} else {
html += '';
}
html += '
' + item.CriticRating + '%
';
}
//if (item.Metascore && metascore !== false) {
// if (item.Metascore >= 60) {
// html += '
' + item.Metascore + '
';
// }
// else if (item.Metascore >= 40) {
// html += '
' + item.Metascore + '
';
// } else {
// html += '
' + item.Metascore + '
';
// }
//}
return html;
},
getItemProgressBarHtml: function (item) {
if (item.Type == "Recording" && item.CompletionPercentage) {
return '';
}
var pct = item.PlayedPercentage;
if (pct && pct < 100) {
return '';
}
return null;
},
getUserDataButtonHtml: function (method, itemId, btnCssClass, icon, tooltip, style) {
var tagName = style == 'fab' ? 'paper-fab' : 'paper-icon-button';
return '<' + tagName + ' title="' + tooltip + '" data-itemid="' + itemId + '" icon="' + icon + '" class="' + btnCssClass + '" onclick="LibraryBrowser.' + method + '(this);return false;">' + tagName + '>';
},
getUserDataIconsHtml: function (item, includePlayed, style) {
var html = '';
var userData = item.UserData || {};
var itemId = item.Id;
if (includePlayed !== false) {
var tooltipPlayed = Globalize.translate('TooltipPlayed');
if (item.MediaType == 'Video' || item.Type == 'Series' || item.Type == 'Season' || item.Type == 'BoxSet' || item.Type == 'Playlist') {
if (item.Type != 'TvChannel') {
if (userData.Played) {
html += LibraryBrowser.getUserDataButtonHtml('markPlayed', itemId, 'btnUserItemRating btnUserItemRatingOn', 'check', tooltipPlayed, style);
} else {
html += LibraryBrowser.getUserDataButtonHtml('markPlayed', itemId, 'btnUserItemRating', 'check', tooltipPlayed, style);
}
}
}
}
var tooltipLike = Globalize.translate('TooltipLike');
var tooltipDislike = Globalize.translate('TooltipDislike');
if (typeof userData.Likes == "undefined") {
html += LibraryBrowser.getUserDataButtonHtml('markDislike', itemId, 'btnUserItemRating', 'thumb-down', tooltipDislike, style);
html += LibraryBrowser.getUserDataButtonHtml('markLike', itemId, 'btnUserItemRating', 'thumb-up', tooltipLike, style);
}
else if (userData.Likes) {
html += LibraryBrowser.getUserDataButtonHtml('markDislike', itemId, 'btnUserItemRating', 'thumb-down', tooltipDislike, style);
html += LibraryBrowser.getUserDataButtonHtml('markLike', itemId, 'btnUserItemRating btnUserItemRatingOn', 'thumb-up', tooltipLike, style);
}
else {
html += LibraryBrowser.getUserDataButtonHtml('markDislike', itemId, 'btnUserItemRating btnUserItemRatingOn', 'thumb-down', tooltipDislike, style);
html += LibraryBrowser.getUserDataButtonHtml('markLike', itemId, 'btnUserItemRating', 'thumb-up', tooltipLike, style);
}
var tooltipFavorite = Globalize.translate('TooltipFavorite');
if (userData.IsFavorite) {
html += LibraryBrowser.getUserDataButtonHtml('markFavorite', itemId, 'btnUserItemRating btnUserItemRatingOn', 'favorite', tooltipFavorite, style);
} else {
html += LibraryBrowser.getUserDataButtonHtml('markFavorite', itemId, 'btnUserItemRating', 'favorite', tooltipFavorite, style);
}
return html;
},
markPlayed: function (link) {
var id = link.getAttribute('data-itemid');
var markAsPlayed = !link.classList.contains('btnUserItemRatingOn');
if (markAsPlayed) {
ApiClient.markPlayed(Dashboard.getCurrentUserId(), id);
link.classList.add('btnUserItemRatingOn');
} else {
ApiClient.markUnplayed(Dashboard.getCurrentUserId(), id);
link.classList.remove('btnUserItemRatingOn');
}
},
markFavorite: function (link) {
var id = link.getAttribute('data-itemid');
var $link = $(link);
var markAsFavorite = !$link.hasClass('btnUserItemRatingOn');
ApiClient.updateFavoriteStatus(Dashboard.getCurrentUserId(), id, markAsFavorite);
if (markAsFavorite) {
$link.addClass('btnUserItemRatingOn');
} else {
$link.removeClass('btnUserItemRatingOn');
}
},
markLike: function (link) {
var id = link.getAttribute('data-itemid');
var $link = $(link);
if (!$link.hasClass('btnUserItemRatingOn')) {
ApiClient.updateUserItemRating(Dashboard.getCurrentUserId(), id, true);
$link.addClass('btnUserItemRatingOn');
} else {
ApiClient.clearUserItemRating(Dashboard.getCurrentUserId(), id);
$link.removeClass('btnUserItemRatingOn');
}
$link.prev().removeClass('btnUserItemRatingOn');
},
markDislike: function (link) {
var id = link.getAttribute('data-itemid');
var $link = $(link);
if (!$link.hasClass('btnUserItemRatingOn')) {
ApiClient.updateUserItemRating(Dashboard.getCurrentUserId(), id, false);
$link.addClass('btnUserItemRatingOn');
} else {
ApiClient.clearUserItemRating(Dashboard.getCurrentUserId(), id);
$link.removeClass('btnUserItemRatingOn');
}
$link.next().removeClass('btnUserItemRatingOn');
},
getDetailImageHtml: function (item, href, preferThumb) {
var imageTags = item.ImageTags || {};
if (item.PrimaryImageTag) {
imageTags.Primary = item.PrimaryImageTag;
}
var html = '';
var url;
var imageHeight = 360;
if (preferThumb && imageTags.Thumb) {
url = ApiClient.getScaledImageUrl(item.Id, {
type: "Thumb",
height: imageHeight,
tag: item.ImageTags.Thumb
});
}
else if (imageTags.Primary) {
url = ApiClient.getScaledImageUrl(item.Id, {
type: "Primary",
height: imageHeight,
tag: item.ImageTags.Primary
});
}
else if (item.BackdropImageTags && item.BackdropImageTags.length) {
url = ApiClient.getScaledImageUrl(item.Id, {
type: "Backdrop",
height: imageHeight,
tag: item.BackdropImageTags[0]
});
}
else if (imageTags.Thumb) {
url = ApiClient.getScaledImageUrl(item.Id, {
type: "Thumb",
height: imageHeight,
tag: item.ImageTags.Thumb
});
}
else if (imageTags.Disc) {
url = ApiClient.getScaledImageUrl(item.Id, {
type: "Disc",
height: imageHeight,
tag: item.ImageTags.Disc
});
}
else if (item.AlbumId && item.AlbumPrimaryImageTag) {
url = ApiClient.getScaledImageUrl(item.AlbumId, {
type: "Primary",
height: imageHeight,
tag: item.AlbumPrimaryImageTag
});
}
else if (item.MediaType == "Audio" || item.Type == "MusicAlbum" || item.Type == "MusicGenre") {
url = "css/images/items/detail/audio.png";
}
else if (item.MediaType == "Game" || item.Type == "GameGenre") {
url = "css/images/items/detail/game.png";
}
else if (item.Type == "Person") {
url = "css/images/items/detail/person.png";
}
else if (item.Type == "Genre" || item.Type == "Studio") {
url = "css/images/items/detail/video.png";
}
else if (item.Type == "TvChannel") {
url = "css/images/items/detail/tv.png";
}
else {
url = "css/images/items/detail/video.png";
}
html += '
';
if (href) {
html += "";
}
html += "";
if (href) {
html += "";
}
var progressHtml = item.IsFolder ? '' : LibraryBrowser.getItemProgressBarHtml((item.Type == 'Recording' ? item : item.UserData));
if (progressHtml) {
html += '