From 661eeac16eccccdc776e38b77982f6cedc5be4b1 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 27 Jan 2017 22:16:59 -0500 Subject: [PATCH] minify resources --- .../accessschedule/accessschedule.js | 115 +- .../components/appfooter/appfooter.css | 21 +- .../components/appfooter/appfooter.js | 62 +- dashboard-ui/components/apphost.js | 246 +- .../components/categorysyncbuttons.js | 51 +- .../components/channelmapper/channelmapper.js | 201 +- dashboard-ui/components/chromecasthelpers.js | 235 +- .../directorybrowser/directorybrowser.css | 17 +- .../directorybrowser/directorybrowser.js | 329 +- .../components/dockedtabs/dockedtabs.css | 45 +- .../components/dockedtabs/dockedtabs.js | 379 +-- dashboard-ui/components/favoriteitems.js | 176 +- .../components/fileorganizer/fileorganizer.js | 263 +- .../components/filterdialog/filterdialog.js | 588 +--- .../components/filterdialog/style.css | 39 +- dashboard-ui/components/groupedcards.js | 55 +- .../components/guestinviter/connectlink.js | 67 +- .../components/guestinviter/guestinviter.js | 116 +- dashboard-ui/components/humanedate.js | 66 +- dashboard-ui/components/iap.js | 75 +- .../imagedownloader/imagedownloader.js | 371 +-- .../components/imageuploader/imageuploader.js | 201 +- .../libraryoptionseditor.js | 155 +- .../medialibrarycreator.js | 274 +- .../medialibraryeditor/medialibraryeditor.js | 297 +- .../components/navdrawer/navdrawer.css | 46 +- .../components/navdrawer/navdrawer.js | 306 +- dashboard-ui/components/remotecontrol.js | 955 +----- .../components/tvproviders/schedulesdirect.js | 332 +- dashboard-ui/components/tvproviders/xmltv.js | 233 +- dashboard-ui/components/viewcontainer-lite.js | 463 +-- dashboard-ui/css/autoorganizetable.css | 73 +- dashboard-ui/css/chromecast.css | 18 +- dashboard-ui/css/dashboard.css | 579 +--- dashboard-ui/css/detailtable.css | 88 +- dashboard-ui/css/librarybrowser.css | 816 +---- dashboard-ui/css/librarymenu.css | 342 +-- dashboard-ui/css/livetv.css | 10 +- dashboard-ui/css/metadataeditor.css | 222 +- dashboard-ui/css/notifications.css | 36 +- dashboard-ui/css/nowplaying.css | 173 +- dashboard-ui/css/nowplayingbar.css | 265 +- dashboard-ui/css/site.css | 345 +-- dashboard-ui/dashboard/aboutpage.js | 16 +- dashboard-ui/dashboard/autoorganizelog.js | 424 +-- dashboard-ui/dashboard/autoorganizesmart.js | 179 +- dashboard-ui/dashboard/autoorganizetv.js | 183 +- .../dashboard/cinemamodeconfiguration.js | 145 +- dashboard-ui/dashboard/dashboardgeneral.js | 159 +- dashboard-ui/dashboard/dashboardhosting.js | 140 +- dashboard-ui/dashboard/devicesupload.js | 102 +- dashboard-ui/dashboard/librarydisplay.js | 71 +- dashboard-ui/dashboard/librarysettings.js | 162 +- .../dashboard/livetvtunerprovider-satip.js | 137 +- dashboard-ui/dashboard/logpage.js | 80 +- dashboard-ui/dashboard/wizardcomponents.js | 146 +- dashboard-ui/dashboard/wizardfinishpage.js | 28 +- dashboard-ui/devices/android/android.css | 16 +- dashboard-ui/devices/ios/ios.css | 96 +- dashboard-ui/legacy/buttonenabled.js | 9 +- dashboard-ui/legacy/dashboard.js | 13 +- dashboard-ui/legacy/fnchecked.js | 21 +- dashboard-ui/legacy/selectmenu.js | 10 +- dashboard-ui/scripts/addpluginpage.js | 358 +-- dashboard-ui/scripts/appservices.js | 107 +- dashboard-ui/scripts/autobackdrops.js | 113 +- dashboard-ui/scripts/camerauploadsettings.js | 74 +- dashboard-ui/scripts/channelitems.js | 265 +- dashboard-ui/scripts/channels.js | 98 +- dashboard-ui/scripts/channelslatest.js | 39 +- dashboard-ui/scripts/connectlogin.js | 349 +-- dashboard-ui/scripts/dashboardpage.js | 1415 +-------- dashboard-ui/scripts/device.js | 97 +- dashboard-ui/scripts/devices.js | 114 +- dashboard-ui/scripts/dlnaprofile.js | 1182 +------- dashboard-ui/scripts/dlnaprofiles.js | 123 +- dashboard-ui/scripts/dlnasettings.js | 84 +- dashboard-ui/scripts/edititemmetadata.js | 39 +- dashboard-ui/scripts/editorsidebar.js | 483 +-- dashboard-ui/scripts/encodingsettings.js | 204 +- dashboard-ui/scripts/episodes.js | 267 +- dashboard-ui/scripts/favorites.js | 21 +- dashboard-ui/scripts/forgotpassword.js | 67 +- dashboard-ui/scripts/forgotpasswordpin.js | 57 +- dashboard-ui/scripts/gamegenrepage.js | 85 +- dashboard-ui/scripts/gamespage.js | 187 +- dashboard-ui/scripts/gamesrecommendedpage.js | 73 +- dashboard-ui/scripts/gamestudiospage.js | 86 +- dashboard-ui/scripts/gamesystemspage.js | 78 +- dashboard-ui/scripts/homefavorites.js | 16 +- dashboard-ui/scripts/homenextup.js | 72 +- dashboard-ui/scripts/homeupcoming.js | 156 +- dashboard-ui/scripts/indexpage.js | 369 +-- dashboard-ui/scripts/itembynamedetailpage.js | 414 +-- dashboard-ui/scripts/itemdetailpage.js | 2467 +-------------- dashboard-ui/scripts/itemlistpage.js | 345 +-- dashboard-ui/scripts/librarybrowser.js | 931 +----- dashboard-ui/scripts/librarymenu.js | 1077 +------ dashboard-ui/scripts/livetvchannel.js | 74 +- dashboard-ui/scripts/livetvchannels.js | 142 +- dashboard-ui/scripts/livetvcomponents.js | 121 +- dashboard-ui/scripts/livetvguide.js | 27 +- dashboard-ui/scripts/livetvguideprovider.js | 52 +- dashboard-ui/scripts/livetvitems.js | 188 +- dashboard-ui/scripts/livetvrecordings.js | 335 +- dashboard-ui/scripts/livetvschedule.js | 136 +- dashboard-ui/scripts/livetvseriestimers.js | 64 +- dashboard-ui/scripts/livetvsettings.js | 209 +- dashboard-ui/scripts/livetvstatus.js | 621 +--- dashboard-ui/scripts/livetvsuggested.js | 400 +-- .../scripts/livetvtunerprovider-hdhomerun.js | 82 +- .../scripts/livetvtunerprovider-m3u.js | 93 +- dashboard-ui/scripts/localsync.js | 46 +- dashboard-ui/scripts/loginpage.js | 249 +- dashboard-ui/scripts/medialibrarypage.js | 497 +-- dashboard-ui/scripts/metadataimagespage.js | 625 +--- dashboard-ui/scripts/metadatanfo.js | 107 +- dashboard-ui/scripts/metadatasubtitles.js | 104 +- dashboard-ui/scripts/moviecollections.js | 292 +- dashboard-ui/scripts/moviegenres.js | 247 +- dashboard-ui/scripts/movies.js | 341 +-- dashboard-ui/scripts/moviesrecommended.js | 355 +-- dashboard-ui/scripts/moviestudios.js | 76 +- dashboard-ui/scripts/movietrailers.js | 282 +- dashboard-ui/scripts/musicalbums.js | 284 +- dashboard-ui/scripts/musicartists.js | 249 +- dashboard-ui/scripts/musicfolders.js | 129 +- dashboard-ui/scripts/musicgenres.js | 164 +- dashboard-ui/scripts/musicrecommended.js | 398 +-- dashboard-ui/scripts/mypreferencescommon.js | 55 +- dashboard-ui/scripts/mypreferencesdisplay.js | 128 +- dashboard-ui/scripts/mypreferenceshome.js | 347 +-- .../scripts/mypreferenceslanguages.js | 202 +- dashboard-ui/scripts/myprofile.js | 219 +- dashboard-ui/scripts/mysync.js | 81 +- dashboard-ui/scripts/mysyncsettings.js | 67 +- dashboard-ui/scripts/notificationlist.js | 40 +- dashboard-ui/scripts/notifications.js | 217 +- dashboard-ui/scripts/notificationsetting.js | 194 +- dashboard-ui/scripts/notificationsettings.js | 88 +- dashboard-ui/scripts/nowplayingbar.js | 754 +---- dashboard-ui/scripts/nowplayingpage.js | 32 +- dashboard-ui/scripts/photos.js | 165 +- dashboard-ui/scripts/playbackconfiguration.js | 67 +- dashboard-ui/scripts/playlistedit.js | 118 +- dashboard-ui/scripts/playlists.js | 226 +- dashboard-ui/scripts/plugincatalogpage.js | 308 +- dashboard-ui/scripts/pluginspage.js | 251 +- dashboard-ui/scripts/reports.js | 1055 +------ dashboard-ui/scripts/scheduledtaskpage.js | 342 +-- dashboard-ui/scripts/scheduledtaskspage.js | 302 +- dashboard-ui/scripts/searchpage.js | 199 +- dashboard-ui/scripts/secondaryitems.js | 278 +- dashboard-ui/scripts/sections.js | 708 +---- dashboard-ui/scripts/selectserver.js | 389 +-- dashboard-ui/scripts/serversecurity.js | 159 +- dashboard-ui/scripts/shared.js | 92 +- dashboard-ui/scripts/site.js | 2686 +---------------- dashboard-ui/scripts/songs.js | 208 +- dashboard-ui/scripts/streamingsettings.js | 101 +- dashboard-ui/scripts/supporterkeypage.js | 176 +- dashboard-ui/scripts/syncactivity.js | 62 +- dashboard-ui/scripts/syncsettings.js | 93 +- dashboard-ui/scripts/taskbutton.js | 150 +- dashboard-ui/scripts/tvgenres.js | 248 +- dashboard-ui/scripts/tvlatest.js | 82 +- dashboard-ui/scripts/tvrecommended.js | 305 +- dashboard-ui/scripts/tvshows.js | 305 +- dashboard-ui/scripts/tvstudios.js | 78 +- dashboard-ui/scripts/tvupcoming.js | 155 +- dashboard-ui/scripts/useredit.js | 160 +- dashboard-ui/scripts/userlibraryaccess.js | 240 +- dashboard-ui/scripts/usernew.js | 174 +- dashboard-ui/scripts/userparentalcontrol.js | 356 +-- dashboard-ui/scripts/userpassword.js | 46 +- dashboard-ui/scripts/userpasswordpage.js | 228 +- dashboard-ui/scripts/userprofilespage.js | 410 +-- dashboard-ui/scripts/videoosd.js | 1048 +------ dashboard-ui/scripts/wizardagreement.js | 27 +- dashboard-ui/scripts/wizardcontroller.js | 22 +- dashboard-ui/scripts/wizardlivetvguide.js | 94 +- dashboard-ui/scripts/wizardlivetvtuner.js | 93 +- dashboard-ui/scripts/wizardsettings.js | 118 +- dashboard-ui/scripts/wizardstartpage.js | 72 +- dashboard-ui/scripts/wizarduserpage.js | 105 +- dashboard-ui/themes/halloween/style.css | 42 +- dashboard-ui/themes/halloween/theme.js | 126 +- dashboard-ui/themes/holiday/style.css | 66 +- dashboard-ui/themes/holiday/theme.js | 410 +-- .../jquerymobile-1.4.5/jqm.listview.css | 246 +- .../jquerymobile-1.4.5/jqm.panel.css | 289 +- .../jquerymobile-1.4.5/jqm.panel.js | 532 +--- .../jquerymobile-1.4.5/jqm.popup.css | 454 +-- .../jquerymobile-1.4.5/jqm.popup.js | 1285 +------- .../jquerymobile-1.4.5/jqm.slider.css | 281 +- .../jquerymobile-1.4.5/jqm.slider.js | 1028 +------ .../jquerymobile-1.4.5/jqm.table.css | 164 +- .../jquerymobile-1.4.5/jqm.table.js | 192 +- .../jquerymobile-1.4.5/jqm.widget.js | 615 +--- .../jstree/themes/default/style.css | 1048 +------ .../thirdparty/paper-button-style.css | 92 +- 201 files changed, 203 insertions(+), 52376 deletions(-) diff --git a/dashboard-ui/components/accessschedule/accessschedule.js b/dashboard-ui/components/accessschedule/accessschedule.js index 0218869846..278029bbec 100644 --- a/dashboard-ui/components/accessschedule/accessschedule.js +++ b/dashboard-ui/components/accessschedule/accessschedule.js @@ -1,114 +1 @@ -define(['dialogHelper', 'datetime', 'emby-select', 'paper-icon-button-light', 'formDialogStyle'], function (dialogHelper, datetime) { - 'use strict'; - - function getDisplayTime(hours) { - - var minutes = 0; - - var pct = hours % 1; - - if (pct) { - minutes = parseInt(pct * 60); - } - - return datetime.getDisplayTime(new Date(2000, 1, 1, hours, minutes, 0, 0)); - } - - function populateHours(context) { - - var html = ''; - - for (var i = 0; i < 24; i++) { - - html += ''; - } - - html += ''; - - context.querySelector('#selectStart').innerHTML = html; - context.querySelector('#selectEnd').innerHTML = html; - } - - function loadSchedule(context, schedule) { - - context.querySelector('#selectDay').value = schedule.DayOfWeek || 'Sunday'; - context.querySelector('#selectStart').value = schedule.StartHour || 0; - context.querySelector('#selectEnd').value = schedule.EndHour || 0; - } - - function submitSchedule(context, options) { - - var updatedSchedule = { - DayOfWeek: context.querySelector('#selectDay').value, - StartHour: context.querySelector('#selectStart').value, - EndHour: context.querySelector('#selectEnd').value - }; - - if (parseFloat(updatedSchedule.StartHour) >= parseFloat(updatedSchedule.EndHour)) { - - alert(Globalize.translate('ErrorMessageStartHourGreaterThanEnd')); - - return; - } - - context.submitted = true; - options.schedule = Object.assign(options.schedule, updatedSchedule); - dialogHelper.close(context); - } - - return { - show: function (options) { - return new Promise(function (resolve, reject) { - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/accessschedule/accessschedule.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - removeOnClose: true, - size: 'small' - }); - - dlg.classList.add('formDialog'); - - var html = ''; - - html += Globalize.translateDocument(template); - - dlg.innerHTML = html; - - populateHours(dlg); - loadSchedule(dlg, options.schedule); - - dialogHelper.open(dlg); - - dlg.addEventListener('close', function () { - - if (dlg.submitted) { - resolve(options.schedule); - } else { - reject(); - } - }); - - dlg.querySelector('.btnCancel').addEventListener('click', function (e) { - - dialogHelper.close(dlg); - }); - - dlg.querySelector('form').addEventListener('submit', function (e) { - - submitSchedule(dlg, options); - - e.preventDefault(); - return false; - }); - } - - xhr.send(); - }); - } - }; -}); \ No newline at end of file +define(["dialogHelper","datetime","emby-select","paper-icon-button-light","formDialogStyle"],function(dialogHelper,datetime){"use strict";function getDisplayTime(hours){var minutes=0,pct=hours%1;return pct&&(minutes=parseInt(60*pct)),datetime.getDisplayTime(new Date(2e3,1,1,hours,minutes,0,0))}function populateHours(context){for(var html="",i=0;i<24;i++)html+='";html+='",context.querySelector("#selectStart").innerHTML=html,context.querySelector("#selectEnd").innerHTML=html}function loadSchedule(context,schedule){context.querySelector("#selectDay").value=schedule.DayOfWeek||"Sunday",context.querySelector("#selectStart").value=schedule.StartHour||0,context.querySelector("#selectEnd").value=schedule.EndHour||0}function submitSchedule(context,options){var updatedSchedule={DayOfWeek:context.querySelector("#selectDay").value,StartHour:context.querySelector("#selectStart").value,EndHour:context.querySelector("#selectEnd").value};return parseFloat(updatedSchedule.StartHour)>=parseFloat(updatedSchedule.EndHour)?void alert(Globalize.translate("ErrorMessageStartHourGreaterThanEnd")):(context.submitted=!0,options.schedule=Object.assign(options.schedule,updatedSchedule),void dialogHelper.close(context))}return{show:function(options){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET","components/accessschedule/accessschedule.template.html",!0),xhr.onload=function(e){var template=this.response,dlg=dialogHelper.createDialog({removeOnClose:!0,size:"small"});dlg.classList.add("formDialog");var html="";html+=Globalize.translateDocument(template),dlg.innerHTML=html,populateHours(dlg),loadSchedule(dlg,options.schedule),dialogHelper.open(dlg),dlg.addEventListener("close",function(){dlg.submitted?resolve(options.schedule):reject()}),dlg.querySelector(".btnCancel").addEventListener("click",function(e){dialogHelper.close(dlg)}),dlg.querySelector("form").addEventListener("submit",function(e){return submitSchedule(dlg,options),e.preventDefault(),!1})},xhr.send()})}}}); \ No newline at end of file diff --git a/dashboard-ui/components/appfooter/appfooter.css b/dashboard-ui/components/appfooter/appfooter.css index 86a542f5f3..9f06e2b4db 100644 --- a/dashboard-ui/components/appfooter/appfooter.css +++ b/dashboard-ui/components/appfooter/appfooter.css @@ -1,20 +1 @@ -.appfooter { - background: #1c1c1c; - position: fixed; - left: 0; - right: 0; - z-index: 1; - bottom: 0; - transition: transform 180ms linear; - contain: layout style; -} - -.appfooter-blurred { - background: rgba(28,28,28,.92); - -webkit-backdrop-filter: blur(5px); - backdrop-filter: blur(5px); -} - -.appfooter.headroom--unpinned { - transform: translateY(100%); -} +.appfooter{background:#1c1c1c;position:fixed;left:0;right:0;z-index:1;bottom:0;-webkit-transition:-webkit-transform 180ms linear;-o-transition:transform 180ms linear;transition:transform 180ms linear;contain:layout style}.appfooter-blurred{background:rgba(28,28,28,.92);-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)}.appfooter.headroom--unpinned{-webkit-transform:translateY(100%);transform:translateY(100%)} \ No newline at end of file diff --git a/dashboard-ui/components/appfooter/appfooter.js b/dashboard-ui/components/appfooter/appfooter.js index 910db6f2e4..aa69377fb8 100644 --- a/dashboard-ui/components/appfooter/appfooter.js +++ b/dashboard-ui/components/appfooter/appfooter.js @@ -1,61 +1 @@ -define(['browser', 'css!./appfooter'], function (browser) { - 'use strict'; - - function render(options) { - - var elem = document.createElement('div'); - - elem.classList.add('appfooter'); - - if (browser.safari) { - elem.classList.add('appfooter-blurred'); - } - - document.body.appendChild(elem); - - return elem; - } - - function initHeadRoom(instance, elem) { - - require(["headroom-window"], function (headroom) { - - self.headroom = headroom; - headroom.add(elem); - }); - } - - function appFooter(options) { - - var self = this; - - self.element = render(options); - - self.add = function (elem) { - self.element.appendChild(elem); - }; - - self.insert = function (elem) { - if (typeof elem === 'string') { - self.element.insertAdjacentHTML('afterbegin', elem); - } else { - self.element.insertBefore(elem, self.element.firstChild); - } - }; - - initHeadRoom(self, self.element); - } - - appFooter.prototype.destroy = function () { - var self = this; - - if (self.headroom) { - self.headroom.remove(self.element); - self.headroom = null; - } - - self.element = null; - }; - - return appFooter; -}); \ No newline at end of file +define(["browser","css!./appfooter"],function(browser){"use strict";function render(options){var elem=document.createElement("div");return elem.classList.add("appfooter"),browser.safari&&elem.classList.add("appfooter-blurred"),document.body.appendChild(elem),elem}function initHeadRoom(instance,elem){require(["headroom-window"],function(headroom){self.headroom=headroom,headroom.add(elem)})}function appFooter(options){var self=this;self.element=render(options),self.add=function(elem){self.element.appendChild(elem)},self.insert=function(elem){"string"==typeof elem?self.element.insertAdjacentHTML("afterbegin",elem):self.element.insertBefore(elem,self.element.firstChild)},initHeadRoom(self,self.element)}return appFooter.prototype.destroy=function(){var self=this;self.headroom&&(self.headroom.remove(self.element),self.headroom=null),self.element=null},appFooter}); \ No newline at end of file diff --git a/dashboard-ui/components/apphost.js b/dashboard-ui/components/apphost.js index d6168974b1..6c7bd5b786 100644 --- a/dashboard-ui/components/apphost.js +++ b/dashboard-ui/components/apphost.js @@ -1,245 +1 @@ -define(['appStorage', 'browser'], function (appStorage, browser) { - 'use strict'; - - function getDeviceProfile() { - - // TODO - return null; - } - - function getCapabilities() { - - var caps = { - PlayableMediaTypes: ['Audio', 'Video'], - - SupportsPersistentIdentifier: false, - DeviceProfile: getDeviceProfile() - }; - - return caps; - } - - function generateDeviceId() { - return new Promise(function (resolve, reject) { - - require(["cryptojs-sha1"], function () { - - var keys = []; - keys.push(navigator.userAgent); - keys.push(new Date().getTime()); - - resolve(CryptoJS.SHA1(keys.join('|')).toString()); - }); - }); - } - - function getDeviceId() { - var key = '_deviceId2'; - var deviceId = appStorage.getItem(key); - - if (deviceId) { - return Promise.resolve(deviceId); - } else { - return generateDeviceId().then(function (deviceId) { - appStorage.setItem(key, deviceId); - return deviceId; - }); - } - } - - function getDeviceName() { - var deviceName; - - if (browser.tizen) { - deviceName = "Samsung Smart TV"; - } else if (browser.web0S) { - deviceName = "LG Smart TV"; - } else if (browser.operaTv) { - deviceName = "Opera TV"; - } else if (browser.xboxOne) { - deviceName = "Xbox One"; - } else if (browser.ps4) { - deviceName = "Sony PS4"; - } else if (browser.chrome) { - deviceName = "Chrome"; - } else if (browser.edge) { - deviceName = "Edge"; - } else if (browser.firefox) { - deviceName = "Firefox"; - } else if (browser.msie) { - deviceName = "Internet Explorer"; - } else { - deviceName = "Web Browser"; - } - - if (browser.version) { - deviceName += " " + browser.version; - } - - if (browser.ipad) { - deviceName += " Ipad"; - } else if (browser.iphone) { - deviceName += " Iphone"; - } else if (browser.android) { - deviceName += " Android"; - } - - return deviceName; - } - - function supportsVoiceInput() { - - if (browser.tv) { - return false; - } - - return window.SpeechRecognition || - window.webkitSpeechRecognition || - window.mozSpeechRecognition || - window.oSpeechRecognition || - window.msSpeechRecognition; - } - - function supportsFullscreen() { - - if (browser.tv) { - return false; - }; - - var element = document.documentElement; - - return element.requestFullscreen || - element.mozRequestFullScreen || - element.webkitRequestFullscreen || - element.msRequestFullscreen; - } - - function getSyncProfile() { - - return new Promise(function (resolve, reject) { - - require(['browserdeviceprofile', 'qualityoptions', 'appSettings'], function (profileBuilder, qualityoptions, appSettings) { - - var profile = profileBuilder(); - - profile.MaxStaticMusicBitrate = appSettings.maxStaticMusicBitrate(); - - resolve(profile); - }); - }); - } - - var supportedFeatures = function () { - - var features = [ - 'filedownload', - 'sharing', - 'externalpremium' - ]; - - if (browser.operaTv || browser.tizen || browser.web0s) { - features.push('exit'); - } else { - features.push('exitmenu'); - } - - if (!browser.operaTv) { - features.push('externallinks'); - } - - if (supportsVoiceInput()) { - features.push('voiceinput'); - } - - if (!browser.mobile || browser.edgeUwp) { - features.push('htmlaudioautoplay'); - features.push('htmlvideoautoplay'); - } - - if (window.SyncRegistered) { - //features.push('sync'); - } - - if (supportsFullscreen()) { - features.push('fullscreenchange'); - } - - if (browser.chrome || (browser.edge && !browser.slow)) { - features.push('imageanalysis'); - } - - if (Dashboard.isConnectMode()) { - features.push('multiserver'); - } - - if (browser.tv || browser.xboxOne || browser.ps4 || browser.mobile) { - features.push('physicalvolumecontrol'); - } - - if (!browser.tv && !browser.xboxOne && !browser.ps4) { - features.push('remotecontrol'); - } - - return features; - }(); - - var appInfo; - var version = window.dashboardVersion || '3.0'; - - return { - getWindowState: function () { - return document.windowState || 'Normal'; - }, - setWindowState: function (state) { - alert('setWindowState is not supported and should not be called'); - }, - exit: function () { - - if (browser.tizen) { - try { - tizen.application.getCurrentApplication().exit(); - } catch (err) { - console.log('error closing application: ' + err); - } - return; - } - - window.close(); - }, - supports: function (command) { - - return supportedFeatures.indexOf(command.toLowerCase()) != -1; - }, - unlockedFeatures: function () { - - var features = []; - - features.push('playback'); - features.push('livetv'); - - return features; - }, - appInfo: function () { - - if (appInfo) { - return Promise.resolve(appInfo); - } - - return getDeviceId().then(function (deviceId) { - - appInfo = { - deviceId: deviceId, - deviceName: getDeviceName(), - appName: 'Emby Mobile', - appVersion: version - }; - - return appInfo; - }); - }, - capabilities: getCapabilities, - preferVisualCards: browser.android || browser.chrome, - moreIcon: browser.safari || browser.edge ? 'dots-horiz' : 'dots-vert', - getSyncProfile: getSyncProfile - }; -}); \ No newline at end of file +define(["appStorage","browser"],function(appStorage,browser){"use strict";function getDeviceProfile(){return null}function getCapabilities(){var caps={PlayableMediaTypes:["Audio","Video"],SupportsPersistentIdentifier:!1,DeviceProfile:getDeviceProfile()};return caps}function generateDeviceId(){return new Promise(function(resolve,reject){require(["cryptojs-sha1"],function(){var keys=[];keys.push(navigator.userAgent),keys.push((new Date).getTime()),resolve(CryptoJS.SHA1(keys.join("|")).toString())})})}function getDeviceId(){var key="_deviceId2",deviceId=appStorage.getItem(key);return deviceId?Promise.resolve(deviceId):generateDeviceId().then(function(deviceId){return appStorage.setItem(key,deviceId),deviceId})}function getDeviceName(){var deviceName;return deviceName=browser.tizen?"Samsung Smart TV":browser.web0S?"LG Smart TV":browser.operaTv?"Opera TV":browser.xboxOne?"Xbox One":browser.ps4?"Sony PS4":browser.chrome?"Chrome":browser.edge?"Edge":browser.firefox?"Firefox":browser.msie?"Internet Explorer":"Web Browser",browser.version&&(deviceName+=" "+browser.version),browser.ipad?deviceName+=" Ipad":browser.iphone?deviceName+=" Iphone":browser.android&&(deviceName+=" Android"),deviceName}function supportsVoiceInput(){return!browser.tv&&(window.SpeechRecognition||window.webkitSpeechRecognition||window.mozSpeechRecognition||window.oSpeechRecognition||window.msSpeechRecognition)}function supportsFullscreen(){if(browser.tv)return!1;var element=document.documentElement;return element.requestFullscreen||element.mozRequestFullScreen||element.webkitRequestFullscreen||element.msRequestFullscreen}function getSyncProfile(){return new Promise(function(resolve,reject){require(["browserdeviceprofile","qualityoptions","appSettings"],function(profileBuilder,qualityoptions,appSettings){var profile=profileBuilder();profile.MaxStaticMusicBitrate=appSettings.maxStaticMusicBitrate(),resolve(profile)})})}var appInfo,supportedFeatures=function(){var features=["filedownload","sharing","externalpremium"];return browser.operaTv||browser.tizen||browser.web0s?features.push("exit"):features.push("exitmenu"),browser.operaTv||features.push("externallinks"),supportsVoiceInput()&&features.push("voiceinput"),browser.mobile&&!browser.edgeUwp||(features.push("htmlaudioautoplay"),features.push("htmlvideoautoplay")),window.SyncRegistered,supportsFullscreen()&&features.push("fullscreenchange"),(browser.chrome||browser.edge&&!browser.slow)&&features.push("imageanalysis"),Dashboard.isConnectMode()&&features.push("multiserver"),(browser.tv||browser.xboxOne||browser.ps4||browser.mobile)&&features.push("physicalvolumecontrol"),browser.tv||browser.xboxOne||browser.ps4||features.push("remotecontrol"),features}(),version=window.dashboardVersion||"3.0";return{getWindowState:function(){return document.windowState||"Normal"},setWindowState:function(state){alert("setWindowState is not supported and should not be called")},exit:function(){if(browser.tizen)try{tizen.application.getCurrentApplication().exit()}catch(err){console.log("error closing application: "+err)}else window.close()},supports:function(command){return supportedFeatures.indexOf(command.toLowerCase())!=-1},unlockedFeatures:function(){var features=[];return features.push("playback"),features.push("livetv"),features},appInfo:function(){return appInfo?Promise.resolve(appInfo):getDeviceId().then(function(deviceId){return appInfo={deviceId:deviceId,deviceName:getDeviceName(),appName:"Emby Mobile",appVersion:version}})},capabilities:getCapabilities,preferVisualCards:browser.android||browser.chrome,moreIcon:browser.safari||browser.edge?"dots-horiz":"dots-vert",getSyncProfile:getSyncProfile}}); \ No newline at end of file diff --git a/dashboard-ui/components/categorysyncbuttons.js b/dashboard-ui/components/categorysyncbuttons.js index 81ddc421a7..5e828ddeef 100644 --- a/dashboard-ui/components/categorysyncbuttons.js +++ b/dashboard-ui/components/categorysyncbuttons.js @@ -1,50 +1 @@ -define(['itemHelper'], function (itemHelper) { - 'use strict'; - - function initSyncButtons(view) { - - var apiClient = window.ApiClient; - - if (!apiClient || !apiClient.getCurrentUserId()) { - return; - } - - apiClient.getCurrentUser().then(function (user) { - - var item = { - SupportsSync: true - }; - - var categorySyncButtons = view.querySelectorAll('.categorySyncButton'); - for (var i = 0, length = categorySyncButtons.length; i < length; i++) { - categorySyncButtons[i].addEventListener('click', onCategorySyncButtonClick); - if (itemHelper.canSync(user, item)) { - categorySyncButtons[i].classList.remove('hide'); - } else { - categorySyncButtons[i].classList.add('hide'); - } - } - }); - } - - function onCategorySyncButtonClick(e) { - - var button = this; - var category = button.getAttribute('data-category'); - var parentId = LibraryMenu.getTopParentId(); - - require(['syncDialog'], function (syncDialog) { - syncDialog.showMenu({ - ParentId: parentId, - Category: category, - serverId: ApiClient.serverId() - }); - }); - } - - return { - init: function (view) { - initSyncButtons(view); - } - }; -}); \ No newline at end of file +define(["itemHelper"],function(itemHelper){"use strict";function initSyncButtons(view){var apiClient=window.ApiClient;apiClient&&apiClient.getCurrentUserId()&&apiClient.getCurrentUser().then(function(user){for(var item={SupportsSync:!0},categorySyncButtons=view.querySelectorAll(".categorySyncButton"),i=0,length=categorySyncButtons.length;imode_edit'; - - html += ''; - - return html; - } - - function getEditorHtml() { - - var html = ''; - - html += '
'; - html += '
'; - html += '
'; - - html += '

' + globalize.translate('HeaderChannels') + '

'; - - html += '
'; - html += '
'; - - html += '
'; - html += '
'; - html += '
'; - - return html; - } - - function initEditor(dlg, options) { - - getChannelMappingOptions(options.serverId, options.providerId).then(function (result) { - - currentMappingOptions = result; - - var channelsElement = dlg.querySelector('.channels'); - - channelsElement.innerHTML = result.TunerChannels.map(function (channel) { - return getTunerChannelHtml(channel, result.ProviderName); - }).join(''); - - channelsElement.addEventListener('click', onChannelsElementClick); - }); - } - - self.show = function () { - - var dialogOptions = { - removeOnClose: true - }; - - dialogOptions.size = 'small'; - - var dlg = dialogHelper.createDialog(dialogOptions); - - dlg.classList.add('formDialog'); - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - - var html = ''; - var title = globalize.translate('MapChannels'); - - html += '
'; - html += ''; - html += '

'; - html += title; - html += '

'; - - html += '
'; - - html += getEditorHtml(); - - dlg.innerHTML = html; - - initEditor(dlg, options); - - dlg.querySelector('.btnCancel').addEventListener('click', function () { - - dialogHelper.close(dlg); - }); - - return new Promise(function (resolve, reject) { - - dlg.addEventListener('close', resolve); - dialogHelper.open(dlg); - }); - }; - }; -}); \ No newline at end of file +define(["dialogHelper","loading","connectionManager","globalize","actionsheet","emby-input","paper-icon-button-light","emby-button","listViewStyle","material-icons","formDialogStyle"],function(dialogHelper,loading,connectionManager,globalize,actionsheet){"use strict";return function(options){function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function mapChannel(button,tunerChannelNumber,providerChannelNumber){loading.show();var providerId=options.providerId,apiClient=connectionManager.getApiClient(options.serverId);apiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/ChannelMappings"),data:{providerId:providerId,tunerChannelNumber:tunerChannelNumber,providerChannelNumber:providerChannelNumber},dataType:"json"}).then(function(mapping){var listItem=parentWithClass(button,"listItem");button.setAttribute("data-providernumber",mapping.ProviderChannelNumber),listItem.querySelector(".secondary").innerHTML=getMappingSecondaryName(mapping,currentMappingOptions.ProviderName),loading.hide()})}function onChannelsElementClick(e){var btnMap=parentWithClass(e.target,"btnMap");if(btnMap){var tunerChannelNumber=btnMap.getAttribute("data-number"),providerChannelNumber=btnMap.getAttribute("data-providernumber"),menuItems=currentMappingOptions.ProviderChannels.map(function(m){return{name:m.Name,id:m.Id,selected:m.Id.toLowerCase()==providerChannelNumber.toLowerCase()}});actionsheet.show({positionTo:btnMap,items:menuItems}).then(function(newChannelNumber){mapChannel(btnMap,tunerChannelNumber,newChannelNumber)})}}function getChannelMappingOptions(serverId,providerId){var apiClient=connectionManager.getApiClient(serverId);return apiClient.getJSON(apiClient.getUrl("LiveTv/ChannelMappingOptions",{providerId:providerId}))}function getMappingSecondaryName(mapping,providerName){return(mapping.ProviderChannelNumber||"")+" "+(mapping.ProviderChannelName||"")+" - "+providerName}function getTunerChannelHtml(channel,providerName){var html="";return html+='
',html+='dvr',html+='
',html+='

',html+=channel.Name,html+="

",html+='
',(channel.ProviderChannelNumber||channel.ProviderChannelName)&&(html+=getMappingSecondaryName(channel,providerName)),html+="
",html+="
",html+='',html+="
"}function getEditorHtml(){var html="";return html+='
',html+='
',html+='
',html+="

"+globalize.translate("HeaderChannels")+"

",html+='
',html+="
",html+="
",html+="
",html+="
"}function initEditor(dlg,options){getChannelMappingOptions(options.serverId,options.providerId).then(function(result){currentMappingOptions=result;var channelsElement=dlg.querySelector(".channels");channelsElement.innerHTML=result.TunerChannels.map(function(channel){return getTunerChannelHtml(channel,result.ProviderName)}).join(""),channelsElement.addEventListener("click",onChannelsElementClick)})}var currentMappingOptions,self=this;self.show=function(){var dialogOptions={removeOnClose:!0};dialogOptions.size="small";var dlg=dialogHelper.createDialog(dialogOptions);dlg.classList.add("formDialog"),dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a");var html="",title=globalize.translate("MapChannels");return html+='
',html+='',html+='

',html+=title,html+="

",html+="
",html+=getEditorHtml(),dlg.innerHTML=html,initEditor(dlg,options),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),new Promise(function(resolve,reject){dlg.addEventListener("close",resolve),dialogHelper.open(dlg)})}}}); \ No newline at end of file diff --git a/dashboard-ui/components/chromecasthelpers.js b/dashboard-ui/components/chromecasthelpers.js index def7031de2..c5a022d12d 100644 --- a/dashboard-ui/components/chromecasthelpers.js +++ b/dashboard-ui/components/chromecasthelpers.js @@ -1,234 +1 @@ -define(['events'], function (events) { - 'use strict'; - - // LinkParser - // - // https://github.com/ravisorg/LinkParser - // - // Locate and extract almost any URL within a string. Handles protocol-less domains, IPv4 and - // IPv6, unrecognised TLDs, and more. - // - // This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. - // http://creativecommons.org/licenses/by-sa/4.0/ - (function () { - - // Original URL regex from the Android android.text.util.Linkify function, found here: - // http://stackoverflow.com/a/19696443 - // - // However there were problems with it, most probably related to the fact it was - // written in 2007, and it's been highly modified. - // - // 1) I didn't like the fact that it was tied to specific TLDs, since new ones - // are being added all the time it wouldn't be reasonable to expect developer to - // be continually updating their regular expressions. - // - // 2) It didn't allow unicode characters in the domains which are now allowed in - // many languages, (including some IDN TLDs). Again these are constantly being - // added to and it doesn't seem reasonable to hard-code them. Note this ended up - // not being possible in standard JS due to the way it handles multibyte strings. - // It is possible using XRegExp, however a big performance hit results. Disabled - // for now. - // - // 3) It didn't allow for IPv6 hostnames - // IPv6 regex from http://stackoverflow.com/a/17871737 - // - // 4) It was very poorly commented - // - // 5) It wasn't as smart as it could have been about what should be part of a - // URL and what should be part of human language. - - var protocols = "(?:(?:http|https|rtsp|ftp):\\/\\/)"; - var credentials = "(?:(?:[a-z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-f0-9]{2})){1,64}" // username (1-64 normal or url escaped characters) - + "(?:\\:(?:[a-z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-f0-9]{2})){1,25})?" // followed by optional password (: + 1-25 normal or url escaped characters) - + "\\@)"; - - // IPv6 Regex http://forums.intermapper.com/viewtopic.php?t=452 - // by Dartware, LLC is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License - // http://intermapper.com/ - var ipv6 = "(" - + "(([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))" - + "|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))" - + "|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))" - + "|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))" - + "|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))" - + "|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))" - + "|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))" - + "|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))" - + ")(%.+)?"; - - var ipv4 = "(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\." - + "(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\." - + "(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\." - + "(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])"; - - // This would have been a lot cleaner if JS RegExp supported conditionals... - var linkRegExpString = - - // begin match for protocol / username / password / host - "(?:" - - // ============================ - // If we have a recognized protocol at the beginning of the URL, we're - // more relaxed about what we accept, because we assume the user wants - // this to be a URL, and we're not accidentally matching human language - + protocols + "?" - - // optional username:password@ - + credentials + "?" - - // IP address (both v4 and v6) - + "(?:" - - // IPv6 - + ipv6 - - // IPv4 - + "|" + ipv4 - - + ")" - - // end match for protocol / username / password / host - + ")" - - // optional port number - + "(?:\\:\\d{1,5})?" - - // plus optional path and query params (no unicode allowed here?) - + "(?:" - + "\\/(?:" - // some characters we'll accept because it's unlikely human language - // would use them after a URL unless they were part of the url - + "(?:[a-z0-9\\/\\@\\&\\#\\~\\*\\_\\-\\+])" - + "|(?:\\%[a-f0-9]{2})" - // some characters are much more likely to be used AFTER a url and - // were not intended to be included in the url itself. Mostly end - // of sentence type things. It's also likely that the URL would - // still work if any of these characters were missing from the end - // because we parsed it incorrectly. For these characters to be accepted - // they must be followed by another character that we're reasonably - // sure is part of the url - + "|(?:[\\;\\?\\:\\.\\!\\'\\(\\)\\,\\=]+(?=(?:[a-z0-9\\/\\@\\&\\#\\~\\*\\_\\-\\+])|(?:\\%[a-f0-9]{2})))" - + ")*" - + "|\\b|\$" - + ")"; - - // regex = XRegExp(regex,'gi'); - var linkRegExp = RegExp(linkRegExpString, 'gi'); - - var protocolRegExp = RegExp('^' + protocols, 'i'); - - // if url doesn't begin with a known protocol, add http by default - function ensureProtocol(url) { - if (!url.match(protocolRegExp)) { - url = "http://" + url; - } - return url; - } - - // look for links in the text - var LinkParser = { - - parse: function (text) { - var links = []; - var match; - - while (match = linkRegExp.exec(text)) { - // console.log(matches); - var txt = match[0]; - var pos = match['index']; - var len = txt.length; - var url = ensureProtocol(text); - links.push({ 'pos': pos, 'text': txt, 'len': len, 'url': url }); - } - - return links; - } - - } - - window.LinkParser = LinkParser; - })(); - - var cache = {}; - - function getEndpointInfo(apiClient) { - - return apiClient.getJSON(apiClient.getUrl('System/Endpoint')); - } - - function isValidIpAddress(address) { - - var links = LinkParser.parse(address); - - return links.length == 1; - } - - function isLocalIpAddress(address) { - - address = address.toLowerCase(); - - if (address.indexOf('127.0.0.1') != -1) { - return true; - } - if (address.indexOf('localhost') != -1) { - return true; - } - - return false; - } - - function getServerAddress(apiClient) { - - var serverAddress = apiClient.serverAddress(); - - if (isValidIpAddress(serverAddress) && !isLocalIpAddress(serverAddress)) { - return Promise.resolve(serverAddress); - } - - var cachedValue = getCachedValue(serverAddress); - if (cachedValue) { - return Promise.resolve(cachedValue); - } - - return apiClient.getJSON(apiClient.getUrl('System/Endpoint')).then(function (endpoint) { - if (endpoint.IsInNetwork) { - return apiClient.getPublicSystemInfo().then(function (info) { - addToCache(serverAddress, info.LocalAddress); - return info.LocalAddress; - }); - } else { - addToCache(serverAddress, serverAddress); - return serverAddress; - } - }); - } - - function clearCache() { - cache = {}; - } - - function addToCache(key, value) { - cache[key] = { - value: value, - time: new Date().getTime() - }; - } - - function getCachedValue(key) { - - var obj = cache[key]; - - if (obj && (new Date().getTime() - obj.time) < 180000) { - return obj.value; - } - - return null; - } - - events.on(ConnectionManager, 'localusersignedin', clearCache); - events.on(ConnectionManager, 'localusersignedout', clearCache); - - return { - getServerAddress: getServerAddress - }; -}); \ No newline at end of file +define(["events"],function(events){"use strict";function isValidIpAddress(address){var links=LinkParser.parse(address);return 1==links.length}function isLocalIpAddress(address){return address=address.toLowerCase(),address.indexOf("127.0.0.1")!=-1||address.indexOf("localhost")!=-1}function getServerAddress(apiClient){var serverAddress=apiClient.serverAddress();if(isValidIpAddress(serverAddress)&&!isLocalIpAddress(serverAddress))return Promise.resolve(serverAddress);var cachedValue=getCachedValue(serverAddress);return cachedValue?Promise.resolve(cachedValue):apiClient.getJSON(apiClient.getUrl("System/Endpoint")).then(function(endpoint){return endpoint.IsInNetwork?apiClient.getPublicSystemInfo().then(function(info){return addToCache(serverAddress,info.LocalAddress),info.LocalAddress}):(addToCache(serverAddress,serverAddress),serverAddress)})}function clearCache(){cache={}}function addToCache(key,value){cache[key]={value:value,time:(new Date).getTime()}}function getCachedValue(key){var obj=cache[key];return obj&&(new Date).getTime()-obj.time<18e4?obj.value:null}!function(){function ensureProtocol(url){return url.match(protocolRegExp)||(url="http://"+url),url}var protocols="(?:(?:http|https|rtsp|ftp):\\/\\/)",credentials="(?:(?:[a-z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-f0-9]{2})){1,64}(?:\\:(?:[a-z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-f0-9]{2})){1,25})?\\@)",ipv6="((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?",ipv4="(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])",linkRegExpString="(?:"+protocols+"?"+credentials+"?(?:"+ipv6+"|"+ipv4+"))(?:\\:\\d{1,5})?(?:\\/(?:(?:[a-z0-9\\/\\@\\&\\#\\~\\*\\_\\-\\+])|(?:\\%[a-f0-9]{2})|(?:[\\;\\?\\:\\.\\!\\'\\(\\)\\,\\=]+(?=(?:[a-z0-9\\/\\@\\&\\#\\~\\*\\_\\-\\+])|(?:\\%[a-f0-9]{2}))))*|\\b|$)",linkRegExp=RegExp(linkRegExpString,"gi"),protocolRegExp=RegExp("^"+protocols,"i"),LinkParser={parse:function(text){for(var match,links=[];match=linkRegExp.exec(text);){var txt=match[0],pos=match.index,len=txt.length,url=ensureProtocol(text);links.push({pos:pos,text:txt,len:len,url:url})}return links}};window.LinkParser=LinkParser}();var cache={};return events.on(ConnectionManager,"localusersignedin",clearCache),events.on(ConnectionManager,"localusersignedout",clearCache),{getServerAddress:getServerAddress}}); \ No newline at end of file diff --git a/dashboard-ui/components/directorybrowser/directorybrowser.css b/dashboard-ui/components/directorybrowser/directorybrowser.css index a985a800d7..81977499b7 100644 --- a/dashboard-ui/components/directorybrowser/directorybrowser.css +++ b/dashboard-ui/components/directorybrowser/directorybrowser.css @@ -1,16 +1 @@ -#ulDirectoryPickerList a { - padding-top: .4em; - padding-bottom: .4em; -} - -.lblDirectoryPickerPath { - white-space: nowrap; -} - -.directoryPickerHeadline { - color: #000; - background: #fff3a5; - padding: 1em; - border-radius: 5px; - margin-bottom: 1.5em; -} \ No newline at end of file +#ulDirectoryPickerList a{padding-top:.4em;padding-bottom:.4em}.lblDirectoryPickerPath{white-space:nowrap}.directoryPickerHeadline{color:#000;background:#fff3a5;padding:1em;-webkit-border-radius:5px;border-radius:5px;margin-bottom:1.5em} \ No newline at end of file diff --git a/dashboard-ui/components/directorybrowser/directorybrowser.js b/dashboard-ui/components/directorybrowser/directorybrowser.js index c8d9d94fa3..f23e481f0b 100644 --- a/dashboard-ui/components/directorybrowser/directorybrowser.js +++ b/dashboard-ui/components/directorybrowser/directorybrowser.js @@ -1,328 +1 @@ -define(['dialogHelper', 'dom', 'listViewStyle', 'emby-input', 'emby-button', 'paper-icon-button-light', 'css!./directorybrowser', 'formDialogStyle'], function (dialogHelper, dom) { - 'use strict'; - - var systemInfo; - function getSystemInfo() { - - var deferred = jQuery.Deferred(); - - if (systemInfo) { - deferred.resolveWith(null, [systemInfo]); - } else { - ApiClient.getPublicSystemInfo().then(function (info) { - systemInfo = info; - deferred.resolveWith(null, [systemInfo]); - }); - } - - return deferred.promise(); - } - - function onDialogClosed() { - - Dashboard.hideLoadingMsg(); - } - - function refreshDirectoryBrowser(page, path, fileOptions) { - - if (path && typeof (path) !== 'string') { - throw new Error('invalid path'); - } - Dashboard.showLoadingMsg(); - - var promises = []; - - if (path === "Network") { - promises.push(ApiClient.getNetworkDevices()); - } - else if (path) { - - promises.push(ApiClient.getDirectoryContents(path, fileOptions)); - promises.push(ApiClient.getParentPath(path)); - } else { - promises.push(ApiClient.getDrives()); - } - - Promise.all(promises).then(function (responses) { - - var folders = responses[0]; - var parentPath = responses[1] || ''; - - page.querySelector('#txtDirectoryPickerPath').value = path || ""; - - var html = ''; - - if (path) { - - html += getItem("lnkPath lnkDirectory", "", parentPath, '...'); - } - - for (var i = 0, length = folders.length; i < length; i++) { - - var folder = folders[i]; - - var cssClass = folder.Type == "File" ? "lnkPath lnkFile" : "lnkPath lnkDirectory"; - - html += getItem(cssClass, folder.Type, folder.Path, folder.Name); - } - - if (!path) { - html += getItem("lnkPath lnkDirectory", "", "Network", Globalize.translate('ButtonNetwork')); - } - - page.querySelector('.results').innerHTML = html; - - Dashboard.hideLoadingMsg(); - - }, function () { - - page.querySelector('#txtDirectoryPickerPath').value = ""; - page.querySelector('.results').innerHTML = ''; - - Dashboard.hideLoadingMsg(); - }); - } - - function getItem(cssClass, type, path, name) { - - var html = ''; - html += '
'; - html += '
'; - html += '
'; - html += name; - html += '
'; - html += '
'; - html += 'arrow_forward'; - html += '
'; - - return html; - } - - function getEditorHtml(options, systemInfo) { - - var html = ''; - - html += '
'; - html += '
'; - - if (!options.pathReadOnly) { - var instruction = options.instruction ? options.instruction + '

' : ''; - - html += '
'; - html += instruction; - html += Globalize.translate('MessageDirectoryPickerInstruction') - .replace('{0}', '\\\\server') - .replace('{1}', '\\\\192.168.1.101'); - - if (systemInfo.OperatingSystem.toLowerCase() == 'bsd') { - - html += '
'; - html += '
'; - html += Globalize.translate('MessageDirectoryPickerBSDInstruction'); - html += '
'; - html += '' + Globalize.translate('ButtonMoreInformation') + ''; - } - else if (systemInfo.OperatingSystem.toLowerCase() == 'linux') { - - html += '
'; - html += '
'; - html += Globalize.translate('MessageDirectoryPickerLinuxInstruction'); - html += '
'; - } - - html += '
'; - } - - html += '
'; - - html += '
'; - html += '
'; - var labelKey = options.includeFiles !== true ? 'LabelFolder' : 'LabelPath'; - var readOnlyAttribute = options.pathReadOnly ? ' readonly' : ''; - html += ''; - html += '
'; - - if (!readOnlyAttribute) { - html += ''; - } - - html += '
'; - - if (!readOnlyAttribute) { - html += '
'; - } - - if (options.enableNetworkSharePath) { - html += '
'; - html += ''; - html += '
'; - html += Globalize.translate('LabelOptionalNetworkPathHelp'); - html += '
'; - html += '
'; - } - - html += '
'; - html += ''; - html += '
'; - - html += '
'; - html += '
'; - - html += '
'; - html += ''; - - return html; - } - - function initEditor(content, options, fileOptions) { - - content.addEventListener("click", function (e) { - - var lnkPath = dom.parentWithClass(e.target, 'lnkPath'); - if (lnkPath) { - var path = lnkPath.getAttribute('data-path'); - - if (lnkPath.classList.contains('lnkFile')) { - content.querySelector('#txtDirectoryPickerPath').value = path; - } else { - refreshDirectoryBrowser(content, path, fileOptions); - } - } - }); - - content.addEventListener("click", function (e) { - - var btnRefreshDirectories = dom.parentWithClass(e.target, 'btnRefreshDirectories'); - if (btnRefreshDirectories) { - var path = content.querySelector('#txtDirectoryPickerPath').value; - - refreshDirectoryBrowser(content, path, fileOptions); - } - }); - - content.addEventListener("change", function (e) { - - var txtDirectoryPickerPath = dom.parentWithTag(e.target, 'INPUT'); - if (txtDirectoryPickerPath && txtDirectoryPickerPath.id == 'txtDirectoryPickerPath') { - refreshDirectoryBrowser(content, txtDirectoryPickerPath.value, fileOptions); - } - }); - - content.querySelector('form').addEventListener('submit', function (e) { - - if (options.callback) { - - var networkSharePath = this.querySelector('#txtNetworkPath'); - networkSharePath = networkSharePath ? networkSharePath.value : null; - options.callback(this.querySelector('#txtDirectoryPickerPath').value, networkSharePath); - } - - e.preventDefault(); - e.stopPropagation(); - return false; - }); - } - - function getDefaultPath(options) { - if (options.path) { - return Promise.resolve(options.path); - } - - return ApiClient.getJSON(ApiClient.getUrl("Environment/DefaultDirectoryBrowser")).then(function (result) { - - return result.Path || ''; - - }, function () { - return ''; - }); - } - - function directoryBrowser() { - - var self = this; - var currentDialog; - - self.show = function (options) { - - options = options || {}; - - var fileOptions = { - includeDirectories: true - }; - - if (options.includeDirectories != null) { - fileOptions.includeDirectories = options.includeDirectories; - } - - if (options.includeFiles != null) { - fileOptions.includeFiles = options.includeFiles; - } - - Promise.all([getSystemInfo(), getDefaultPath(options)]).then(function (responses) { - - var systemInfo = responses[0]; - var initialPath = responses[1]; - - var dlg = dialogHelper.createDialog({ - size: 'medium-tall', - removeOnClose: true, - scrollY: false - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - - dlg.classList.add('directoryPicker'); - dlg.classList.add('formDialog'); - - var html = ''; - html += '
'; - html += ''; - html += '

'; - html += options.header || Globalize.translate('HeaderSelectPath'); - html += '

'; - - html += '
'; - - html += getEditorHtml(options, systemInfo); - - dlg.innerHTML = html; - - initEditor(dlg, options, fileOptions); - - dlg.addEventListener('close', onDialogClosed); - - dialogHelper.open(dlg); - - dlg.querySelector('.btnCloseDialog').addEventListener('click', function () { - - dialogHelper.close(dlg); - }); - - currentDialog = dlg; - - var txtCurrentPath = dlg.querySelector('#txtDirectoryPickerPath'); - txtCurrentPath.value = initialPath; - - var txtNetworkPath = dlg.querySelector('#txtNetworkPath'); - if (txtNetworkPath) { - txtNetworkPath.value = options.networkSharePath || ''; - } - - if (!options.pathReadOnly) { - refreshDirectoryBrowser(dlg, txtCurrentPath.value); - } - - }); - }; - - self.close = function () { - if (currentDialog) { - dialogHelper.close(currentDialog); - } - }; - - } - - return directoryBrowser; -}); \ No newline at end of file +define(["dialogHelper","dom","listViewStyle","emby-input","emby-button","paper-icon-button-light","css!./directorybrowser","formDialogStyle"],function(dialogHelper,dom){"use strict";function getSystemInfo(){var deferred=jQuery.Deferred();return systemInfo?deferred.resolveWith(null,[systemInfo]):ApiClient.getPublicSystemInfo().then(function(info){systemInfo=info,deferred.resolveWith(null,[systemInfo])}),deferred.promise()}function onDialogClosed(){Dashboard.hideLoadingMsg()}function refreshDirectoryBrowser(page,path,fileOptions){if(path&&"string"!=typeof path)throw new Error("invalid path");Dashboard.showLoadingMsg();var promises=[];"Network"===path?promises.push(ApiClient.getNetworkDevices()):path?(promises.push(ApiClient.getDirectoryContents(path,fileOptions)),promises.push(ApiClient.getParentPath(path))):promises.push(ApiClient.getDrives()),Promise.all(promises).then(function(responses){var folders=responses[0],parentPath=responses[1]||"";page.querySelector("#txtDirectoryPickerPath").value=path||"";var html="";path&&(html+=getItem("lnkPath lnkDirectory","",parentPath,"..."));for(var i=0,length=folders.length;i',html+='
',html+='
',html+=name,html+="
",html+="
",html+='arrow_forward',html+=""}function getEditorHtml(options,systemInfo){var html="";if(html+='
',html+='
',!options.pathReadOnly){var instruction=options.instruction?options.instruction+"

":"";html+='
',html+=instruction,html+=Globalize.translate("MessageDirectoryPickerInstruction").replace("{0}","\\\\server").replace("{1}","\\\\192.168.1.101"),"bsd"==systemInfo.OperatingSystem.toLowerCase()?(html+="
",html+="
",html+=Globalize.translate("MessageDirectoryPickerBSDInstruction"),html+="
",html+=''+Globalize.translate("ButtonMoreInformation")+""):"linux"==systemInfo.OperatingSystem.toLowerCase()&&(html+="
",html+="
",html+=Globalize.translate("MessageDirectoryPickerLinuxInstruction"),html+="
"),html+="
"}html+='
',html+='
',html+='
';var labelKey=options.includeFiles!==!0?"LabelFolder":"LabelPath",readOnlyAttribute=options.pathReadOnly?" readonly":"";return html+='',html+="
",readOnlyAttribute||(html+=''),html+="
",readOnlyAttribute||(html+='
'),options.enableNetworkSharePath&&(html+='
',html+='',html+='
',html+=Globalize.translate("LabelOptionalNetworkPathHelp"),html+="
",html+="
"),html+='
',html+='",html+="
",html+="
",html+="
",html+="
",html+=""}function initEditor(content,options,fileOptions){content.addEventListener("click",function(e){var lnkPath=dom.parentWithClass(e.target,"lnkPath");if(lnkPath){var path=lnkPath.getAttribute("data-path");lnkPath.classList.contains("lnkFile")?content.querySelector("#txtDirectoryPickerPath").value=path:refreshDirectoryBrowser(content,path,fileOptions)}}),content.addEventListener("click",function(e){var btnRefreshDirectories=dom.parentWithClass(e.target,"btnRefreshDirectories");if(btnRefreshDirectories){var path=content.querySelector("#txtDirectoryPickerPath").value;refreshDirectoryBrowser(content,path,fileOptions)}}),content.addEventListener("change",function(e){var txtDirectoryPickerPath=dom.parentWithTag(e.target,"INPUT");txtDirectoryPickerPath&&"txtDirectoryPickerPath"==txtDirectoryPickerPath.id&&refreshDirectoryBrowser(content,txtDirectoryPickerPath.value,fileOptions)}),content.querySelector("form").addEventListener("submit",function(e){if(options.callback){var networkSharePath=this.querySelector("#txtNetworkPath");networkSharePath=networkSharePath?networkSharePath.value:null,options.callback(this.querySelector("#txtDirectoryPickerPath").value,networkSharePath)}return e.preventDefault(),e.stopPropagation(),!1})}function getDefaultPath(options){return options.path?Promise.resolve(options.path):ApiClient.getJSON(ApiClient.getUrl("Environment/DefaultDirectoryBrowser")).then(function(result){return result.Path||""},function(){return""})}function directoryBrowser(){var currentDialog,self=this;self.show=function(options){options=options||{};var fileOptions={includeDirectories:!0};null!=options.includeDirectories&&(fileOptions.includeDirectories=options.includeDirectories),null!=options.includeFiles&&(fileOptions.includeFiles=options.includeFiles),Promise.all([getSystemInfo(),getDefaultPath(options)]).then(function(responses){var systemInfo=responses[0],initialPath=responses[1],dlg=dialogHelper.createDialog({size:"medium-tall",removeOnClose:!0,scrollY:!1});dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a"),dlg.classList.add("directoryPicker"),dlg.classList.add("formDialog");var html="";html+='
',html+='',html+='

',html+=options.header||Globalize.translate("HeaderSelectPath"),html+="

",html+="
",html+=getEditorHtml(options,systemInfo),dlg.innerHTML=html,initEditor(dlg,options,fileOptions),dlg.addEventListener("close",onDialogClosed),dialogHelper.open(dlg),dlg.querySelector(".btnCloseDialog").addEventListener("click",function(){dialogHelper.close(dlg)}),currentDialog=dlg;var txtCurrentPath=dlg.querySelector("#txtDirectoryPickerPath");txtCurrentPath.value=initialPath;var txtNetworkPath=dlg.querySelector("#txtNetworkPath");txtNetworkPath&&(txtNetworkPath.value=options.networkSharePath||""),options.pathReadOnly||refreshDirectoryBrowser(dlg,txtCurrentPath.value)})},self.close=function(){currentDialog&&dialogHelper.close(currentDialog)}}var systemInfo;return directoryBrowser}); \ No newline at end of file diff --git a/dashboard-ui/components/dockedtabs/dockedtabs.css b/dashboard-ui/components/dockedtabs/dockedtabs.css index d6435c9760..71f89d2b6a 100644 --- a/dashboard-ui/components/dockedtabs/dockedtabs.css +++ b/dashboard-ui/components/dockedtabs/dockedtabs.css @@ -1,44 +1 @@ -.dockedtabs-tabs { - flex-grow: 1; - display: flex; - padding: .5em 0; - /* Override size from librarymenu */ - font-size: inherit; - font-size: 13px; -} - -.dockedtabs-tab-button { - flex-grow: 1; - align-items: center; - justify-content: center; - text-transform: none !important; - font-size: 12.4px !important; - padding: 0 !important; - margin: 0 !important; - text-align: center; - border-color: transparent !important; - border-width: 0 !important; -} - -.dockedtabs-tab-button { - display: flex; -} - -.dockedtabs-tab-button-noflex { - display: block; -} - -.dockedtabs-tab-button, .dockedtabs-tab-button-foreground { - font-weight: normal !important; -} - -.dockedtabs-tab-button-icon { - margin-bottom: .25em; - font-size: 22px; -} - -@media all and (max-width: 800px) { - .dockedtab-midsize { - display: none !important; - } -} +.dockedtabs-tabs{-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;display:-webkit-box;display:-webkit-flex;display:flex;padding:.5em 0;font-size:inherit;font-size:13px}.dockedtabs-tab-button{-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;text-transform:none!important;font-size:12.4px!important;padding:0!important;margin:0!important;text-align:center;border-color:transparent!important;border-width:0!important;display:-webkit-box;display:-webkit-flex;display:flex}.dockedtabs-tab-button-noflex{display:block}.dockedtabs-tab-button,.dockedtabs-tab-button-foreground{font-weight:400!important}.dockedtabs-tab-button-icon{margin-bottom:.25em;font-size:22px}@media all and (max-width:800px){.dockedtab-midsize{display:none!important}} \ No newline at end of file diff --git a/dashboard-ui/components/dockedtabs/dockedtabs.js b/dashboard-ui/components/dockedtabs/dockedtabs.js index d6bedc6711..03236c540b 100644 --- a/dashboard-ui/components/dockedtabs/dockedtabs.js +++ b/dashboard-ui/components/dockedtabs/dockedtabs.js @@ -1,378 +1 @@ -define(['apphost', 'connectionManager', 'events', 'globalize', 'browser', 'require', 'dom', 'embyRouter', 'emby-tabs'], function (appHost, connectionManager, events, globalize, browser, require, dom, embyRouter) { - 'use strict'; - - // Make sure this is pulled in after button and tab css - require(['css!./dockedtabs']); - - var currentUser = {}; - var currentUserViews = []; - - function showUserView(id) { - - var view = currentUserViews.filter(function (current) { - return current.Id == id; - })[0]; - - if (view) { - embyRouter.showItem(view); - } - } - - function executeCommand(id) { - - switch (id) { - - case 'settings': - embyRouter.showSettings(); - break; - case 'signout': - Dashboard.logout(); - break; - case 'selectserver': - embyRouter.showSelectServer(); - break; - case 'reports': - Dashboard.navigate('reports.html'); - break; - case 'metadatamanager': - Dashboard.navigate('edititemmetadata.html'); - break; - case 'manageserver': - Dashboard.navigate('dashboard.html'); - break; - case 'remotecontrol': - Dashboard.navigate('nowplaying.html'); - break; - case 'sync': - Dashboard.navigate('mysync.html'); - break; - default: - showUserView(id); - break; - } - } - - function showMenu(menuItems, button, tabIndex) { - - var actionSheetType = browser.safari ? 'actionsheet' : 'webActionSheet'; - - require([actionSheetType], function (actionSheet) { - - actionSheet.show({ - - items: menuItems, - positionTo: button, - entryAnimation: 'slideup', - exitAnimation: 'fadeout', - entryAnimationDuration: 160, - exitAnimationDuration: 100, - offsetTop: -35, - positionY: 'top', - dialogClass: 'dockedtabs-dlg', - menuItemClass: 'dockedtabs-dlg-menuitem' - - }).then(function (id) { - - executeCommand(id); - if (id) { - var tabs = dom.parentWithClass(button, 'dockedtabs-tabs'); - tabs.selectedIndex(tabIndex, false); - } - }); - }); - } - - function showLibrariesMenu(button) { - - var commands = currentUserViews.map(function (view) { - - return { - name: view.Name, - id: view.Id - }; - }); - - showMenu(commands, button, 1); - } - - function showMoreMenu(button) { - - var commands = []; - - commands.push({ - name: globalize.translate('ButtonRemoteControl'), - id: 'remotecontrol' - }); - - // manage server, metadata manager, reports, sync to other devices - if (currentUser.Policy.IsAdministrator) { - commands.push({ - name: globalize.translate('ButtonManageServer'), - id: 'manageserver' - }); - - if (dom.getWindowSize().innerWidth >= 1000) { - commands.push({ - name: globalize.translate('MetadataManager'), - id: 'metadatamanager' - }); - } - - commands.push({ - name: globalize.translate('ButtonReports'), - id: 'reports' - }); - } - - if (appHost.supports('multiserver')) { - commands.push({ - name: globalize.translate('HeaderSelectServer'), - id: 'selectserver' - }); - } - - commands.push({ - name: globalize.translate('TabSettings'), - id: 'settings' - }); - - if (currentUser.Policy.EnableSync) { - commands.push({ - name: globalize.translate('SyncToOtherDevices'), - id: 'sync' - }); - } - - commands.push({ - name: globalize.translate('ButtonSignOut'), - id: 'signout' - }); - - showMenu(commands, button, 5); - } - - function onTabClick(e) { - - var index = parseInt(this.getAttribute('data-index')); - - switch (index) { - - case 0: - embyRouter.goHome(); - break; - case 1: - showLibrariesMenu(this); - e.preventDefault(); - e.stopPropagation(); - break; - case 2: - embyRouter.showLiveTV(); - break; - case 3: - embyRouter.showFavorites(); - break; - case 4: - Dashboard.navigate('mysync.html?mode=offline'); - break; - case 5: - showMoreMenu(this); - e.preventDefault(); - e.stopPropagation(); - break; - case 6: - Dashboard.navigate('dashboard.html'); - break; - default: - break; - } - } - - function addNoFlexClass(buttons) { - - setTimeout(function () { - for (var i = 0, length = buttons.length; i < length; i++) { - - var button = buttons[i]; - - if (button.classList.contains('emby-button-noflex')) { - button.classList.add('dockedtabs-tab-button-noflex'); - } - } - }, 300); - } - - function render(options) { - - var elem = document.createElement('div'); - - elem.classList.add('hide'); - elem.classList.add('dockedtabs'); - elem.classList.add('dockedtabs-bottom'); - - // tabs: - // home - // favorites - // live tv - // now playing - - var html = ''; - - var liveTVButtonClass = appHost.supports('sync') ? ' dockedtab-midsize' : ''; - - html += '
\ - \ - \ - \ - \ -'; - - if (appHost.supports('sync')) { - html += '\ - '; - } - - html += '\ - '; - - html += '\ -
\ -'; - - elem.innerHTML = html; - - var buttons = elem.querySelectorAll('.emby-tab-button'); - for (var i = 0, length = buttons.length; i < length; i++) { - - var button = buttons[i]; - button.addEventListener('click', onTabClick); - } - addNoFlexClass(buttons); - - options.appFooter.add(elem); - - return elem; - } - - function onUserViewResponse(user, views, element) { - - if (views.filter(function (v) { - - return v.CollectionType == 'livetv'; - - }).length) { - element.querySelector('.docked-tab-livetv').classList.remove('hide'); - } else { - element.querySelector('.docked-tab-livetv').classList.add('hide'); - } - - var downloadsTab = element.querySelector('.docked-tab-syncdownloads'); - if (downloadsTab) { - if (user.Policy.EnableSync) { - downloadsTab.classList.remove('hide'); - } else { - downloadsTab.classList.add('hide'); - } - } - - if (user.Policy.IsAdministrator) { - element.querySelector('.docked-tab-manageserver').classList.remove('hide'); - } else { - element.querySelector('.docked-tab-manageserver').classList.add('hide'); - } - } - - function showUserTabs(user, element) { - - currentUser = user; - - var apiClient = ConnectionManager.getApiClient(user.ServerId); - - apiClient.getUserViews({}, user.Id).then(function (result) { - - currentUserViews = result.Items; - onUserViewResponse(user, result.Items, element); - - }, function () { - currentUserViews = []; - onUserViewResponse(user, [], element); - }); - } - - function showCurrentUserTabs(element) { - - if (!Dashboard.getCurrentUserId()) { - return; - } - - Dashboard.getCurrentUser().then(function (user) { - showUserTabs(user, element); - }); - } - - var instance; - - function onViewShow(e) { - if (e.detail.properties.indexOf('fullscreen') !== -1 || !Dashboard.getCurrentUserId()) { - instance.hide(); - } else { - instance.show(); - } - } - - function dockedTabs(options) { - - var self = this; - instance = self; - - self.element = render(options); - - events.on(connectionManager, 'localusersignedin', function (e, user) { - self.show(); - showUserTabs(user, self.element); - }); - - events.on(connectionManager, 'localusersignedout', function () { - self.hide(); - }); - - showCurrentUserTabs(self.element); - document.addEventListener('viewshow', onViewShow); - } - - dockedTabs.prototype.destroy = function () { - - document.removeEventListener('viewshow', onViewShow); - instance = null; - - var self = this; - - var elem = self.element; - if (elem) { - } - self.element = null; - }; - - dockedTabs.prototype.show = function () { - this.element.classList.remove('hide'); - }; - - dockedTabs.prototype.hide = function () { - this.element.classList.add('hide'); - }; - - return dockedTabs; -}); \ No newline at end of file +define(["apphost","connectionManager","events","globalize","browser","require","dom","embyRouter","emby-tabs"],function(appHost,connectionManager,events,globalize,browser,require,dom,embyRouter){"use strict";function showUserView(id){var view=currentUserViews.filter(function(current){return current.Id==id})[0];view&&embyRouter.showItem(view)}function executeCommand(id){switch(id){case"settings":embyRouter.showSettings();break;case"signout":Dashboard.logout();break;case"selectserver":embyRouter.showSelectServer();break;case"reports":Dashboard.navigate("reports.html");break;case"metadatamanager":Dashboard.navigate("edititemmetadata.html");break;case"manageserver":Dashboard.navigate("dashboard.html");break;case"remotecontrol":Dashboard.navigate("nowplaying.html");break;case"sync":Dashboard.navigate("mysync.html");break;default:showUserView(id)}}function showMenu(menuItems,button,tabIndex){var actionSheetType=browser.safari?"actionsheet":"webActionSheet";require([actionSheetType],function(actionSheet){actionSheet.show({items:menuItems,positionTo:button,entryAnimation:"slideup",exitAnimation:"fadeout",entryAnimationDuration:160,exitAnimationDuration:100,offsetTop:-35,positionY:"top",dialogClass:"dockedtabs-dlg",menuItemClass:"dockedtabs-dlg-menuitem"}).then(function(id){if(executeCommand(id),id){var tabs=dom.parentWithClass(button,"dockedtabs-tabs");tabs.selectedIndex(tabIndex,!1)}})})}function showLibrariesMenu(button){var commands=currentUserViews.map(function(view){return{name:view.Name,id:view.Id}});showMenu(commands,button,1)}function showMoreMenu(button){var commands=[];commands.push({name:globalize.translate("ButtonRemoteControl"),id:"remotecontrol"}),currentUser.Policy.IsAdministrator&&(commands.push({name:globalize.translate("ButtonManageServer"),id:"manageserver"}),dom.getWindowSize().innerWidth>=1e3&&commands.push({name:globalize.translate("MetadataManager"),id:"metadatamanager"}),commands.push({name:globalize.translate("ButtonReports"),id:"reports"})),appHost.supports("multiserver")&&commands.push({name:globalize.translate("HeaderSelectServer"),id:"selectserver"}),commands.push({name:globalize.translate("TabSettings"),id:"settings"}),currentUser.Policy.EnableSync&&commands.push({name:globalize.translate("SyncToOtherDevices"),id:"sync"}),commands.push({name:globalize.translate("ButtonSignOut"),id:"signout"}),showMenu(commands,button,5)}function onTabClick(e){var index=parseInt(this.getAttribute("data-index"));switch(index){case 0:embyRouter.goHome();break;case 1:showLibrariesMenu(this),e.preventDefault(),e.stopPropagation();break;case 2:embyRouter.showLiveTV();break;case 3:embyRouter.showFavorites();break;case 4:Dashboard.navigate("mysync.html?mode=offline");break;case 5:showMoreMenu(this),e.preventDefault(),e.stopPropagation();break;case 6:Dashboard.navigate("dashboard.html")}}function addNoFlexClass(buttons){setTimeout(function(){for(var i=0,length=buttons.length;i ",appHost.supports("sync")&&(html+=' "),html+=' ",html+=' ",elem.innerHTML=html;for(var buttons=elem.querySelectorAll(".emby-tab-button"),i=0,length=buttons.length;i= 1920 ? 10 : (screenWidth >= 1440 ? 8 : 6); - - if (enableScrollX()) { - options.Limit = 20; - } - } - - var promise; - if (section.types == 'MusicArtist') { - promise = ApiClient.getArtists(userId, options); - } else { - - options.IncludeItemTypes = section.types; - promise = ApiClient.getItems(userId, options); - } - - return promise.then(function (result) { - - var html = ''; - - if (result.Items.length) { - - html += '
'; - html += '

' + Globalize.translate(section.name) + '

'; - - if (options.Limit && result.Items.length >= options.Limit) { - var href = "secondaryitems.html?type=" + section.types + "&filters=IsFavorite"; - - html += ''; - } - - html += '
'; - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = (appHost.preferVisualCards || supportsImageAnalysis) && section.showTitle; - - html += cardBuilder.getCardsHtml(result.Items, { - preferThumb: section.preferThumb, - shape: section.shape, - centerText: section.centerText && !cardLayout, - overlayText: section.overlayText !== false, - showTitle: section.showTitle, - showParentTitle: section.showParentTitle, - scalable: true, - overlayPlayButton: section.overlayPlayButton, - overlayMoreButton: section.overlayMoreButton && !cardLayout, - action: section.action, - allowBottomPadding: !enableScrollX(), - cardLayout: cardLayout, - vibrant: supportsImageAnalysis && cardLayout - }); - - html += '
'; - } - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - }); - } - - function loadSections(page, userId, topParentId, types) { - - Dashboard.showLoadingMsg(); - - var sections = getSections(); - - var sectionid = getParameterByName('sectionid'); - - if (sectionid) { - sections = sections.filter(function (s) { - - return s.id == sectionid; - }); - } - - if (types) { - sections = sections.filter(function (s) { - - return types.indexOf(s.id) != -1; - }); - } - - var i, length; - - var elem = page.querySelector('.favoriteSections'); - - if (!elem.innerHTML) { - var html = ''; - for (i = 0, length = sections.length; i < length; i++) { - - html += '
'; - } - - elem.innerHTML = html; - } - - var promises = []; - - for (i = 0, length = sections.length; i < length; i++) { - - var section = sections[i]; - - elem = page.querySelector('.section' + section.id); - - promises.push(loadSection(elem, userId, topParentId, section, sections.length == 1)); - } - - Promise.all(promises).then(function () { - Dashboard.hideLoadingMsg(); - }); - } - - return { - render: loadSections - }; - -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","dom","apphost","imageLoader","scrollStyles","emby-itemscontainer"],function(libraryBrowser,cardBuilder,dom,appHost,imageLoader){"use strict";function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function getPosterShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getSquareShape(){return enableScrollX()?"overflowSquare":"square"}function getSections(){return[{name:"HeaderFavoriteMovies",types:"Movie",id:"favoriteMovies",shape:getPosterShape(),showTitle:!1,overlayPlayButton:!0},{name:"HeaderFavoriteShows",types:"Series",id:"favoriteShows",shape:getPosterShape(),showTitle:!1,overlayPlayButton:!0},{name:"HeaderFavoriteEpisodes",types:"Episode",id:"favoriteEpisode",shape:getThumbShape(),preferThumb:!1,showTitle:!0,showParentTitle:!0,overlayPlayButton:!0,overlayText:!1,centerText:!0},{name:"HeaderFavoriteGames",types:"Game",id:"favoriteGames",shape:getSquareShape(),preferThumb:!1,showTitle:!0},{name:"HeaderFavoriteArtists",types:"MusicArtist",id:"favoriteArtists",shape:getSquareShape(),preferThumb:!1,showTitle:!0,overlayText:!1,showParentTitle:!0,centerText:!0,overlayPlayButton:!0},{name:"HeaderFavoriteAlbums",types:"MusicAlbum",id:"favoriteAlbums",shape:getSquareShape(),preferThumb:!1,showTitle:!0,overlayText:!1,showParentTitle:!0,centerText:!0,overlayPlayButton:!0},{name:"HeaderFavoriteSongs",types:"Audio",id:"favoriteSongs",shape:getSquareShape(),preferThumb:!1,showTitle:!0,overlayText:!1,showParentTitle:!0,centerText:!0,overlayMoreButton:!0,action:"instantmix"}]}function loadSection(elem,userId,topParentId,section,isSingleSection){var screenWidth=dom.getWindowSize().innerWidth,options={SortBy:"SortName",SortOrder:"Ascending",Filters:"IsFavorite",Recursive:!0,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",CollapseBoxSetItems:!1,ExcludeLocationTypes:"Virtual",EnableTotalRecordCount:!1};topParentId&&(options.ParentId=topParentId),isSingleSection||(options.Limit=screenWidth>=1920?10:screenWidth>=1440?8:6,enableScrollX()&&(options.Limit=20));var promise;return"MusicArtist"==section.types?promise=ApiClient.getArtists(userId,options):(options.IncludeItemTypes=section.types,promise=ApiClient.getItems(userId,options)),promise.then(function(result){var html="";if(result.Items.length){if(html+="
",html+='

'+Globalize.translate(section.name)+"

",options.Limit&&result.Items.length>=options.Limit){var href="secondaryitems.html?type="+section.types+"&filters=IsFavorite";html+='"}html+="
",html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=(appHost.preferVisualCards||supportsImageAnalysis)&§ion.showTitle;html+=cardBuilder.getCardsHtml(result.Items,{preferThumb:section.preferThumb,shape:section.shape,centerText:section.centerText&&!cardLayout,overlayText:section.overlayText!==!1,showTitle:section.showTitle,showParentTitle:section.showParentTitle,scalable:!0,overlayPlayButton:section.overlayPlayButton,overlayMoreButton:section.overlayMoreButton&&!cardLayout,action:section.action,allowBottomPadding:!enableScrollX(),cardLayout:cardLayout,vibrant:supportsImageAnalysis&&cardLayout}),html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadSections(page,userId,topParentId,types){Dashboard.showLoadingMsg();var sections=getSections(),sectionid=getParameterByName("sectionid");sectionid&&(sections=sections.filter(function(s){return s.id==sectionid})),types&&(sections=sections.filter(function(s){return types.indexOf(s.id)!=-1}));var i,length,elem=page.querySelector(".favoriteSections");if(!elem.innerHTML){var html="";for(i=0,length=sections.length;i
';elem.innerHTML=html}var promises=[];for(i=0,length=sections.length;i' + s.Name + ''; - - }).join(''); - - existingSeriesHtml = '' + existingSeriesHtml; - - context.querySelector('#selectSeries').innerHTML = existingSeriesHtml; - - ApiClient.getVirtualFolders().then(function (result) { - - //var movieLocations = []; - var seriesLocations = []; - - for (var n = 0; n < result.length; n++) { - - var virtualFolder = result[n]; - - for (var i = 0, length = virtualFolder.Locations.length; i < length; i++) { - var location = { - value: virtualFolder.Locations[i], - display: virtualFolder.Name + ': ' + virtualFolder.Locations[i] - }; - - //if (virtualFolder.CollectionType == 'movies') { - // movieLocations.push(location); - //} - if (virtualFolder.CollectionType == 'tvshows') { - seriesLocations.push(location); - } - } - } - - seriesLocationsCount = seriesLocations.length; - - var seriesFolderHtml = seriesLocations.map(function (s) { - return ''; - }).join(''); - - if (seriesLocations.length > 1) { - // If the user has multiple folders, add an empty item to enforce a manual selection - seriesFolderHtml = '' + seriesFolderHtml; - } - - context.querySelector('#selectSeriesFolder').innerHTML = seriesFolderHtml; - - }, onApiFailure); - - }, onApiFailure); - } - - function submitEpisodeForm(dlg) { - - Dashboard.showLoadingMsg(); - - var resultId = dlg.querySelector('#hfResultId').value; - var seriesId = dlg.querySelector('#selectSeries').value; - - var targetFolder = null; - var newProviderIds = null; - var newSeriesName = null; - var newSeriesYear = null; - - if (seriesId == "##NEW##" && currentNewItem != null) { - seriesId = null; - newProviderIds = JSON.stringify(currentNewItem.ProviderIds); - newSeriesName = currentNewItem.Name; - newSeriesYear = currentNewItem.ProductionYear; - targetFolder = dlg.querySelector('#selectSeriesFolder').value; - } - - var options = { - - SeriesId: seriesId, - SeasonNumber: dlg.querySelector('#txtSeason').value, - EpisodeNumber: dlg.querySelector('#txtEpisode').value, - EndingEpisodeNumber: dlg.querySelector('#txtEndingEpisode').value, - RememberCorrection: dlg.querySelector('#chkRememberCorrection').checked, - NewSeriesProviderIds: newProviderIds, - NewSeriesName: newSeriesName, - NewSeriesYear: newSeriesYear, - TargetFolder: targetFolder - }; - - ApiClient.performEpisodeOrganization(resultId, options).then(function () { - - Dashboard.hideLoadingMsg(); - - dlg.submitted = true; - dialogHelper.close(dlg); - - }, onApiFailure); - } - - function showNewSeriesDialog(dlg) { - - if (seriesLocationsCount == 0) { - - require(['alert'], function (alert) { - alert({ - title: Globalize.translate('AutoOrganizeError'), - text: Globalize.translate('NoTvFoldersConfigured') - }); - }); - return; - } - - require(['itemIdentifier'], function (itemIdentifier) { - - itemIdentifier.showFindNew(extractedName, extractedYear, 'Series', ApiClient.serverId()).then(function (newItem) { - - if (newItem != null) { - currentNewItem = newItem; - var seriesHtml = existingSeriesHtml; - seriesHtml = seriesHtml + ''; - dlg.querySelector('#selectSeries').innerHTML = seriesHtml; - selectedSeriesChanged(dlg); - } - }); - }); - } - - function selectedSeriesChanged(dlg) { - var seriesId = dlg.querySelector('#selectSeries').value; - - if (seriesId == "##NEW##") { - dlg.querySelector('.fldSelectSeriesFolder').classList.remove('hide'); - dlg.querySelector('#selectSeriesFolder').setAttribute('required', 'required'); - } - else { - dlg.querySelector('.fldSelectSeriesFolder').classList.add('hide'); - dlg.querySelector('#selectSeriesFolder').removeAttribute('required'); - } - } - - return { - show: function (item) { - return new Promise(function (resolve, reject) { - - extractedName = null; - extractedYear = null; - currentNewItem = null; - existingSeriesHtml = null; - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/fileorganizer/fileorganizer.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - removeOnClose: true, - size: 'small' - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - - dlg.classList.add('formDialog'); - - var html = ''; - - html += Globalize.translateDocument(template); - - dlg.innerHTML = html; - - dlg.querySelector('.formDialogHeaderTitle').innerHTML = Globalize.translate('FileOrganizeManually'); - - dialogHelper.open(dlg); - - dlg.addEventListener('close', function () { - - if (dlg.submitted) { - resolve(); - } else { - reject(); - } - }); - - dlg.querySelector('.btnCancel').addEventListener('click', function (e) { - - dialogHelper.close(dlg); - }); - - dlg.querySelector('form').addEventListener('submit', function (e) { - - submitEpisodeForm(dlg); - - e.preventDefault(); - return false; - }); - - dlg.querySelector('#btnNewSeries').addEventListener('click', function (e) { - - showNewSeriesDialog(dlg); - }); - - dlg.querySelector('#selectSeries').addEventListener('change', function (e) { - - selectedSeriesChanged(dlg); - }); - - initEpisodeForm(dlg, item); - } - - xhr.send(); - }); - } - }; -}); \ No newline at end of file +define(["dialogHelper","emby-checkbox","emby-input","emby-button","emby-select","paper-icon-button-light","formDialogStyle"],function(dialogHelper){"use strict";function onApiFailure(e){Dashboard.hideLoadingMsg(),require(["alert"],function(alert){alert({title:Globalize.translate("AutoOrganizeError"),text:Globalize.translate("ErrorOrganizingFileWithErrorCode",e.headers.get("X-Application-Error-Code"))})})}function initEpisodeForm(context,item){!item.ExtractedName||item.ExtractedName.length<3?context.querySelector(".fldRemember").classList.add("hide"):context.querySelector(".fldRemember").classList.remove("hide"),context.querySelector(".inputFile").innerHTML=item.OriginalFileName,context.querySelector("#txtSeason").value=item.ExtractedSeasonNumber,context.querySelector("#txtEpisode").value=item.ExtractedEpisodeNumber,context.querySelector("#txtEndingEpisode").value=item.ExtractedEndingEpisodeNumber,extractedName=item.ExtractedName,extractedYear=item.ExtractedYear,context.querySelector("#chkRememberCorrection").checked=!1,context.querySelector("#hfResultId").value=item.Id,ApiClient.getItems(null,{recursive:!0,includeItemTypes:"Series",sortBy:"SortName"}).then(function(result){existingSeriesHtml=result.Items.map(function(s){return'"}).join(""),existingSeriesHtml=''+existingSeriesHtml,context.querySelector("#selectSeries").innerHTML=existingSeriesHtml,ApiClient.getVirtualFolders().then(function(result){for(var seriesLocations=[],n=0;n'+s.display+""}).join("");seriesLocations.length>1&&(seriesFolderHtml=''+seriesFolderHtml),context.querySelector("#selectSeriesFolder").innerHTML=seriesFolderHtml},onApiFailure)},onApiFailure)}function submitEpisodeForm(dlg){Dashboard.showLoadingMsg();var resultId=dlg.querySelector("#hfResultId").value,seriesId=dlg.querySelector("#selectSeries").value,targetFolder=null,newProviderIds=null,newSeriesName=null,newSeriesYear=null;"##NEW##"==seriesId&&null!=currentNewItem&&(seriesId=null,newProviderIds=JSON.stringify(currentNewItem.ProviderIds),newSeriesName=currentNewItem.Name,newSeriesYear=currentNewItem.ProductionYear,targetFolder=dlg.querySelector("#selectSeriesFolder").value);var options={SeriesId:seriesId,SeasonNumber:dlg.querySelector("#txtSeason").value,EpisodeNumber:dlg.querySelector("#txtEpisode").value,EndingEpisodeNumber:dlg.querySelector("#txtEndingEpisode").value,RememberCorrection:dlg.querySelector("#chkRememberCorrection").checked,NewSeriesProviderIds:newProviderIds,NewSeriesName:newSeriesName,NewSeriesYear:newSeriesYear,TargetFolder:targetFolder};ApiClient.performEpisodeOrganization(resultId,options).then(function(){Dashboard.hideLoadingMsg(),dlg.submitted=!0,dialogHelper.close(dlg)},onApiFailure)}function showNewSeriesDialog(dlg){return 0==seriesLocationsCount?void require(["alert"],function(alert){alert({title:Globalize.translate("AutoOrganizeError"),text:Globalize.translate("NoTvFoldersConfigured")})}):void require(["itemIdentifier"],function(itemIdentifier){itemIdentifier.showFindNew(extractedName,extractedYear,"Series",ApiClient.serverId()).then(function(newItem){if(null!=newItem){currentNewItem=newItem;var seriesHtml=existingSeriesHtml;seriesHtml=seriesHtml+'",dlg.querySelector("#selectSeries").innerHTML=seriesHtml,selectedSeriesChanged(dlg)}})})}function selectedSeriesChanged(dlg){var seriesId=dlg.querySelector("#selectSeries").value;"##NEW##"==seriesId?(dlg.querySelector(".fldSelectSeriesFolder").classList.remove("hide"),dlg.querySelector("#selectSeriesFolder").setAttribute("required","required")):(dlg.querySelector(".fldSelectSeriesFolder").classList.add("hide"),dlg.querySelector("#selectSeriesFolder").removeAttribute("required"))}var extractedName,extractedYear,currentNewItem,existingSeriesHtml,seriesLocationsCount=0;return{show:function(item){return new Promise(function(resolve,reject){extractedName=null,extractedYear=null,currentNewItem=null,existingSeriesHtml=null;var xhr=new XMLHttpRequest;xhr.open("GET","components/fileorganizer/fileorganizer.template.html",!0),xhr.onload=function(e){var template=this.response,dlg=dialogHelper.createDialog({removeOnClose:!0,size:"small"});dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a"),dlg.classList.add("formDialog");var html="";html+=Globalize.translateDocument(template),dlg.innerHTML=html,dlg.querySelector(".formDialogHeaderTitle").innerHTML=Globalize.translate("FileOrganizeManually"),dialogHelper.open(dlg),dlg.addEventListener("close",function(){dlg.submitted?resolve():reject()}),dlg.querySelector(".btnCancel").addEventListener("click",function(e){dialogHelper.close(dlg)}),dlg.querySelector("form").addEventListener("submit",function(e){return submitEpisodeForm(dlg),e.preventDefault(),!1}),dlg.querySelector("#btnNewSeries").addEventListener("click",function(e){showNewSeriesDialog(dlg)}),dlg.querySelector("#selectSeries").addEventListener("change",function(e){selectedSeriesChanged(dlg)}),initEpisodeForm(dlg,item)},xhr.send()})}}}); \ No newline at end of file diff --git a/dashboard-ui/components/filterdialog/filterdialog.js b/dashboard-ui/components/filterdialog/filterdialog.js index 28ec10dc2a..2a01c51292 100644 --- a/dashboard-ui/components/filterdialog/filterdialog.js +++ b/dashboard-ui/components/filterdialog/filterdialog.js @@ -1,587 +1 @@ -define(['dialogHelper', 'events', 'browser', 'emby-checkbox', 'emby-collapse', 'css!components/filterdialog/style'], function (dialogHelper, events, browser) { - 'use strict'; - - function renderOptions(context, selector, cssClass, items, isCheckedFn) { - - var elem = context.querySelector(selector); - - if (items.length) { - - elem.classList.remove('hide'); - - } else { - elem.classList.add('hide'); - } - - var html = ''; - - // style="margin: -.2em -.8em;" - html += '
'; - - html += items.map(function (filter) { - - var itemHtml = ''; - - var checkedHtml = isCheckedFn(filter) ? ' checked' : ''; - itemHtml += ''; - - return itemHtml; - - }).join(''); - - html += '
'; - - elem.querySelector('.filterOptions').innerHTML = html; - } - - function renderFilters(context, result, query) { - - // If there's a huge number of these they will be really show to render - if (result.Tags) { - result.Tags.length = Math.min(result.Tags.length, 50); - } - - renderOptions(context, '.genreFilters', 'chkGenreFilter', result.Genres, function (i) { - var delimeter = '|'; - return (delimeter + (query.Genres || '') + delimeter).indexOf(delimeter + i + delimeter) != -1; - }); - - renderOptions(context, '.officialRatingFilters', 'chkOfficialRatingFilter', result.OfficialRatings, function (i) { - var delimeter = '|'; - return (delimeter + (query.OfficialRatings || '') + delimeter).indexOf(delimeter + i + delimeter) != -1; - }); - - renderOptions(context, '.tagFilters', 'chkTagFilter', result.Tags, function (i) { - var delimeter = '|'; - return (delimeter + (query.Tags || '') + delimeter).indexOf(delimeter + i + delimeter) != -1; - }); - - renderOptions(context, '.yearFilters', 'chkYearFilter', result.Years, function (i) { - - var delimeter = ','; - return (delimeter + (query.Years || '') + delimeter).indexOf(delimeter + i + delimeter) != -1; - }); - } - - function loadDynamicFilters(context, userId, itemQuery) { - - return ApiClient.getJSON(ApiClient.getUrl('Items/Filters', { - - UserId: userId, - ParentId: itemQuery.ParentId, - IncludeItemTypes: itemQuery.IncludeItemTypes - - - })).then(function (result) { - - renderFilters(context, result, itemQuery); - }); - - } - - function updateFilterControls(context, options) { - - var query = options.query; - - var elems, i, length; - - if (options.mode == 'livetvchannels') { - - context.querySelector('.chkFavorite').checked = query.IsFavorite == true; - context.querySelector('.chkLikes').checked = query.IsLiked == true; - context.querySelector('.chkDislikes').checked = query.IsDisliked == true; - - } else { - elems = context.querySelectorAll('.chkStandardFilter'); - for (i = 0, length = elems.length; i < length; i++) { - - var chkStandardFilter = elems[i]; - var filters = "," + (query.Filters || ""); - var filterName = chkStandardFilter.getAttribute('data-filter'); - - chkStandardFilter.checked = filters.indexOf(',' + filterName) != -1; - } - } - - elems = context.querySelectorAll('.chkVideoTypeFilter'); - for (i = 0, length = elems.length; i < length; i++) { - - var chkVideoTypeFilter = elems[i]; - var filters = "," + (query.VideoTypes || ""); - var filterName = chkVideoTypeFilter.getAttribute('data-filter'); - - chkVideoTypeFilter.checked = filters.indexOf(',' + filterName) != -1; - } - - context.querySelector('.chk3DFilter').checked = query.Is3D == true; - context.querySelector('.chkHDFilter').checked = query.IsHD == true; - context.querySelector('.chkSDFilter').checked = query.IsHD == true; - - context.querySelector('#chkSubtitle').checked = query.HasSubtitles == true; - context.querySelector('#chkTrailer').checked = query.HasTrailer == true; - context.querySelector('#chkThemeSong').checked = query.HasThemeSong == true; - context.querySelector('#chkThemeVideo').checked = query.HasThemeVideo == true; - context.querySelector('#chkSpecialFeature').checked = query.HasSpecialFeature == true; - - context.querySelector('#chkSpecialEpisode').checked = query.ParentIndexNumber == 0; - context.querySelector('#chkMissingEpisode').checked = query.IsMissing == true; - context.querySelector('#chkFutureEpisode').checked = query.IsUnaired == true; - - //context.querySelector('.playersRadioGroup').selected = query.MinPlayers == null ? 'all' : query.MinPlayers; - - for (i = 0, length = elems.length; i < length; i++) { - - var chkStatus = elems[i]; - var filters = "," + (query.SeriesStatus || ""); - var filterName = chkStatus.getAttribute('data-filter'); - - chkStatus.checked = filters.indexOf(',' + filterName) != -1; - } - - elems = context.querySelectorAll('.chkAirDays'); - for (i = 0, length = elems.length; i < length; i++) { - - var chkAirDays = elems[i]; - var filters = "," + (query.AirDays || ""); - var filterName = chkAirDays.getAttribute('data-filter'); - - chkAirDays.checked = filters.indexOf(',' + filterName) != -1; - } - } - - function triggerChange(instance) { - - events.trigger(instance, 'filterchange'); - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function setVisibility(context, options) { - - if (options.mode == 'livetvchannels' || options.mode == 'albums' || options.mode == 'artists' || options.mode == 'albumartists' || options.mode == 'songs') { - hideByClass(context, 'videoStandard'); - } - - if (enableDynamicFilters(options.mode)) { - context.querySelector('.genreFilters').classList.remove('hide'); - context.querySelector('.officialRatingFilters').classList.remove('hide'); - context.querySelector('.tagFilters').classList.remove('hide'); - context.querySelector('.yearFilters').classList.remove('hide'); - } - - if (options.mode == 'movies' || options.mode == 'episodes') { - context.querySelector('.videoTypeFilters').classList.remove('hide'); - } - - if (options.mode == 'games') { - //context.querySelector('.players').classList.remove('hide'); - } - - if (options.mode == 'movies' || options.mode == 'series' || options.mode == 'games' || options.mode == 'episodes') { - context.querySelector('.features').classList.remove('hide'); - } - - if (options.mode == 'series') { - context.querySelector('.airdays').classList.remove('hide'); - context.querySelector('.seriesStatus').classList.remove('hide'); - } - - if (options.mode == 'episodes') { - showByClass(context, 'episodeFilter'); - } - } - - function showByClass(context, className) { - - var elems = context.querySelectorAll('.' + className); - - for (var i = 0, length = elems.length; i < length; i++) { - elems[i].classList.remove('hide'); - } - } - - function hideByClass(context, className) { - - var elems = context.querySelectorAll('.' + className); - - for (var i = 0, length = elems.length; i < length; i++) { - elems[i].classList.add('hide'); - } - } - - function enableDynamicFilters(mode) { - return mode == 'movies' || mode == 'games' || mode == 'series' || mode == 'albums' || mode == 'albumartists' || mode == 'artists' || mode == 'songs' || mode == 'episodes'; - } - - return function (options) { - - var self = this; - - function onFavoriteChange() { - var query = options.query; - query.StartIndex = 0; - query.IsFavorite = this.checked ? true : null; - triggerChange(self); - } - - function onStandardFilterChange() { - - var query = options.query; - var filterName = this.getAttribute('data-filter'); - var filters = query.Filters || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.StartIndex = 0; - query.Filters = filters; - triggerChange(self); - } - - function onVideoTypeFilterChange() { - - var query = options.query; - var filterName = this.getAttribute('data-filter'); - var filters = query.VideoTypes || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.StartIndex = 0; - query.VideoTypes = filters; - - triggerChange(self); - } - - function onStatusChange() { - var query = options.query; - var filterName = this.getAttribute('data-filter'); - var filters = query.SeriesStatus || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.SeriesStatus = filters; - query.StartIndex = 0; - triggerChange(self); - } - - function onAirDayChange() { - - var query = options.query; - var filterName = this.getAttribute('data-filter'); - var filters = query.AirDays || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.AirDays = filters; - query.StartIndex = 0; - triggerChange(self); - } - - function bindEvents(context) { - - var query = options.query; - var elems, i, length; - - if (options.mode == 'livetvchannels') { - - elems = context.querySelectorAll('.chkFavorite'); - for (i = 0, length = elems.length; i < length; i++) { - - elems[i].addEventListener('change', onFavoriteChange); - } - - - context.querySelector('.chkLikes').addEventListener('change', function () { - - query.StartIndex = 0; - query.IsLiked = this.checked ? true : null; - triggerChange(self); - }); - - context.querySelector('.chkDislikes').addEventListener('change', function () { - - query.StartIndex = 0; - query.IsDisliked = this.checked ? true : null; - triggerChange(self); - }); - - } else { - elems = context.querySelectorAll('.chkStandardFilter'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('change', onStandardFilterChange); - } - } - - elems = context.querySelectorAll('.chkVideoTypeFilter'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('change', onVideoTypeFilterChange); - } - - context.querySelector('.chk3DFilter').addEventListener('change', function () { - - query.StartIndex = 0; - query.Is3D = this.checked ? true : null; - - triggerChange(self); - }); - - context.querySelector('.chkHDFilter').addEventListener('change', function () { - - query.StartIndex = 0; - query.IsHD = this.checked ? true : null; - triggerChange(self); - }); - - context.querySelector('.chkSDFilter').addEventListener('change', function () { - - query.StartIndex = 0; - query.IsHD = this.checked ? false : null; - - triggerChange(self); - }); - - elems = context.querySelectorAll('.chkStatus'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('change', onStatusChange); - } - - elems = context.querySelectorAll('.chkAirDays'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('change', onAirDayChange); - } - - context.querySelector('#chkTrailer').addEventListener('change', function () { - query.StartIndex = 0; - query.HasTrailer = this.checked ? true : null; - - triggerChange(self); - }); - - context.querySelector('#chkThemeSong').addEventListener('change', function () { - query.StartIndex = 0; - query.HasThemeSong = this.checked ? true : null; - - triggerChange(self); - }); - - context.querySelector('#chkSpecialFeature').addEventListener('change', function () { - query.StartIndex = 0; - query.HasSpecialFeature = this.checked ? true : null; - - triggerChange(self); - }); - - context.querySelector('#chkThemeVideo').addEventListener('change', function () { - - query.StartIndex = 0; - query.HasThemeVideo = this.checked ? true : null; - - triggerChange(self); - }); - - context.querySelector('#chkMissingEpisode').addEventListener('change', function () { - - query.StartIndex = 0; - query.IsMissing = this.checked ? true : false; - - triggerChange(self); - }); - - context.querySelector('#chkSpecialEpisode').addEventListener('change', function () { - - query.StartIndex = 0; - query.ParentIndexNumber = this.checked ? 0 : null; - - triggerChange(self); - }); - - context.querySelector('#chkFutureEpisode').addEventListener('change', function () { - - query.StartIndex = 0; - - if (this.checked) { - query.IsUnaired = true; - query.IsVirtualUnaired = null; - } else { - query.IsUnaired = null; - query.IsVirtualUnaired = false; - } - - triggerChange(self); - }); - - context.querySelector('#chkSubtitle').addEventListener('change', function () { - - query.StartIndex = 0; - query.HasSubtitles = this.checked ? true : null; - - triggerChange(self); - }); - - //context.querySelector('.playersRadioGroup').addEventListener('iron-select', function (e) { - - // query.StartIndex = 0; - // var val = e.target.selected; - // var newValue = val == "all" ? null : val; - // var changed = query.MinPlayers != newValue; - // query.MinPlayers = newValue; - // if (changed) { - // triggerChange(self); - // } - //}); - - context.addEventListener('change', function (e) { - - var chkGenreFilter = parentWithClass(e.target, 'chkGenreFilter'); - if (chkGenreFilter) { - var filterName = chkGenreFilter.getAttribute('data-filter'); - var filters = query.Genres || ""; - var delimiter = '|'; - - filters = (delimiter + filters).replace(delimiter + filterName, '').substring(1); - - if (chkGenreFilter.checked) { - filters = filters ? (filters + delimiter + filterName) : filterName; - } - - query.StartIndex = 0; - query.Genres = filters; - - triggerChange(self); - return; - } - - var chkTagFilter = parentWithClass(e.target, 'chkTagFilter'); - if (chkTagFilter) { - var filterName = chkTagFilter.getAttribute('data-filter'); - var filters = query.Tags || ""; - var delimiter = '|'; - - filters = (delimiter + filters).replace(delimiter + filterName, '').substring(1); - - if (chkTagFilter.checked) { - filters = filters ? (filters + delimiter + filterName) : filterName; - } - - query.StartIndex = 0; - query.Tags = filters; - - triggerChange(self); - return; - } - - var chkYearFilter = parentWithClass(e.target, 'chkYearFilter'); - if (chkYearFilter) { - var filterName = chkYearFilter.getAttribute('data-filter'); - var filters = query.Years || ""; - var delimiter = ','; - - filters = (delimiter + filters).replace(delimiter + filterName, '').substring(1); - - if (chkYearFilter.checked) { - filters = filters ? (filters + delimiter + filterName) : filterName; - } - - query.StartIndex = 0; - query.Years = filters; - - triggerChange(self); - return; - } - - var chkOfficialRatingFilter = parentWithClass(e.target, 'chkOfficialRatingFilter'); - if (chkOfficialRatingFilter) { - var filterName = chkOfficialRatingFilter.getAttribute('data-filter'); - var filters = query.OfficialRatings || ""; - var delimiter = '|'; - - filters = (delimiter + filters).replace(delimiter + filterName, '').substring(1); - - if (chkOfficialRatingFilter.checked) { - filters = filters ? (filters + delimiter + filterName) : filterName; - } - - query.StartIndex = 0; - query.OfficialRatings = filters; - - triggerChange(self); - return; - } - }); - } - - self.show = function () { - return new Promise(function (resolve, reject) { - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/filterdialog/filterdialog.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - removeOnClose: true, - modal: false, - entryAnimationDuration: 160, - exitAnimationDuration: 200, - autoFocus: false - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - - dlg.classList.add('formDialog'); - dlg.classList.add('filterDialog'); - - dlg.innerHTML = Globalize.translateDocument(template); - - setVisibility(dlg, options); - - dialogHelper.open(dlg); - - dlg.addEventListener('close', resolve); - - updateFilterControls(dlg, options); - bindEvents(dlg); - - if (enableDynamicFilters(options.mode)) { - dlg.classList.add('dynamicFilterDialog'); - loadDynamicFilters(dlg, Dashboard.getCurrentUserId(), options.query); - } - } - - xhr.send(); - }); - }; - - }; -}); \ No newline at end of file +define(["dialogHelper","events","browser","emby-checkbox","emby-collapse","css!components/filterdialog/style"],function(dialogHelper,events,browser){"use strict";function renderOptions(context,selector,cssClass,items,isCheckedFn){var elem=context.querySelector(selector);items.length?elem.classList.remove("hide"):elem.classList.add("hide");var html="";html+='
',html+=items.map(function(filter){var itemHtml="",checkedHtml=isCheckedFn(filter)?" checked":"";return itemHtml+=""}).join(""),html+="
",elem.querySelector(".filterOptions").innerHTML=html}function renderFilters(context,result,query){result.Tags&&(result.Tags.length=Math.min(result.Tags.length,50)),renderOptions(context,".genreFilters","chkGenreFilter",result.Genres,function(i){var delimeter="|";return(delimeter+(query.Genres||"")+delimeter).indexOf(delimeter+i+delimeter)!=-1}),renderOptions(context,".officialRatingFilters","chkOfficialRatingFilter",result.OfficialRatings,function(i){var delimeter="|";return(delimeter+(query.OfficialRatings||"")+delimeter).indexOf(delimeter+i+delimeter)!=-1}),renderOptions(context,".tagFilters","chkTagFilter",result.Tags,function(i){var delimeter="|";return(delimeter+(query.Tags||"")+delimeter).indexOf(delimeter+i+delimeter)!=-1}),renderOptions(context,".yearFilters","chkYearFilter",result.Years,function(i){var delimeter=",";return(delimeter+(query.Years||"")+delimeter).indexOf(delimeter+i+delimeter)!=-1})}function loadDynamicFilters(context,userId,itemQuery){return ApiClient.getJSON(ApiClient.getUrl("Items/Filters",{UserId:userId,ParentId:itemQuery.ParentId,IncludeItemTypes:itemQuery.IncludeItemTypes})).then(function(result){renderFilters(context,result,itemQuery)})}function updateFilterControls(context,options){var elems,i,length,query=options.query;if("livetvchannels"==options.mode)context.querySelector(".chkFavorite").checked=1==query.IsFavorite,context.querySelector(".chkLikes").checked=1==query.IsLiked,context.querySelector(".chkDislikes").checked=1==query.IsDisliked;else for(elems=context.querySelectorAll(".chkStandardFilter"),i=0,length=elems.length;i' + i.Name + ''; - return currentHtml; - - }).join(''); - - context.querySelector('.librarySharingList').innerHTML = folderHtml; - } - - function inviteUser(dlg) { - - Dashboard.showLoadingMsg(); - - var shareExcludes = $(".chkShareFolder", dlg).get().filter(function (i) { - - return i.checked; - - }).map(function (i) { - - return i.getAttribute('data-folderid'); - }); - - require(['connectHelper'], function (connectHelper) { - - connectHelper.inviteGuest({ - apiClient: ApiClient, - guestOptions: { - - ConnectUsername: dlg.querySelector('#txtConnectUsername').value, - EnabledLibraries: shareExcludes.join(','), - SendingUserId: Dashboard.getCurrentUserId(), - EnableLiveTv: false - } - }).then(function() { - - dlg.submitted = true; - dialogHelper.close(dlg); - }); - }); - } - - return { - show: function () { - return new Promise(function (resolve, reject) { - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/guestinviter/guestinviter.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - removeOnClose: true, - size: 'small' - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - - dlg.classList.add('formDialog'); - - var html = ''; - - html += Globalize.translateDocument(template); - - dlg.innerHTML = html; - - dialogHelper.open(dlg); - - dlg.addEventListener('close', function () { - - if (dlg.submitted) { - resolve(); - } else { - reject(); - } - }); - - dlg.querySelector('.btnCancel').addEventListener('click', function (e) { - - dialogHelper.close(dlg); - }); - - dlg.querySelector('form').addEventListener('submit', function (e) { - - inviteUser(dlg); - - e.preventDefault(); - return false; - }); - - ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders", { IsHidden: false })).then(function (result) { - - renderLibrarySharingList(dlg, result); - }); - } - - xhr.send(); - }); - } - }; -}); \ No newline at end of file +define(["dialogHelper","jQuery","emby-input","emby-button","emby-checkbox","paper-icon-button-light","formDialogStyle"],function(dialogHelper,$){"use strict";function renderLibrarySharingList(context,result){var folderHtml="";folderHtml+=result.Items.map(function(i){var currentHtml="",isChecked=!0,checkedHtml=isChecked?' checked="checked"':"";return currentHtml+='"}).join(""),context.querySelector(".librarySharingList").innerHTML=folderHtml}function inviteUser(dlg){Dashboard.showLoadingMsg();var shareExcludes=$(".chkShareFolder",dlg).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-folderid")});require(["connectHelper"],function(connectHelper){connectHelper.inviteGuest({apiClient:ApiClient,guestOptions:{ConnectUsername:dlg.querySelector("#txtConnectUsername").value,EnabledLibraries:shareExcludes.join(","),SendingUserId:Dashboard.getCurrentUserId(),EnableLiveTv:!1}}).then(function(){dlg.submitted=!0,dialogHelper.close(dlg)})})}return{show:function(){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET","components/guestinviter/guestinviter.template.html",!0),xhr.onload=function(e){var template=this.response,dlg=dialogHelper.createDialog({removeOnClose:!0,size:"small"});dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a"),dlg.classList.add("formDialog");var html="";html+=Globalize.translateDocument(template),dlg.innerHTML=html,dialogHelper.open(dlg),dlg.addEventListener("close",function(){dlg.submitted?resolve():reject()}),dlg.querySelector(".btnCancel").addEventListener("click",function(e){dialogHelper.close(dlg)}),dlg.querySelector("form").addEventListener("submit",function(e){return inviteUser(dlg),e.preventDefault(),!1}),ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders",{IsHidden:!1})).then(function(result){renderLibrarySharingList(dlg,result)})},xhr.send()})}}}); \ No newline at end of file diff --git a/dashboard-ui/components/humanedate.js b/dashboard-ui/components/humanedate.js index 71b631a058..5ce5e26445 100644 --- a/dashboard-ui/components/humanedate.js +++ b/dashboard-ui/components/humanedate.js @@ -1,65 +1 @@ -define(['datetime'], function (datetime) { - 'use strict'; - - /* - * Javascript Humane Dates - * Copyright (c) 2008 Dean Landolt (deanlandolt.com) - * Re-write by Zach Leatherman (zachleat.com) - * - * Adopted from the John Resig's pretty.js - * at http://ejohn.org/blog/javascript-pretty-date - * and henrah's proposed modification - * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458 - * - * Licensed under the MIT license. - */ - - function humane_date(date_str) { - var time_formats = [[90, 'a minute'], // 60*1.5 - [3600, 'minutes', 60], // 60*60, 60 - [5400, 'an hour'], // 60*60*1.5 - [86400, 'hours', 3600], // 60*60*24, 60*60 - [129600, 'a day'], // 60*60*24*1.5 - [604800, 'days', 86400], // 60*60*24*7, 60*60*24 - [907200, 'a week'], // 60*60*24*7*1.5 - [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7 - [3942000, 'a month'], // 60*60*24*(365/12)*1.5 - [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12) - [47304000, 'a year'], // 60*60*24*365*1.5 - [3153600000, 'years', 31536000] // 60*60*24*365*100, 60*60*24*365 - ]; - - var dt = new Date; - var date = datetime.parseISO8601Date(date_str, true); - - var seconds = ((dt - date) / 1000); - var token = ' ago'; - var i = 0; - var format; - - if (seconds < 0) { - seconds = Math.abs(seconds); - //token = ''; - } - - while (format = time_formats[i++]) { - if (seconds < format[0]) { - if (format.length == 2) { - return format[1] + token; - } else { - return Math.round(seconds / format[2]) + ' ' + format[1] + token; - } - } - } - - // overflow for centuries - if (seconds > 4730400000) - return Math.round(seconds / 4730400000) + ' centuries' + token; - - return date_str; - } - - window.humane_date = humane_date; - - return humane_date; -}); \ No newline at end of file +define(["datetime"],function(datetime){"use strict";function humane_date(date_str){var format,time_formats=[[90,"a minute"],[3600,"minutes",60],[5400,"an hour"],[86400,"hours",3600],[129600,"a day"],[604800,"days",86400],[907200,"a week"],[2628e3,"weeks",604800],[3942e3,"a month"],[31536e3,"months",2628e3],[47304e3,"a year"],[31536e5,"years",31536e3]],dt=new Date,date=datetime.parseISO8601Date(date_str,!0),seconds=(dt-date)/1e3,token=" ago",i=0;for(seconds<0&&(seconds=Math.abs(seconds));format=time_formats[i++];)if(seconds47304e5?Math.round(seconds/47304e5)+" centuries"+token:date_str}return window.humane_date=humane_date,humane_date}); \ No newline at end of file diff --git a/dashboard-ui/components/iap.js b/dashboard-ui/components/iap.js index 1063790866..d06a88d066 100644 --- a/dashboard-ui/components/iap.js +++ b/dashboard-ui/components/iap.js @@ -1,74 +1 @@ -define(['apphost', 'globalize', 'shell'], function (appHost, globalize, shell) { - 'use strict'; - - function getProductInfo(feature) { - return null; - } - - function showExternalPremiereInfo() { - shell.openUrl('https://emby.media/premiere'); - } - - function beginPurchase(feature, email) { - showExternalPremiereInfo(); - return Promise.reject(); - } - - function restorePurchase(id) { - return Promise.reject(); - } - - function getSubscriptionOptions() { - - var options = []; - - options.push({ - id: 'embypremiere', - title: globalize.translate('sharedcomponents#HeaderBecomeProjectSupporter'), - requiresEmail: false - }); - - return Promise.resolve(options); - } - - function isUnlockedByDefault(feature, options) { - - var autoUnlockedFeatures = appHost.unlockedFeatures ? appHost.unlockedFeatures() : []; - if (autoUnlockedFeatures.indexOf(feature) != -1) { - - return Promise.resolve(); - } - - return Promise.reject(); - } - - function getAdminFeatureName(feature) { - - return feature; - } - - function getRestoreButtonText() { - return globalize.translate('sharedcomponents#ButtonAlreadyPaid'); - } - - function getPeriodicMessageIntervalMs(feature) { - - if (feature === 'playback') { - return 43200000; - } - - return 0; - } - - return { - getProductInfo: getProductInfo, - beginPurchase: beginPurchase, - restorePurchase: restorePurchase, - getSubscriptionOptions: getSubscriptionOptions, - isUnlockedByDefault: isUnlockedByDefault, - getAdminFeatureName: getAdminFeatureName, - getRestoreButtonText: getRestoreButtonText, - getPeriodicMessageIntervalMs: getPeriodicMessageIntervalMs - }; - -}); \ No newline at end of file +define(["apphost","globalize","shell"],function(appHost,globalize,shell){"use strict";function getProductInfo(feature){return null}function showExternalPremiereInfo(){shell.openUrl("https://emby.media/premiere")}function beginPurchase(feature,email){return showExternalPremiereInfo(),Promise.reject()}function restorePurchase(id){return Promise.reject()}function getSubscriptionOptions(){var options=[];return options.push({id:"embypremiere",title:globalize.translate("sharedcomponents#HeaderBecomeProjectSupporter"),requiresEmail:!1}),Promise.resolve(options)}function isUnlockedByDefault(feature,options){var autoUnlockedFeatures=appHost.unlockedFeatures?appHost.unlockedFeatures():[];return autoUnlockedFeatures.indexOf(feature)!=-1?Promise.resolve():Promise.reject()}function getAdminFeatureName(feature){return feature}function getRestoreButtonText(){return globalize.translate("sharedcomponents#ButtonAlreadyPaid")}function getPeriodicMessageIntervalMs(feature){return"playback"===feature?432e5:0}return{getProductInfo:getProductInfo,beginPurchase:beginPurchase,restorePurchase:restorePurchase,getSubscriptionOptions:getSubscriptionOptions,isUnlockedByDefault:isUnlockedByDefault,getAdminFeatureName:getAdminFeatureName,getRestoreButtonText:getRestoreButtonText,getPeriodicMessageIntervalMs:getPeriodicMessageIntervalMs}}); \ No newline at end of file diff --git a/dashboard-ui/components/imagedownloader/imagedownloader.js b/dashboard-ui/components/imagedownloader/imagedownloader.js index 0807f7357b..0559a8be9e 100644 --- a/dashboard-ui/components/imagedownloader/imagedownloader.js +++ b/dashboard-ui/components/imagedownloader/imagedownloader.js @@ -1,370 +1 @@ -define(['dialogHelper', 'imageLoader', 'emby-checkbox', 'emby-button', 'paper-icon-button-light', 'css!css/metadataeditor.css'], function (dialogHelper, imageLoader) { - 'use strict'; - - var currentItemId; - var currentItemType; - var currentResolve; - var currentReject; - var hasChanges = false; - - // These images can be large and we're seeing memory problems in safari - var browsableImagePageSize = browserInfo.slow ? 6 : 30; - - var browsableImageStartIndex = 0; - var browsableImageType = 'Primary'; - var selectedProvider; - - function getBaseRemoteOptions() { - - var options = {}; - - options.itemId = currentItemId; - - return options; - } - - function reloadBrowsableImages(page) { - - Dashboard.showLoadingMsg(); - - var options = getBaseRemoteOptions(); - - options.type = browsableImageType; - options.startIndex = browsableImageStartIndex; - options.limit = browsableImagePageSize; - options.IncludeAllLanguages = page.querySelector('#chkAllLanguages').checked; - - var provider = selectedProvider || ''; - - if (provider) { - options.ProviderName = provider; - } - - ApiClient.getAvailableRemoteImages(options).then(function (result) { - - renderRemoteImages(page, result, browsableImageType, options.startIndex, options.limit); - - page.querySelector('#selectBrowsableImageType').value = browsableImageType; - - var providersHtml = result.Providers.map(function (p) { - return ''; - }); - - var selectImageProvider = page.querySelector('#selectImageProvider'); - selectImageProvider.innerHTML = '' + providersHtml; - selectImageProvider.value = provider; - - Dashboard.hideLoadingMsg(); - }); - - } - - function renderRemoteImages(page, imagesResult, imageType, startIndex, limit) { - - page.querySelector('.availableImagesPaging').innerHTML = getPagingHtml(startIndex, limit, imagesResult.TotalRecordCount); - - var html = ''; - - for (var i = 0, length = imagesResult.Images.length; i < length; i++) { - - html += getRemoteImageHtml(imagesResult.Images[i], imageType); - } - - var availableImagesList = page.querySelector('.availableImagesList'); - availableImagesList.innerHTML = html; - imageLoader.lazyChildren(availableImagesList); - - var btnNextPage = page.querySelector('.btnNextPage'); - var btnPreviousPage = page.querySelector('.btnPreviousPage'); - - if (btnNextPage) { - btnNextPage.addEventListener('click', function () { - browsableImageStartIndex += browsableImagePageSize; - reloadBrowsableImages(page); - }); - } - - if (btnPreviousPage) { - btnPreviousPage.addEventListener('click', function () { - browsableImageStartIndex -= browsableImagePageSize; - reloadBrowsableImages(page); - }); - } - - } - - function getPagingHtml(startIndex, limit, totalRecordCount) { - - var html = ''; - - var recordsEnd = Math.min(startIndex + limit, totalRecordCount); - - // 20 is the minimum page size - var showControls = totalRecordCount > limit; - - html += '
'; - - html += ''; - - var startAtDisplay = totalRecordCount ? startIndex + 1 : 0; - html += startAtDisplay + '-' + recordsEnd + ' of ' + totalRecordCount; - - html += ''; - - if (showControls) { - html += '
'; - - html += ''; - html += ''; - html += '
'; - } - - html += '
'; - - return html; - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function downloadRemoteImage(page, url, type, provider) { - - var options = getBaseRemoteOptions(); - - options.Type = type; - options.ImageUrl = url; - options.ProviderName = provider; - - Dashboard.showLoadingMsg(); - - ApiClient.downloadRemoteImage(options).then(function () { - - hasChanges = true; - var dlg = parentWithClass(page, 'dialog'); - dialogHelper.close(dlg); - }); - } - - function getDisplayUrl(url) { - return ApiClient.getUrl("Images/Remote", { imageUrl: url }); - } - - function getRemoteImageHtml(image, imageType) { - - var html = ''; - - html += '
'; - - var cssClass = "remoteImage lazy"; - - if (imageType == "Backdrop" || imageType == "Art" || imageType == "Thumb" || imageType == "Logo") { - cssClass += " remoteBackdropImage"; - } - else if (imageType == "Banner") { - cssClass += " remoteBannerImage"; - } - else if (imageType == "Disc") { - cssClass += " remoteDiscImage"; - } - else { - - if (currentItemType == "Episode") { - cssClass += " remoteBackdropImage"; - } - else if (currentItemType == "MusicAlbum" || currentItemType == "MusicArtist") { - cssClass += " remoteDiscImage"; - } - else { - cssClass += " remotePosterImage"; - } - } - - var displayUrl = getDisplayUrl(image.ThumbnailUrl || image.Url); - - html += ''; - html += ''; - - html += '
'; - - html += '
'; - html += image.ProviderName; - html += '
'; - - if (image.Width || image.Height || image.Language) { - - html += '
'; - - if (image.Width && image.Height) { - html += image.Width + ' x ' + image.Height; - - if (image.Language) { - - html += ' • ' + image.Language; - } - } else { - if (image.Language) { - - html += image.Language; - } - } - - html += '
'; - } - - if (image.CommunityRating != null) { - - html += '
'; - - if (image.RatingType == "Likes") { - html += image.CommunityRating + (image.CommunityRating == 1 ? " like" : " likes"); - } else { - - if (image.CommunityRating) { - html += image.CommunityRating.toFixed(1); - - if (image.VoteCount) { - html += ' • ' + image.VoteCount + (image.VoteCount == 1 ? " vote" : " votes"); - } - } else { - html += "Unrated"; - } - } - - html += '
'; - } - - html += ''; - - html += '
'; - html += '
'; - - return html; - } - - function initEditor(page) { - - - page.querySelector('#selectBrowsableImageType').addEventListener('change', function () { - browsableImageType = this.value; - browsableImageStartIndex = 0; - selectedProvider = null; - - reloadBrowsableImages(page); - }); - - page.querySelector('#selectImageProvider').addEventListener('change', function () { - - browsableImageStartIndex = 0; - selectedProvider = this.value; - - reloadBrowsableImages(page); - }); - - page.querySelector('#chkAllLanguages').addEventListener('change', function () { - - browsableImageStartIndex = 0; - - reloadBrowsableImages(page); - }); - - page.addEventListener('click', function (e) { - - var btnDownloadRemoteImage = parentWithClass(e.target, 'btnDownloadRemoteImage'); - if (btnDownloadRemoteImage) { - downloadRemoteImage(page, btnDownloadRemoteImage.getAttribute('data-imageurl'), btnDownloadRemoteImage.getAttribute('data-imagetype'), btnDownloadRemoteImage.getAttribute('data-imageprovider')); - } - }); - } - - function showEditor(itemId, itemType) { - - Dashboard.showLoadingMsg(); - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/imagedownloader/imagedownloader.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - currentItemId = itemId; - currentItemType = itemType; - - var dlg = dialogHelper.createDialog({ - size: 'fullscreen-border', - lockScroll: true, - removeOnClose: true - }); - - var theme = 'b'; - - dlg.classList.add('ui-body-' + theme); - dlg.classList.add('background-theme-' + theme); - - var html = ''; - html += '

'; - html += ''; - html += '
' + Globalize.translate('HeaderSearch') + '
'; - html += '

'; - - html += '
'; - html += Globalize.translateDocument(template); - html += '
'; - - dlg.innerHTML = html; - - // Has to be assigned a z-index after the call to .open() - dlg.addEventListener('close', onDialogClosed); - - dialogHelper.open(dlg); - - var editorContent = dlg.querySelector('.editorContent'); - initEditor(editorContent); - - dlg.querySelector('.btnCloseDialog').addEventListener('click', function () { - - dialogHelper.close(dlg); - }); - - reloadBrowsableImages(editorContent); - } - - xhr.send(); - } - - function onDialogClosed() { - - Dashboard.hideLoadingMsg(); - if (hasChanges) { - currentResolve(); - } else { - currentReject(); - } - } - - return { - show: function (itemId, itemType, imageType) { - - return new Promise(function (resolve, reject) { - - currentResolve = resolve; - currentReject = reject; - hasChanges = false; - browsableImageStartIndex = 0; - browsableImageType = imageType || 'Primary'; - selectedProvider = null; - - showEditor(itemId, itemType); - }); - } - }; -}); \ No newline at end of file +define(["dialogHelper","imageLoader","emby-checkbox","emby-button","paper-icon-button-light","css!css/metadataeditor.css"],function(dialogHelper,imageLoader){"use strict";function getBaseRemoteOptions(){var options={};return options.itemId=currentItemId,options}function reloadBrowsableImages(page){Dashboard.showLoadingMsg();var options=getBaseRemoteOptions();options.type=browsableImageType,options.startIndex=browsableImageStartIndex,options.limit=browsableImagePageSize,options.IncludeAllLanguages=page.querySelector("#chkAllLanguages").checked;var provider=selectedProvider||"";provider&&(options.ProviderName=provider),ApiClient.getAvailableRemoteImages(options).then(function(result){renderRemoteImages(page,result,browsableImageType,options.startIndex,options.limit),page.querySelector("#selectBrowsableImageType").value=browsableImageType;var providersHtml=result.Providers.map(function(p){return'"}),selectImageProvider=page.querySelector("#selectImageProvider");selectImageProvider.innerHTML='"+providersHtml,selectImageProvider.value=provider,Dashboard.hideLoadingMsg()})}function renderRemoteImages(page,imagesResult,imageType,startIndex,limit){page.querySelector(".availableImagesPaging").innerHTML=getPagingHtml(startIndex,limit,imagesResult.TotalRecordCount);for(var html="",i=0,length=imagesResult.Images.length;ilimit;html+='
',html+='';var startAtDisplay=totalRecordCount?startIndex+1:0;return html+=startAtDisplay+"-"+recordsEnd+" of "+totalRecordCount,html+="",showControls&&(html+='
',html+='',html+='',html+="
"),html+="
"}function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function downloadRemoteImage(page,url,type,provider){var options=getBaseRemoteOptions();options.Type=type,options.ImageUrl=url,options.ProviderName=provider,Dashboard.showLoadingMsg(),ApiClient.downloadRemoteImage(options).then(function(){hasChanges=!0;var dlg=parentWithClass(page,"dialog");dialogHelper.close(dlg)})}function getDisplayUrl(url){return ApiClient.getUrl("Images/Remote",{imageUrl:url})}function getRemoteImageHtml(image,imageType){var html="";html+='
';var cssClass="remoteImage lazy";cssClass+="Backdrop"==imageType||"Art"==imageType||"Thumb"==imageType||"Logo"==imageType?" remoteBackdropImage":"Banner"==imageType?" remoteBannerImage":"Disc"==imageType?" remoteDiscImage":"Episode"==currentItemType?" remoteBackdropImage":"MusicAlbum"==currentItemType||"MusicArtist"==currentItemType?" remoteDiscImage":" remotePosterImage";var displayUrl=getDisplayUrl(image.ThumbnailUrl||image.Url);return html+='',html+="",html+='
',html+='
',html+=image.ProviderName,html+="
",(image.Width||image.Height||image.Language)&&(html+='
',image.Width&&image.Height?(html+=image.Width+" x "+image.Height,image.Language&&(html+=" • "+image.Language)):image.Language&&(html+=image.Language),html+="
"),null!=image.CommunityRating&&(html+='
',"Likes"==image.RatingType?html+=image.CommunityRating+(1==image.CommunityRating?" like":" likes"):image.CommunityRating?(html+=image.CommunityRating.toFixed(1),image.VoteCount&&(html+=" • "+image.VoteCount+(1==image.VoteCount?" vote":" votes"))):html+="Unrated",html+="
"),html+='',html+="
",html+="
"}function initEditor(page){page.querySelector("#selectBrowsableImageType").addEventListener("change",function(){browsableImageType=this.value,browsableImageStartIndex=0,selectedProvider=null,reloadBrowsableImages(page)}),page.querySelector("#selectImageProvider").addEventListener("change",function(){browsableImageStartIndex=0,selectedProvider=this.value,reloadBrowsableImages(page)}),page.querySelector("#chkAllLanguages").addEventListener("change",function(){browsableImageStartIndex=0,reloadBrowsableImages(page)}),page.addEventListener("click",function(e){var btnDownloadRemoteImage=parentWithClass(e.target,"btnDownloadRemoteImage");btnDownloadRemoteImage&&downloadRemoteImage(page,btnDownloadRemoteImage.getAttribute("data-imageurl"),btnDownloadRemoteImage.getAttribute("data-imagetype"),btnDownloadRemoteImage.getAttribute("data-imageprovider"))})}function showEditor(itemId,itemType){Dashboard.showLoadingMsg();var xhr=new XMLHttpRequest;xhr.open("GET","components/imagedownloader/imagedownloader.template.html",!0),xhr.onload=function(e){var template=this.response;currentItemId=itemId,currentItemType=itemType;var dlg=dialogHelper.createDialog({size:"fullscreen-border",lockScroll:!0,removeOnClose:!0}),theme="b";dlg.classList.add("ui-body-"+theme),dlg.classList.add("background-theme-"+theme);var html="";html+='

',html+='',html+='
'+Globalize.translate("HeaderSearch")+"
",html+="

",html+='
',html+=Globalize.translateDocument(template),html+="
",dlg.innerHTML=html,dlg.addEventListener("close",onDialogClosed),dialogHelper.open(dlg);var editorContent=dlg.querySelector(".editorContent");initEditor(editorContent),dlg.querySelector(".btnCloseDialog").addEventListener("click",function(){dialogHelper.close(dlg)}),reloadBrowsableImages(editorContent)},xhr.send()}function onDialogClosed(){Dashboard.hideLoadingMsg(),hasChanges?currentResolve():currentReject()}var currentItemId,currentItemType,currentResolve,currentReject,selectedProvider,hasChanges=!1,browsableImagePageSize=browserInfo.slow?6:30,browsableImageStartIndex=0,browsableImageType="Primary";return{show:function(itemId,itemType,imageType){return new Promise(function(resolve,reject){currentResolve=resolve,currentReject=reject,hasChanges=!1,browsableImageStartIndex=0,browsableImageType=imageType||"Primary",selectedProvider=null,showEditor(itemId,itemType)})}}}); \ No newline at end of file diff --git a/dashboard-ui/components/imageuploader/imageuploader.js b/dashboard-ui/components/imageuploader/imageuploader.js index c28594d748..572f3c222c 100644 --- a/dashboard-ui/components/imageuploader/imageuploader.js +++ b/dashboard-ui/components/imageuploader/imageuploader.js @@ -1,200 +1 @@ -define(['dialogHelper', 'jQuery', 'emby-button', 'emby-select'], function (dialogHelper, $) { - 'use strict'; - - var currentItemId; - var currentFile; - var currentDeferred; - var hasChanges = false; - - function onFileReaderError(evt) { - - Dashboard.hideLoadingMsg(); - - switch (evt.target.error.code) { - case evt.target.error.NOT_FOUND_ERR: - require(['toast'], function (toast) { - toast(Globalize.translate('MessageFileNotFound')); - }); - break; - case evt.target.error.ABORT_ERR: - break; // noop - default: - require(['toast'], function (toast) { - toast(Globalize.translate('MessageFileReadError')); - }); - break; - }; - } - - function setFiles(page, files) { - - var file = files[0]; - - if (!file || !file.type.match('image.*')) { - $('#imageOutput', page).html(''); - $('#fldUpload', page).hide(); - currentFile = null; - return; - } - - currentFile = file; - - var reader = new FileReader(); - - reader.onerror = onFileReaderError; - reader.onloadstart = function () { - $('#fldUpload', page).hide(); - }; - reader.onabort = function () { - Dashboard.hideLoadingMsg(); - console.log('File read cancelled'); - }; - - // Closure to capture the file information. - reader.onload = (function (theFile) { - return function (e) { - - // Render thumbnail. - var html = [''].join(''); - - $('#imageOutput', page).html(html); - $('#fldUpload', page).show(); - }; - })(file); - - // Read in the image file as a data URL. - reader.readAsDataURL(file); - } - - function processImageChangeResult(page) { - - hasChanges = true; - history.back(); - } - - function onSubmit() { - - var file = currentFile; - - if (!file) { - return false; - } - - if (file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/jpeg") { - return false; - } - - Dashboard.showLoadingMsg(); - - var page = $(this).parents('.dialog'); - - var imageType = $('#selectImageType', page).val(); - - ApiClient.uploadItemImage(currentItemId, imageType, file).then(function () { - - $('#uploadImage', page).val('').trigger('change'); - Dashboard.hideLoadingMsg(); - processImageChangeResult(page); - }); - - return false; - } - - function initEditor(page) { - - $('form', page).off('submit', onSubmit).on('submit', onSubmit); - - $('#uploadImage', page).on("change", function () { - setFiles(page, this.files); - }); - - $("#imageDropZone", page).on('dragover', function (e) { - - e.preventDefault(); - - e.originalEvent.dataTransfer.dropEffect = 'Copy'; - - return false; - - }).on('drop', function (e) { - - e.preventDefault(); - - setFiles(page, e.originalEvent.dataTransfer.files); - - return false; - }); - } - - function showEditor(itemId, options) { - - options = options || {}; - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/imageuploader/imageuploader.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - currentItemId = itemId; - - var dlg = dialogHelper.createDialog({ - size: 'fullscreen-border' - }); - - var theme = options.theme || 'b'; - - dlg.classList.add('ui-body-' + theme); - dlg.classList.add('background-theme-' + theme); - - var html = ''; - html += '

'; - html += ''; - html += '
' + Globalize.translate('HeaderUploadImage') + '
'; - html += '

'; - - html += '
'; - html += Globalize.translateDocument(template); - html += '
'; - - dlg.innerHTML = html; - - // Has to be assigned a z-index after the call to .open() - $(dlg).on('close', onDialogClosed); - - dialogHelper.open(dlg); - - var editorContent = dlg.querySelector('.editorContent'); - initEditor(editorContent); - - $('#selectImageType', dlg).val(options.imageType || 'Primary'); - - $('.btnCloseDialog', dlg).on('click', function () { - - dialogHelper.close(dlg); - }); - } - - xhr.send(); - } - - function onDialogClosed() { - - $(this).remove(); - Dashboard.hideLoadingMsg(); - currentDeferred.resolveWith(null, [hasChanges]); - } - - return { - show: function (itemId, options) { - - var deferred = jQuery.Deferred(); - - currentDeferred = deferred; - hasChanges = false; - - showEditor(itemId, options); - return deferred.promise(); - } - }; -}); \ No newline at end of file +define(["dialogHelper","jQuery","emby-button","emby-select"],function(dialogHelper,$){"use strict";function onFileReaderError(evt){switch(Dashboard.hideLoadingMsg(),evt.target.error.code){case evt.target.error.NOT_FOUND_ERR:require(["toast"],function(toast){toast(Globalize.translate("MessageFileNotFound"))});break;case evt.target.error.ABORT_ERR:break;default:require(["toast"],function(toast){toast(Globalize.translate("MessageFileReadError"))})}}function setFiles(page,files){var file=files[0];if(!file||!file.type.match("image.*"))return $("#imageOutput",page).html(""),$("#fldUpload",page).hide(),void(currentFile=null);currentFile=file;var reader=new FileReader;reader.onerror=onFileReaderError,reader.onloadstart=function(){$("#fldUpload",page).hide()},reader.onabort=function(){Dashboard.hideLoadingMsg(),console.log("File read cancelled")},reader.onload=function(theFile){return function(e){var html=[''].join("");$("#imageOutput",page).html(html),$("#fldUpload",page).show()}}(file),reader.readAsDataURL(file)}function processImageChangeResult(page){hasChanges=!0,history.back()}function onSubmit(){var file=currentFile;if(!file)return!1;if("image/png"!=file.type&&"image/jpeg"!=file.type&&"image/jpeg"!=file.type)return!1;Dashboard.showLoadingMsg();var page=$(this).parents(".dialog"),imageType=$("#selectImageType",page).val();return ApiClient.uploadItemImage(currentItemId,imageType,file).then(function(){$("#uploadImage",page).val("").trigger("change"),Dashboard.hideLoadingMsg(),processImageChangeResult(page)}),!1}function initEditor(page){$("form",page).off("submit",onSubmit).on("submit",onSubmit),$("#uploadImage",page).on("change",function(){setFiles(page,this.files)}),$("#imageDropZone",page).on("dragover",function(e){return e.preventDefault(),e.originalEvent.dataTransfer.dropEffect="Copy",!1}).on("drop",function(e){return e.preventDefault(),setFiles(page,e.originalEvent.dataTransfer.files),!1})}function showEditor(itemId,options){options=options||{};var xhr=new XMLHttpRequest;xhr.open("GET","components/imageuploader/imageuploader.template.html",!0),xhr.onload=function(e){var template=this.response;currentItemId=itemId;var dlg=dialogHelper.createDialog({size:"fullscreen-border"}),theme=options.theme||"b";dlg.classList.add("ui-body-"+theme),dlg.classList.add("background-theme-"+theme);var html="";html+='

',html+='',html+='
'+Globalize.translate("HeaderUploadImage")+"
",html+="

",html+='
',html+=Globalize.translateDocument(template),html+="
",dlg.innerHTML=html,$(dlg).on("close",onDialogClosed),dialogHelper.open(dlg);var editorContent=dlg.querySelector(".editorContent");initEditor(editorContent),$("#selectImageType",dlg).val(options.imageType||"Primary"),$(".btnCloseDialog",dlg).on("click",function(){dialogHelper.close(dlg)})},xhr.send()}function onDialogClosed(){$(this).remove(),Dashboard.hideLoadingMsg(),currentDeferred.resolveWith(null,[hasChanges])}var currentItemId,currentFile,currentDeferred,hasChanges=!1;return{show:function(itemId,options){var deferred=jQuery.Deferred();return currentDeferred=deferred,hasChanges=!1,showEditor(itemId,options),deferred.promise()}}}); \ No newline at end of file diff --git a/dashboard-ui/components/libraryoptionseditor/libraryoptionseditor.js b/dashboard-ui/components/libraryoptionseditor/libraryoptionseditor.js index 5a644f3698..07dab31d73 100644 --- a/dashboard-ui/components/libraryoptionseditor/libraryoptionseditor.js +++ b/dashboard-ui/components/libraryoptionseditor/libraryoptionseditor.js @@ -1,154 +1 @@ -define(['globalize', 'emby-checkbox', 'emby-select'], function (globalize) { - 'use strict'; - - function populateLanguages(select) { - - return ApiClient.getCultures().then(function (languages) { - - var html = ""; - - html += ""; - - for (var i = 0, length = languages.length; i < length; i++) { - - var culture = languages[i]; - - html += ""; - } - - select.innerHTML = html; - }); - } - - function populateCountries(select) { - - return ApiClient.getCountries().then(function (allCountries) { - - var html = ""; - - html += ""; - - for (var i = 0, length = allCountries.length; i < length; i++) { - - var culture = allCountries[i]; - - html += ""; - } - - select.innerHTML = html; - }); - } - - function embed(parent, contentType, libraryOptions) { - - return new Promise(function (resolve, reject) { - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/libraryoptionseditor/libraryoptionseditor.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - parent.innerHTML = globalize.translateDocument(template); - - var promises = [ - populateLanguages(parent.querySelector('#selectLanguage')), - populateCountries(parent.querySelector('#selectCountry')) - ]; - - Promise.all(promises).then(function () { - - setContentType(parent, contentType); - - if (libraryOptions) { - setLibraryOptions(parent, libraryOptions); - } - - resolve(); - }); - } - - xhr.send(); - }); - } - - function setContentType(parent, contentType) { - - if (contentType == 'homevideos' || contentType == 'photos') { - parent.querySelector('.chkEnablePhotosContainer').classList.remove('hide'); - parent.querySelector('.chkDownloadImagesInAdvanceContainer').classList.add('hide'); - parent.querySelector('.chkEnableInternetProvidersContainer').classList.add('hide'); - parent.querySelector('.fldMetadataLanguage').classList.add('hide'); - parent.querySelector('.fldMetadataCountry').classList.add('hide'); - } else { - parent.querySelector('.chkEnablePhotosContainer').classList.add('hide'); - parent.querySelector('.chkDownloadImagesInAdvanceContainer').classList.remove('hide'); - parent.querySelector('.chkEnableInternetProvidersContainer').classList.remove('hide'); - parent.querySelector('.fldMetadataLanguage').classList.remove('hide'); - parent.querySelector('.fldMetadataCountry').classList.remove('hide'); - } - - if (contentType == 'photos') { - parent.querySelector('.chkSaveLocalContainer').classList.add('hide'); - } else { - parent.querySelector('.chkSaveLocalContainer').classList.remove('hide'); - } - - if (contentType == 'tvshows' || contentType == 'movies' || contentType == 'homevideos' || contentType == 'musicvideos' || contentType == 'mixed' || !contentType) { - parent.querySelector('.chapterSettingsSection').classList.remove('hide'); - } else { - parent.querySelector('.chapterSettingsSection').classList.add('hide'); - } - - if (contentType == 'tvshows') { - parent.querySelector('.chkImportMissingEpisodesContainer').classList.remove('hide'); - parent.querySelector('.chkAutomaticallyGroupSeriesContainer').classList.remove('hide'); - } else { - parent.querySelector('.chkImportMissingEpisodesContainer').classList.add('hide'); - parent.querySelector('.chkAutomaticallyGroupSeriesContainer').classList.add('hide'); - } - } - - function getLibraryOptions(parent) { - - var options = { - EnableArchiveMediaFiles: false, - EnablePhotos: parent.querySelector('.chkEnablePhotos').checked, - EnableRealtimeMonitor: parent.querySelector('.chkEnableRealtimeMonitor').checked, - ExtractChapterImagesDuringLibraryScan: parent.querySelector('.chkExtractChaptersDuringLibraryScan').checked, - EnableChapterImageExtraction: parent.querySelector('.chkExtractChapterImages').checked, - DownloadImagesInAdvance: parent.querySelector('#chkDownloadImagesInAdvance').checked, - EnableInternetProviders: parent.querySelector('#chkEnableInternetProviders').checked, - ImportMissingEpisodes: parent.querySelector('#chkImportMissingEpisodes').checked, - SaveLocalMetadata: parent.querySelector('#chkSaveLocal').checked, - EnableAutomaticSeriesGrouping: parent.querySelector('.chkAutomaticallyGroupSeries').checked, - PreferredMetadataLanguage: parent.querySelector('#selectLanguage').value, - MetadataCountryCode: parent.querySelector('#selectCountry').value - }; - - return options; - } - - function setLibraryOptions(parent, options) { - - parent.querySelector('#selectLanguage').value = options.PreferredMetadataLanguage || ''; - parent.querySelector('#selectCountry').value = options.MetadataCountryCode || ''; - - parent.querySelector('.chkEnablePhotos').checked = options.EnablePhotos; - parent.querySelector('.chkEnableRealtimeMonitor').checked = options.EnableRealtimeMonitor; - parent.querySelector('.chkExtractChaptersDuringLibraryScan').checked = options.ExtractChapterImagesDuringLibraryScan; - parent.querySelector('.chkExtractChapterImages').checked = options.EnableChapterImageExtraction; - parent.querySelector('#chkDownloadImagesInAdvance').checked = options.DownloadImagesInAdvance; - parent.querySelector('#chkEnableInternetProviders').checked = options.EnableInternetProviders; - parent.querySelector('#chkSaveLocal').checked = options.SaveLocalMetadata; - parent.querySelector('#chkImportMissingEpisodes').checked = options.ImportMissingEpisodes; - parent.querySelector('.chkAutomaticallyGroupSeries').checked = options.EnableAutomaticSeriesGrouping; - } - - return { - embed: embed, - setContentType: setContentType, - getLibraryOptions: getLibraryOptions, - setLibraryOptions: setLibraryOptions - }; -}); \ No newline at end of file +define(["globalize","emby-checkbox","emby-select"],function(globalize){"use strict";function populateLanguages(select){return ApiClient.getCultures().then(function(languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateCountries(select){return ApiClient.getCountries().then(function(allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html})}function embed(parent,contentType,libraryOptions){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest;xhr.open("GET","components/libraryoptionseditor/libraryoptionseditor.template.html",!0),xhr.onload=function(e){var template=this.response;parent.innerHTML=globalize.translateDocument(template);var promises=[populateLanguages(parent.querySelector("#selectLanguage")),populateCountries(parent.querySelector("#selectCountry"))];Promise.all(promises).then(function(){setContentType(parent,contentType),libraryOptions&&setLibraryOptions(parent,libraryOptions),resolve()})},xhr.send()})}function setContentType(parent,contentType){"homevideos"==contentType||"photos"==contentType?(parent.querySelector(".chkEnablePhotosContainer").classList.remove("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.add("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.add("hide"),parent.querySelector(".fldMetadataLanguage").classList.add("hide"),parent.querySelector(".fldMetadataCountry").classList.add("hide")):(parent.querySelector(".chkEnablePhotosContainer").classList.add("hide"),parent.querySelector(".chkDownloadImagesInAdvanceContainer").classList.remove("hide"),parent.querySelector(".chkEnableInternetProvidersContainer").classList.remove("hide"),parent.querySelector(".fldMetadataLanguage").classList.remove("hide"),parent.querySelector(".fldMetadataCountry").classList.remove("hide")),"photos"==contentType?parent.querySelector(".chkSaveLocalContainer").classList.add("hide"):parent.querySelector(".chkSaveLocalContainer").classList.remove("hide"),"tvshows"!=contentType&&"movies"!=contentType&&"homevideos"!=contentType&&"musicvideos"!=contentType&&"mixed"!=contentType&&contentType?parent.querySelector(".chapterSettingsSection").classList.add("hide"):parent.querySelector(".chapterSettingsSection").classList.remove("hide"),"tvshows"==contentType?(parent.querySelector(".chkImportMissingEpisodesContainer").classList.remove("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.remove("hide")):(parent.querySelector(".chkImportMissingEpisodesContainer").classList.add("hide"),parent.querySelector(".chkAutomaticallyGroupSeriesContainer").classList.add("hide"))}function getLibraryOptions(parent){var options={EnableArchiveMediaFiles:!1,EnablePhotos:parent.querySelector(".chkEnablePhotos").checked,EnableRealtimeMonitor:parent.querySelector(".chkEnableRealtimeMonitor").checked,ExtractChapterImagesDuringLibraryScan:parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked,EnableChapterImageExtraction:parent.querySelector(".chkExtractChapterImages").checked,DownloadImagesInAdvance:parent.querySelector("#chkDownloadImagesInAdvance").checked,EnableInternetProviders:parent.querySelector("#chkEnableInternetProviders").checked,ImportMissingEpisodes:parent.querySelector("#chkImportMissingEpisodes").checked,SaveLocalMetadata:parent.querySelector("#chkSaveLocal").checked,EnableAutomaticSeriesGrouping:parent.querySelector(".chkAutomaticallyGroupSeries").checked,PreferredMetadataLanguage:parent.querySelector("#selectLanguage").value,MetadataCountryCode:parent.querySelector("#selectCountry").value};return options}function setLibraryOptions(parent,options){parent.querySelector("#selectLanguage").value=options.PreferredMetadataLanguage||"",parent.querySelector("#selectCountry").value=options.MetadataCountryCode||"",parent.querySelector(".chkEnablePhotos").checked=options.EnablePhotos,parent.querySelector(".chkEnableRealtimeMonitor").checked=options.EnableRealtimeMonitor,parent.querySelector(".chkExtractChaptersDuringLibraryScan").checked=options.ExtractChapterImagesDuringLibraryScan,parent.querySelector(".chkExtractChapterImages").checked=options.EnableChapterImageExtraction,parent.querySelector("#chkDownloadImagesInAdvance").checked=options.DownloadImagesInAdvance,parent.querySelector("#chkEnableInternetProviders").checked=options.EnableInternetProviders,parent.querySelector("#chkSaveLocal").checked=options.SaveLocalMetadata,parent.querySelector("#chkImportMissingEpisodes").checked=options.ImportMissingEpisodes,parent.querySelector(".chkAutomaticallyGroupSeries").checked=options.EnableAutomaticSeriesGrouping}return{embed:embed,setContentType:setContentType,getLibraryOptions:getLibraryOptions,setLibraryOptions:setLibraryOptions}}); \ No newline at end of file diff --git a/dashboard-ui/components/medialibrarycreator/medialibrarycreator.js b/dashboard-ui/components/medialibrarycreator/medialibrarycreator.js index 58998154c3..e05aef05ba 100644 --- a/dashboard-ui/components/medialibrarycreator/medialibrarycreator.js +++ b/dashboard-ui/components/medialibrarycreator/medialibrarycreator.js @@ -1,273 +1 @@ -define(['dialogHelper', 'jQuery', 'components/libraryoptionseditor/libraryoptionseditor', 'emby-input', 'emby-select', 'paper-icon-button-light', 'listViewStyle', 'formDialogStyle'], function (dialogHelper, $, libraryoptionseditor) { - 'use strict'; - - var currentDeferred; - var hasChanges; - var currentOptions; - var pathInfos = []; - - function onSubmit() { - - if (pathInfos.length == 0) { - require(['alert'], function (alert) { - alert({ - text: Globalize.translate('PleaseAddAtLeastOneFolder'), - type: 'error' - }); - }); - return false; - } - - var form = this; - var dlg = $(form).parents('.dialog')[0]; - - var name = $('#txtValue', form).val(); - var type = $('#selectCollectionType', form).val(); - - if (type == 'mixed') { - type = null; - } - - var libraryOptions = libraryoptionseditor.getLibraryOptions(dlg.querySelector('.libraryOptions')); - - libraryOptions.PathInfos = pathInfos; - - ApiClient.addVirtualFolder(name, type, currentOptions.refresh, libraryOptions).then(function () { - - hasChanges = true; - dialogHelper.close(dlg); - - }, function () { - - require(['toast'], function (toast) { - toast(Globalize.translate('ErrorAddingMediaPathToVirtualFolder')); - }); - }); - - return false; - } - - function getCollectionTypeOptionsHtml(collectionTypeOptions) { - - return collectionTypeOptions.filter(function (i) { - - return i.isSelectable !== false; - - }).map(function (i) { - - return ''; - - }).join(""); - } - - function initEditor(page, collectionTypeOptions) { - - $('#selectCollectionType', page).html(getCollectionTypeOptionsHtml(collectionTypeOptions)).val('').on('change', function () { - - var value = this.value; - - var dlg = $(this).parents('.dialog')[0]; - - libraryoptionseditor.setContentType(dlg.querySelector('.libraryOptions'), (value == 'mixed' ? '' : value)); - - if (value) { - dlg.querySelector('.libraryOptions').classList.remove('hide'); - } else { - dlg.querySelector('.libraryOptions').classList.add('hide'); - } - - if (value == 'mixed') { - return; - } - - var index = this.selectedIndex; - if (index != -1) { - - var name = this.options[index].innerHTML - .replace('*', '') - .replace('&', '&'); - - $('#txtValue', dlg).val(name); - - var folderOption = collectionTypeOptions.filter(function (i) { - - return i.value == value; - - })[0]; - - $('.collectionTypeFieldDescription', dlg).html(folderOption.message || ''); - } - - }); - - $('.btnAddFolder', page).on('click', onAddButtonClick); - $('form', page).off('submit', onSubmit).on('submit', onSubmit); - } - - function onAddButtonClick() { - - var page = $(this).parents('.dlg-librarycreator')[0]; - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - enableNetworkSharePath: true, - callback: function (path, networkSharePath) { - - if (path) { - addMediaLocation(page, path, networkSharePath); - } - picker.close(); - } - - }); - }); - } - - function getFolderHtml(pathInfo, index) { - - var html = ''; - - html += '
'; - - html += 'folder'; - - var cssClass = pathInfo.NetworkPath ? 'listItemBody two-line' : 'listItemBody'; - - html += '
'; - html += '
' + pathInfo.Path + '
'; - - if (pathInfo.NetworkPath) { - html += '
' + pathInfo.NetworkPath + '
'; - } - html += '
'; - - html += ''; - - html += '
'; - - return html; - } - - function renderPaths(page) { - var foldersHtml = pathInfos.map(getFolderHtml).join(''); - - var folderList = page.querySelector('.folderList'); - folderList.innerHTML = foldersHtml; - - if (foldersHtml) { - folderList.classList.remove('hide'); - } else { - folderList.classList.add('hide'); - } - - $(page.querySelectorAll('.btnRemovePath')).on('click', onRemoveClick); - } - - function addMediaLocation(page, path, networkSharePath) { - - if (pathInfos.filter(function (p) { - - return p.Path.toLowerCase() == path.toLowerCase(); - - }).length == 0) { - - var pathInfo = { - Path: path - }; - if (networkSharePath) { - pathInfo.NetworkPath = networkSharePath; - } - pathInfos.push(pathInfo); - renderPaths(page); - } - } - - function onRemoveClick() { - - var button = this; - var index = parseInt(button.getAttribute('data-index')); - - var location = pathInfos[index]; - pathInfos = pathInfos.filter(function (p) { - - return p.Path.toLowerCase() != location.toLowerCase(); - }); - var page = $(this).parents('.dlg-librarycreator')[0]; - renderPaths(page); - } - - function onDialogClosed() { - - Dashboard.hideLoadingMsg(); - currentDeferred.resolveWith(null, [hasChanges]); - } - - function initLibraryOptions(dlg) { - libraryoptionseditor.embed(dlg.querySelector('.libraryOptions')).then(function () { - $('#selectCollectionType', dlg).trigger('change'); - }); - } - - function editor() { - - var self = this; - - self.show = function (options) { - - var deferred = jQuery.Deferred(); - - currentOptions = options; - currentDeferred = deferred; - hasChanges = false; - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/medialibrarycreator/medialibrarycreator.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - size: 'medium', - - // In (at least) chrome this is causing the text field to not be editable - modal: false, - - removeOnClose: true, - scrollY: false - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - dlg.classList.add('dlg-librarycreator'); - dlg.classList.add('formDialog'); - - dlg.innerHTML = Globalize.translateDocument(template); - - initEditor(dlg, options.collectionTypeOptions); - - dlg.addEventListener('close', onDialogClosed); - - dialogHelper.open(dlg); - - dlg.querySelector('.btnCancel').addEventListener('click', function () { - - dialogHelper.close(dlg); - }); - - pathInfos = []; - renderPaths(dlg); - initLibraryOptions(dlg); - } - - xhr.send(); - - return deferred.promise(); - }; - } - - return editor; -}); \ No newline at end of file +define(["dialogHelper","jQuery","components/libraryoptionseditor/libraryoptionseditor","emby-input","emby-select","paper-icon-button-light","listViewStyle","formDialogStyle"],function(dialogHelper,$,libraryoptionseditor){"use strict";function onSubmit(){if(0==pathInfos.length)return require(["alert"],function(alert){alert({text:Globalize.translate("PleaseAddAtLeastOneFolder"),type:"error"})}),!1;var form=this,dlg=$(form).parents(".dialog")[0],name=$("#txtValue",form).val(),type=$("#selectCollectionType",form).val();"mixed"==type&&(type=null);var libraryOptions=libraryoptionseditor.getLibraryOptions(dlg.querySelector(".libraryOptions"));return libraryOptions.PathInfos=pathInfos,ApiClient.addVirtualFolder(name,type,currentOptions.refresh,libraryOptions).then(function(){hasChanges=!0,dialogHelper.close(dlg)},function(){require(["toast"],function(toast){toast(Globalize.translate("ErrorAddingMediaPathToVirtualFolder"))})}),!1}function getCollectionTypeOptionsHtml(collectionTypeOptions){return collectionTypeOptions.filter(function(i){return i.isSelectable!==!1}).map(function(i){return'"}).join("")}function initEditor(page,collectionTypeOptions){$("#selectCollectionType",page).html(getCollectionTypeOptionsHtml(collectionTypeOptions)).val("").on("change",function(){var value=this.value,dlg=$(this).parents(".dialog")[0];if(libraryoptionseditor.setContentType(dlg.querySelector(".libraryOptions"),"mixed"==value?"":value),value?dlg.querySelector(".libraryOptions").classList.remove("hide"):dlg.querySelector(".libraryOptions").classList.add("hide"),"mixed"!=value){var index=this.selectedIndex;if(index!=-1){var name=this.options[index].innerHTML.replace("*","").replace("&","&");$("#txtValue",dlg).val(name);var folderOption=collectionTypeOptions.filter(function(i){return i.value==value})[0];$(".collectionTypeFieldDescription",dlg).html(folderOption.message||"")}}}),$(".btnAddFolder",page).on("click",onAddButtonClick),$("form",page).off("submit",onSubmit).on("submit",onSubmit)}function onAddButtonClick(){var page=$(this).parents(".dlg-librarycreator")[0];require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({enableNetworkSharePath:!0,callback:function(path,networkSharePath){path&&addMediaLocation(page,path,networkSharePath),picker.close()}})})}function getFolderHtml(pathInfo,index){var html="";html+='
',html+='folder';var cssClass=pathInfo.NetworkPath?"listItemBody two-line":"listItemBody";return html+='
',html+='
'+pathInfo.Path+"
",pathInfo.NetworkPath&&(html+='
'+pathInfo.NetworkPath+"
"),html+="
",html+='',html+="
"}function renderPaths(page){var foldersHtml=pathInfos.map(getFolderHtml).join(""),folderList=page.querySelector(".folderList");folderList.innerHTML=foldersHtml,foldersHtml?folderList.classList.remove("hide"):folderList.classList.add("hide"),$(page.querySelectorAll(".btnRemovePath")).on("click",onRemoveClick)}function addMediaLocation(page,path,networkSharePath){if(0==pathInfos.filter(function(p){return p.Path.toLowerCase()==path.toLowerCase()}).length){var pathInfo={Path:path};networkSharePath&&(pathInfo.NetworkPath=networkSharePath),pathInfos.push(pathInfo),renderPaths(page)}}function onRemoveClick(){var button=this,index=parseInt(button.getAttribute("data-index")),location=pathInfos[index];pathInfos=pathInfos.filter(function(p){return p.Path.toLowerCase()!=location.toLowerCase()});var page=$(this).parents(".dlg-librarycreator")[0];renderPaths(page)}function onDialogClosed(){Dashboard.hideLoadingMsg(),currentDeferred.resolveWith(null,[hasChanges])}function initLibraryOptions(dlg){libraryoptionseditor.embed(dlg.querySelector(".libraryOptions")).then(function(){$("#selectCollectionType",dlg).trigger("change")})}function editor(){var self=this;self.show=function(options){var deferred=jQuery.Deferred();currentOptions=options,currentDeferred=deferred,hasChanges=!1;var xhr=new XMLHttpRequest;return xhr.open("GET","components/medialibrarycreator/medialibrarycreator.template.html",!0),xhr.onload=function(e){var template=this.response,dlg=dialogHelper.createDialog({size:"medium",modal:!1,removeOnClose:!0,scrollY:!1});dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a"),dlg.classList.add("dlg-librarycreator"),dlg.classList.add("formDialog"),dlg.innerHTML=Globalize.translateDocument(template),initEditor(dlg,options.collectionTypeOptions),dlg.addEventListener("close",onDialogClosed),dialogHelper.open(dlg),dlg.querySelector(".btnCancel").addEventListener("click",function(){dialogHelper.close(dlg)}),pathInfos=[],renderPaths(dlg),initLibraryOptions(dlg)},xhr.send(),deferred.promise()}}var currentDeferred,hasChanges,currentOptions,pathInfos=[];return editor}); \ No newline at end of file diff --git a/dashboard-ui/components/medialibraryeditor/medialibraryeditor.js b/dashboard-ui/components/medialibraryeditor/medialibraryeditor.js index d2b91cc386..8963ecdd8e 100644 --- a/dashboard-ui/components/medialibraryeditor/medialibraryeditor.js +++ b/dashboard-ui/components/medialibraryeditor/medialibraryeditor.js @@ -1,296 +1 @@ -define(['dialogHelper', 'dom', 'components/libraryoptionseditor/libraryoptionseditor', 'emby-button', 'listViewStyle', 'paper-icon-button-light', 'formDialogStyle'], function (dialogHelper, dom, libraryoptionseditor) { - 'use strict'; - - var currentDeferred; - var hasChanges; - var currentOptions; - - function addMediaLocation(page, path, networkSharePath) { - - var virtualFolder = currentOptions.library; - - var refreshAfterChange = currentOptions.refresh; - - ApiClient.addMediaPath(virtualFolder.Name, path, networkSharePath, refreshAfterChange).then(function () { - - hasChanges = true; - refreshLibraryFromServer(page); - - }, function () { - - require(['toast'], function (toast) { - toast(Globalize.translate('ErrorAddingMediaPathToVirtualFolder')); - }); - }); - } - - function updateMediaLocation(page, path, networkSharePath) { - var virtualFolder = currentOptions.library; - ApiClient.updateMediaPath(virtualFolder.Name, { - - Path: path, - NetworkPath: networkSharePath - - }).then(function () { - - hasChanges = true; - refreshLibraryFromServer(page); - - }, function () { - - require(['toast'], function (toast) { - toast(Globalize.translate('ErrorAddingMediaPathToVirtualFolder')); - }); - }); - } - - function onRemoveClick(btnRemovePath) { - - var button = btnRemovePath; - var index = parseInt(button.getAttribute('data-index')); - - var virtualFolder = currentOptions.library; - - var location = virtualFolder.Locations[index]; - - require(['confirm'], function (confirm) { - - confirm({ - - title: Globalize.translate('HeaderRemoveMediaLocation'), - text: Globalize.translate('MessageConfirmRemoveMediaLocation'), - confirmText: Globalize.translate('ButtonDelete'), - primary: 'cancel' - - }).then(function () { - - var refreshAfterChange = currentOptions.refresh; - - ApiClient.removeMediaPath(virtualFolder.Name, location, refreshAfterChange).then(function () { - - hasChanges = true; - refreshLibraryFromServer(dom.parentWithClass(button, 'dlg-libraryeditor')); - - }, function () { - - require(['toast'], function (toast) { - toast(Globalize.translate('DefaultErrorMessage')); - }); - }); - }); - }); - } - - function onListItemClick(e) { - - var btnRemovePath = dom.parentWithClass(e.target, 'btnRemovePath'); - if (btnRemovePath) { - onRemoveClick(btnRemovePath); - return; - } - - var listItem = dom.parentWithClass(e.target, 'listItem'); - if (!listItem) { - return; - } - - var index = parseInt(listItem.getAttribute('data-index')); - var page = dom.parentWithClass(listItem, 'dlg-libraryeditor'); - showDirectoryBrowser(page, index); - } - - function getFolderHtml(pathInfo, index) { - - var html = ''; - - html += '
'; - - html += 'folder'; - - var cssClass = pathInfo.NetworkPath ? 'listItemBody two-line' : 'listItemBody'; - - html += '
'; - - html += '

'; - html += pathInfo.Path; - html += '

'; - if (pathInfo.NetworkPath) { - html += '
' + pathInfo.NetworkPath + '
'; - } - html += '
'; - - html += ''; - - html += '
'; - - return html; - } - - function refreshLibraryFromServer(page) { - - ApiClient.getVirtualFolders().then(function (result) { - - var library = result.filter(function (f) { - - return f.Name == currentOptions.library.Name; - - })[0]; - - if (library) { - currentOptions.library = library; - renderLibrary(page, currentOptions); - } - }); - } - - function renderLibrary(page, options) { - - var pathInfos = (options.library.LibraryOptions || {}).PathInfos || []; - - if (!pathInfos.length) { - pathInfos = options.library.Locations.map(function (p) { - return { - Path: p - }; - }); - } - - var foldersHtml = pathInfos.map(getFolderHtml).join(''); - - page.querySelector('.folderList').innerHTML = foldersHtml; - - var listItems = page.querySelectorAll('.listItem'); - for (var i = 0, length = listItems.length; i < length; i++) { - listItems[i].addEventListener('click', onListItemClick); - } - } - - function onAddButtonClick() { - - var page = dom.parentWithClass(this, 'dlg-libraryeditor'); - - showDirectoryBrowser(page); - } - - function showDirectoryBrowser(context, listIndex) { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - var pathInfos = (currentOptions.library.LibraryOptions || {}).PathInfos || []; - var pathInfo = listIndex == null ? {} : (pathInfos[listIndex] || {}); - // legacy - var location = listIndex == null ? null : (currentOptions.library.Locations[listIndex]); - var originalPath = pathInfo.Path || location; - - picker.show({ - - enableNetworkSharePath: true, - pathReadOnly: listIndex != null, - path: originalPath, - networkSharePath: pathInfo.NetworkPath, - callback: function (path, networkSharePath) { - - if (path) { - if (originalPath) { - updateMediaLocation(context, originalPath, networkSharePath); - } else { - addMediaLocation(context, path, networkSharePath); - } - } - picker.close(); - } - - }); - }); - } - - function initEditor(dlg, options) { - renderLibrary(dlg, options); - - dlg.querySelector('.btnAddFolder').addEventListener('click', onAddButtonClick); - - libraryoptionseditor.embed(dlg.querySelector('.libraryOptions'), options.library.CollectionType, options.library.LibraryOptions); - } - - function onDialogClosing() { - - var dlg = this; - - var libraryOptions = libraryoptionseditor.getLibraryOptions(dlg.querySelector('.libraryOptions')); - - libraryOptions = Object.assign(currentOptions.library.LibraryOptions || {}, libraryOptions); - - ApiClient.updateVirtualFolderOptions(currentOptions.library.ItemId, libraryOptions); - } - - function onDialogClosed() { - - Dashboard.hideLoadingMsg(); - - // hardcoding this to true for now until libraryOptions are taken into account - hasChanges = true; - - currentDeferred.resolveWith(null, [hasChanges]); - } - - function editor() { - - var self = this; - - self.show = function (options) { - - var deferred = jQuery.Deferred(); - - currentOptions = options; - currentDeferred = deferred; - hasChanges = false; - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/medialibraryeditor/medialibraryeditor.template.html', true); - - xhr.onload = function (e) { - - var template = this.response; - var dlg = dialogHelper.createDialog({ - size: 'medium', - - // In (at least) chrome this is causing the text field to not be editable - modal: false, - removeOnClose: true, - scrollY: false - }); - - dlg.classList.add('dlg-libraryeditor'); - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - dlg.classList.add('formDialog'); - - dlg.innerHTML = Globalize.translateDocument(template); - - dlg.querySelector('.formDialogHeaderTitle').innerHTML = options.library.Name; - - initEditor(dlg, options); - - dlg.addEventListener('closing', onDialogClosing); - dlg.addEventListener('close', onDialogClosed); - - dialogHelper.open(dlg); - - dlg.querySelector('.btnCancel').addEventListener('click', function () { - - dialogHelper.close(dlg); - }); - - refreshLibraryFromServer(dlg); - } - - xhr.send(); - - return deferred.promise(); - }; - } - - return editor; -}); \ No newline at end of file +define(["dialogHelper","dom","components/libraryoptionseditor/libraryoptionseditor","emby-button","listViewStyle","paper-icon-button-light","formDialogStyle"],function(dialogHelper,dom,libraryoptionseditor){"use strict";function addMediaLocation(page,path,networkSharePath){var virtualFolder=currentOptions.library,refreshAfterChange=currentOptions.refresh;ApiClient.addMediaPath(virtualFolder.Name,path,networkSharePath,refreshAfterChange).then(function(){hasChanges=!0,refreshLibraryFromServer(page)},function(){require(["toast"],function(toast){toast(Globalize.translate("ErrorAddingMediaPathToVirtualFolder"))})})}function updateMediaLocation(page,path,networkSharePath){var virtualFolder=currentOptions.library;ApiClient.updateMediaPath(virtualFolder.Name,{Path:path,NetworkPath:networkSharePath}).then(function(){hasChanges=!0,refreshLibraryFromServer(page)},function(){require(["toast"],function(toast){toast(Globalize.translate("ErrorAddingMediaPathToVirtualFolder"))})})}function onRemoveClick(btnRemovePath){var button=btnRemovePath,index=parseInt(button.getAttribute("data-index")),virtualFolder=currentOptions.library,location=virtualFolder.Locations[index];require(["confirm"],function(confirm){confirm({title:Globalize.translate("HeaderRemoveMediaLocation"),text:Globalize.translate("MessageConfirmRemoveMediaLocation"),confirmText:Globalize.translate("ButtonDelete"),primary:"cancel"}).then(function(){var refreshAfterChange=currentOptions.refresh;ApiClient.removeMediaPath(virtualFolder.Name,location,refreshAfterChange).then(function(){hasChanges=!0,refreshLibraryFromServer(dom.parentWithClass(button,"dlg-libraryeditor"))},function(){require(["toast"],function(toast){toast(Globalize.translate("DefaultErrorMessage"))})})})})}function onListItemClick(e){var btnRemovePath=dom.parentWithClass(e.target,"btnRemovePath");if(btnRemovePath)return void onRemoveClick(btnRemovePath);var listItem=dom.parentWithClass(e.target,"listItem");if(listItem){var index=parseInt(listItem.getAttribute("data-index")),page=dom.parentWithClass(listItem,"dlg-libraryeditor");showDirectoryBrowser(page,index)}}function getFolderHtml(pathInfo,index){var html="";html+='
',html+='folder';var cssClass=pathInfo.NetworkPath?"listItemBody two-line":"listItemBody";return html+='
',html+='

',html+=pathInfo.Path,html+="

",pathInfo.NetworkPath&&(html+='
'+pathInfo.NetworkPath+"
"),html+="
",html+='',html+="
"}function refreshLibraryFromServer(page){ApiClient.getVirtualFolders().then(function(result){var library=result.filter(function(f){return f.Name==currentOptions.library.Name})[0];library&&(currentOptions.library=library,renderLibrary(page,currentOptions))})}function renderLibrary(page,options){var pathInfos=(options.library.LibraryOptions||{}).PathInfos||[];pathInfos.length||(pathInfos=options.library.Locations.map(function(p){return{Path:p}}));var foldersHtml=pathInfos.map(getFolderHtml).join("");page.querySelector(".folderList").innerHTML=foldersHtml;for(var listItems=page.querySelectorAll(".listItem"),i=0,length=listItems.length;i 0) { - draggingY = true; - } - - if (!draggingX && !draggingY && (!isOpen || Math.abs(ev.deltaX) >= 10)) { - draggingX = true; - scrollContainer.addEventListener('scroll', disableEvent); - self.showMask(); - - } else if (!draggingY) { - draggingY = true; - } - - if (draggingX) { - newPos = currentPos + ev.deltaX; - self.changeMenuPos(); - } - } - - function onPanEnd(ev) { - options.target.classList.add('transition'); - scrollContainer.removeEventListener('scroll', disableEvent); - draggingX = false; - draggingY = false; - currentPos = ev.deltaX; - self.checkMenuState(ev.deltaX, ev.deltaY); - } - - function initEdgeSwipe(Hammer) { - if (options.disableEdgeSwipe) { - return; - } - return; - require(['hammer-main'], initEdgeSwipeInternal); - } - - function initEdgeSwipeInternal(edgeHammer) { - var isPeeking = false; - - edgeHammer.on('panstart panmove', function (ev) { - - if (isPeeking) { - onPanMove(ev); - } else { - var srcEvent = ev.srcEvent; - var clientX = srcEvent.clientX; - if (!clientX) { - var touches = srcEvent.touches; - if (touches && touches.length) { - clientX = touches[0].clientX; - } - } - if (clientX <= options.handleSize) { - isPeeking = true; - onPanStart(ev); - } - } - }); - edgeHammer.on('panend pancancel', function (ev) { - if (isPeeking) { - isPeeking = false; - onPanEnd(ev); - } - }); - - self.edgeHammer = edgeHammer; - } - - function disableEvent(e) { - - e.preventDefault(); - e.stopPropagation(); - } - - TouchMenuLA.prototype.touchStartMenu = function () { - - menuHammer.on('panstart', function (ev) { - onPanStart(ev); - }); - menuHammer.on('panmove', function (ev) { - onPanMove(ev); - }); - }; - - TouchMenuLA.prototype.animateToPosition = function (pos) { - - requestAnimationFrame(function () { - if (pos) { - options.target.style.transform = 'translate3d(' + pos + 'px, 0, 0)'; - } else { - options.target.style.transform = 'none'; - } - }); - }; - - TouchMenuLA.prototype.changeMenuPos = function () { - if (newPos <= options.width) { - this.animateToPosition(newPos); - } - }; - - TouchMenuLA.prototype.touchEndMenu = function () { - menuHammer.on('panend pancancel', onPanEnd); - }; - - TouchMenuLA.prototype.clickMaskClose = function () { - mask.addEventListener('click', function () { - self.close(); - }); - }; - - TouchMenuLA.prototype.checkMenuState = function (deltaX, deltaY) { - if (velocity >= 1.0) { - if (deltaX >= -80 || Math.abs(deltaY) >= 70) { - self.open(); - } else { - self.close(); - } - } else { - if (newPos >= 100) { - self.open(); - } else { - self.close(); - } - } - }; - - TouchMenuLA.prototype.open = function () { - this.animateToPosition(options.width); - - currentPos = options.width; - this.isVisible = true; - options.target.classList.add('open'); - - self.showMask(); - self.invoke(options.onChange); - }; - - TouchMenuLA.prototype.close = function () { - this.animateToPosition(0); - currentPos = 0; - self.isVisible = false; - options.target.classList.remove('open'); - - self.hideMask(); - self.invoke(options.onChange); - }; - - TouchMenuLA.prototype.toggle = function () { - if (self.isVisible) { - self.close(); - } else { - self.open(); - } - }; - - TouchMenuLA.prototype.eventStartMask = function () { - maskHammer.on('panstart panmove', function (ev) { - if (ev.center.x <= options.width && self.isVisible) { - countStart++; - - if (countStart == 1) { - startPoint = ev.deltaX; - } - - if (ev.deltaX < 0) { - draggingX = true; - newPos = (ev.deltaX - startPoint) + options.width; - self.changeMenuPos(); - velocity = Math.abs(ev.velocity); - } - } - }); - }; - - TouchMenuLA.prototype.eventEndMask = function () { - maskHammer.on('panend pancancel', function (ev) { - self.checkMenuState(ev.deltaX); - countStart = 0; - }); - }; - - TouchMenuLA.prototype.showMask = function () { - - mask.classList.add('backdrop'); - }; - - TouchMenuLA.prototype.hideMask = function () { - - mask.classList.remove('backdrop'); - }; - - TouchMenuLA.prototype.invoke = function (fn) { - if (fn) { - fn.apply(self); - } - }; - - function initWithHammer(Hammer) { - - if (Hammer) { - menuHammer = Hammer(options.target, null); - } - - self.initElements(Hammer); - - if (Hammer) { - self.touchStartMenu(); - self.touchEndMenu(); - self.eventStartMask(); - self.eventEndMask(); - initEdgeSwipe(Hammer); - } - - if (!options.disableMask) { - self.clickMaskClose(); - } - } - - TouchMenuLA.prototype.initialize = function () { - - options = Object.assign(defaults, options || {}); - - // Not ready yet - if (browser.edge) { - options.disableEdgeSwipe = true; - } - - if (browser.touch) { - require(['hammer'], initWithHammer); - } else { - initWithHammer(); - } - }; - - return new TouchMenuLA(); - }; -}); \ No newline at end of file +define(["browser","css!./navdrawer","scrollStyles"],function(browser){"use strict";return function(options){function onPanStart(ev){options.target.classList.remove("transition"),options.target.classList.add("open"),velocity=Math.abs(ev.velocity)}function onPanMove(ev){velocity=Math.abs(ev.velocity);var isOpen=self.visible;isOpen&&!draggingX&&ev.deltaX>0&&(draggingY=!0),draggingX||draggingY||isOpen&&!(Math.abs(ev.deltaX)>=10)?draggingY||(draggingY=!0):(draggingX=!0,scrollContainer.addEventListener("scroll",disableEvent),self.showMask()),draggingX&&(newPos=currentPos+ev.deltaX,self.changeMenuPos())}function onPanEnd(ev){options.target.classList.add("transition"),scrollContainer.removeEventListener("scroll",disableEvent),draggingX=!1,draggingY=!1,currentPos=ev.deltaX,self.checkMenuState(ev.deltaX,ev.deltaY)}function initEdgeSwipe(Hammer){options.disableEdgeSwipe}function disableEvent(e){e.preventDefault(),e.stopPropagation()}function initWithHammer(Hammer){Hammer&&(menuHammer=Hammer(options.target,null)),self.initElements(Hammer),Hammer&&(self.touchStartMenu(),self.touchEndMenu(),self.eventStartMask(),self.eventEndMask(),initEdgeSwipe(Hammer)),options.disableMask||self.clickMaskClose()}var self,defaults,mask,maskHammer,menuHammer,newPos=0,currentPos=0,startPoint=0,countStart=0,velocity=0;options.target.classList.add("transition");var draggingX,draggingY,scrollContainer=options.target.querySelector(".scrollContainer");scrollContainer.classList.add("smoothScrollY");var TouchMenuLA=function(){self=this,defaults={width:260,handleSize:30,disableMask:!1,maxMaskOpacity:.5},this.isVisible=!1,this.initialize()};return TouchMenuLA.prototype.initElements=function(Hammer){options.target.classList.add("touch-menu-la"),options.target.style.width=options.width+"px",options.target.style.left=-options.width+"px",options.disableMask||(mask=document.createElement("div"),mask.className="tmla-mask",document.body.appendChild(mask),Hammer&&(maskHammer=new Hammer(mask,null)))},TouchMenuLA.prototype.touchStartMenu=function(){menuHammer.on("panstart",function(ev){onPanStart(ev)}),menuHammer.on("panmove",function(ev){onPanMove(ev)})},TouchMenuLA.prototype.animateToPosition=function(pos){requestAnimationFrame(function(){pos?options.target.style.transform="translate3d("+pos+"px, 0, 0)":options.target.style.transform="none"})},TouchMenuLA.prototype.changeMenuPos=function(){newPos<=options.width&&this.animateToPosition(newPos)},TouchMenuLA.prototype.touchEndMenu=function(){menuHammer.on("panend pancancel",onPanEnd)},TouchMenuLA.prototype.clickMaskClose=function(){mask.addEventListener("click",function(){self.close()})},TouchMenuLA.prototype.checkMenuState=function(deltaX,deltaY){velocity>=1?deltaX>=-80||Math.abs(deltaY)>=70?self.open():self.close():newPos>=100?self.open():self.close()},TouchMenuLA.prototype.open=function(){this.animateToPosition(options.width),currentPos=options.width,this.isVisible=!0,options.target.classList.add("open"),self.showMask(),self.invoke(options.onChange)},TouchMenuLA.prototype.close=function(){this.animateToPosition(0),currentPos=0,self.isVisible=!1,options.target.classList.remove("open"),self.hideMask(),self.invoke(options.onChange)},TouchMenuLA.prototype.toggle=function(){self.isVisible?self.close():self.open()},TouchMenuLA.prototype.eventStartMask=function(){maskHammer.on("panstart panmove",function(ev){ev.center.x<=options.width&&self.isVisible&&(countStart++,1==countStart&&(startPoint=ev.deltaX),ev.deltaX<0&&(draggingX=!0,newPos=ev.deltaX-startPoint+options.width,self.changeMenuPos(),velocity=Math.abs(ev.velocity)))})},TouchMenuLA.prototype.eventEndMask=function(){maskHammer.on("panend pancancel",function(ev){self.checkMenuState(ev.deltaX),countStart=0})},TouchMenuLA.prototype.showMask=function(){mask.classList.add("backdrop")},TouchMenuLA.prototype.hideMask=function(){mask.classList.remove("backdrop")},TouchMenuLA.prototype.invoke=function(fn){fn&&fn.apply(self)},TouchMenuLA.prototype.initialize=function(){options=Object.assign(defaults,options||{}),browser.edge&&(options.disableEdgeSwipe=!0),browser.touch?require(["hammer"],initWithHammer):initWithHammer()},new TouchMenuLA}}); \ No newline at end of file diff --git a/dashboard-ui/components/remotecontrol.js b/dashboard-ui/components/remotecontrol.js index 8bab8ee2bc..37648df5cc 100644 --- a/dashboard-ui/components/remotecontrol.js +++ b/dashboard-ui/components/remotecontrol.js @@ -1,954 +1 @@ -define(['browser', 'datetime', 'backdrop', 'libraryBrowser', 'listView', 'userdataButtons', 'imageLoader', 'playbackManager', 'nowPlayingHelper', 'events', 'connectionManager', 'apphost', 'globalize', 'cardStyle', 'emby-itemscontainer', 'css!css/nowplaying.css'], function (browser, datetime, backdrop, libraryBrowser, listView, userdataButtons, imageLoader, playbackManager, nowPlayingHelper, events, connectionManager, appHost, globalize) { - 'use strict'; - - function showSlideshowMenu(context) { - require(['scripts/slideshow'], function () { - SlideShow.showMenu(); - }); - } - - function showAudioMenu(context, player, button, item) { - - var currentIndex = playbackManager.getAudioStreamIndex(player); - - var streams = (item.MediaStreams || []).filter(function (i) { - - return i.Type == 'Audio'; - }); - - var menuItems = streams.map(function (s) { - - var menuItem = { - name: s.DisplayTitle, - id: s.Index - }; - - if (s.Index == currentIndex) { - menuItem.selected = true; - } - - return menuItem; - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: button, - callback: function (id) { - - playbackManager.setAudioStreamIndex(parseInt(id), player); - } - }); - - }); - } - - function showSubtitleMenu(context, player, button, item) { - - var currentIndex = playbackManager.getSubtitleStreamIndex(player); - - var streams = (item.MediaStreams || []).filter(function (i) { - - return i.Type == 'Subtitle'; - }); - - var menuItems = streams.map(function (s) { - - var menuItem = { - name: s.DisplayTitle, - id: s.Index - }; - - if (s.Index == currentIndex) { - menuItem.selected = true; - } - - return menuItem; - }); - - menuItems.unshift({ - id: -1, - name: globalize.translate('ButtonOff'), - selected: currentIndex == null - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: button, - callback: function (id) { - - playbackManager.setSubtitleStreamIndex(parseInt(id), player); - } - }); - - }); - } - - function showButton(button) { - button.classList.remove('hide'); - } - - function hideButton(button) { - button.classList.add('hide'); - } - - function hasStreams(item, type) { - return item && item.MediaStreams && item.MediaStreams.filter(function (i) { - return i.Type == type; - }).length > 0; - } - - function getNowPlayingNameHtml(nowPlayingItem, includeNonNameInfo) { - - var names = nowPlayingHelper.getNowPlayingNames(nowPlayingItem, includeNonNameInfo); - - return names.map(function (i) { - - return i.text; - - }).join('
'); - } - - function seriesImageUrl(item, options) { - - if (item.Type !== 'Episode') { - return null; - } - - options = options || {}; - options.type = options.type || "Primary"; - - if (options.type === 'Primary') { - - if (item.SeriesPrimaryImageTag) { - - options.tag = item.SeriesPrimaryImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - } - - if (options.type === 'Thumb') { - - if (item.SeriesThumbImageTag) { - - options.tag = item.SeriesThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - if (item.ParentThumbImageTag) { - - options.tag = item.ParentThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId, options); - } - } - - return null; - } - - function imageUrl(item, options) { - - options = options || {}; - options.type = options.type || "Primary"; - - if (item.ImageTags && item.ImageTags[options.type]) { - - options.tag = item.ImageTags[options.type]; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId || item.Id, options); - } - - if (item.AlbumId && item.AlbumPrimaryImageTag) { - - options.tag = item.AlbumPrimaryImageTag; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId, options); - } - - return null; - } - var currentImgUrl; - function updateNowPlayingInfo(context, state) { - - var item = state.NowPlayingItem; - var displayName = item ? getNowPlayingNameHtml(item).replace('
', ' - ') : ''; - - context.querySelector('.nowPlayingPageTitle').innerHTML = displayName; - - if (displayName.length > 0) { - context.querySelector('.nowPlayingPageTitle').classList.remove('hide'); - } else { - context.querySelector('.nowPlayingPageTitle').classList.add('hide'); - } - - var url = item ? seriesImageUrl(item, { - - maxHeight: 300 - - }) || imageUrl(item, { - maxHeight: 300 - - }) : null; - - if (url === currentImgUrl) { - return; - } - - setImageUrl(context, url); - - if (item) { - - backdrop.setBackdrops([item]); - - ApiClient.getItem(Dashboard.getCurrentUserId(), item.Id).then(function (fullItem) { - userdataButtons.fill({ - item: fullItem, - includePlayed: false, - style: 'icon', - element: context.querySelector('.nowPlayingPageUserDataButtons'), - }); - }); - } else { - - backdrop.clear(); - - userdataButtons.destroy({ - element: context.querySelector('.nowPlayingPageUserDataButtons') - }); - } - } - - function setImageUrl(context, url) { - currentImgUrl = url; - - var imgContainer = context.querySelector('.nowPlayingPageImageContainer'); - - if (url) { - imgContainer.innerHTML = ''; - imgContainer.classList.remove('hide'); - } else { - imgContainer.classList.add('hide'); - imgContainer.innerHTML = ''; - } - } - - function buttonEnabled(btn, enabled) { - btn.disabled = !enabled; - } - - function buttonVisible(btn, enabled) { - if (enabled) { - btn.classList.remove('hide'); - } else { - btn.classList.add('hide'); - } - } - - function updateSupportedCommands(context, commands) { - - var all = context.querySelectorAll('.btnCommand'); - - for (var i = 0, length = all.length; i < length; i++) { - buttonEnabled(all[i], commands.indexOf(all[i].getAttribute('data-command')) != -1); - } - } - - return function () { - - var dlg; - var currentPlayer; - var currentPlayerSupportedCommands = []; - var lastPlayerState; - var lastUpdateTime = 0; - var currentRuntimeTicks = 0; - - var self = this; - - function toggleRepeat(player) { - - if (player) { - switch (playbackManager.getRepeatMode(player)) { - case 'RepeatNone': - playbackManager.setRepeatMode('RepeatAll', player); - break; - case 'RepeatAll': - playbackManager.setRepeatMode('RepeatOne', player); - break; - case 'RepeatOne': - playbackManager.setRepeatMode('RepeatNone', player); - break; - } - } - } - - function updatePlayerState(context, state) { - - lastPlayerState = state; - - var item = state.NowPlayingItem; - - var playerInfo = playbackManager.getPlayerInfo(); - - var supportedCommands = playerInfo.supportedCommands; - var playState = state.PlayState || {}; - - buttonVisible(context.querySelector('.btnToggleFullscreen'), item && item.MediaType == 'Video' && supportedCommands.indexOf('ToggleFullscreen') != -1); - buttonVisible(context.querySelector('.btnAudioTracks'), hasStreams(item, 'Audio') && supportedCommands.indexOf('SetAudioStreamIndex') != -1); - buttonVisible(context.querySelector('.btnSubtitles'), hasStreams(item, 'Subtitle') && supportedCommands.indexOf('SetSubtitleStreamIndex') != -1); - - if (supportedCommands.indexOf('DisplayMessage') != -1) { - context.querySelector('.sendMessageSection').classList.remove('hide'); - } else { - context.querySelector('.sendMessageSection').classList.add('hide'); - } - if (supportedCommands.indexOf('SendString') != -1) { - context.querySelector('.sendTextSection').classList.remove('hide'); - } else { - context.querySelector('.sendTextSection').classList.add('hide'); - } - - buttonVisible(context.querySelector('.btnStop'), item != null); - buttonVisible(context.querySelector('.btnNextTrack'), item != null); - buttonVisible(context.querySelector('.btnPreviousTrack'), item != null); - - var positionSlider = context.querySelector('.nowPlayingPositionSlider'); - if (positionSlider && !positionSlider.dragging) { - positionSlider.disabled = !playState.CanSeek; - } - - updatePlayPauseState(playState.IsPaused, item != null); - - var runtimeTicks = item ? item.RunTimeTicks : null; - updateTimeDisplay(playState.PositionTicks, runtimeTicks); - updatePlayerVolumeState(context, playState.IsMuted, playState.VolumeLevel); - - if (item && item.MediaType == 'Video') { - context.classList.remove('hideVideoButtons'); - } else { - context.classList.add('hideVideoButtons'); - } - - updateRepeatModeDisplay(playState.RepeatMode); - updateNowPlayingInfo(context, state); - } - - function updateRepeatModeDisplay(repeatMode) { - - var context = dlg; - var toggleRepeatButton = context.querySelector('.repeatToggleButton'); - - if (repeatMode == 'RepeatAll') { - toggleRepeatButton.innerHTML = "repeat"; - toggleRepeatButton.classList.add('nowPlayingPageRepeatActive'); - } - else if (repeatMode == 'RepeatOne') { - toggleRepeatButton.innerHTML = "repeat_one"; - toggleRepeatButton.classList.add('nowPlayingPageRepeatActive'); - } else { - toggleRepeatButton.innerHTML = "repeat"; - toggleRepeatButton.classList.remove('nowPlayingPageRepeatActive'); - } - } - - function updatePlayerVolumeState(context, isMuted, volumeLevel) { - - var view = context; - var supportedCommands = currentPlayerSupportedCommands; - - var showMuteButton = true; - var showVolumeSlider = true; - - if (supportedCommands.indexOf('Mute') === -1) { - showMuteButton = false; - } - - if (supportedCommands.indexOf('SetVolume') === -1) { - showVolumeSlider = false; - } - - if (currentPlayer.isLocalPlayer && appHost.supports('physicalvolumecontrol')) { - showMuteButton = false; - showVolumeSlider = false; - } - - if (isMuted) { - view.querySelector('.buttonMute').setAttribute('title', globalize.translate('Unmute')); - view.querySelector('.buttonMute i').innerHTML = ''; - } else { - view.querySelector('.buttonMute').setAttribute('title', globalize.translate('Mute')); - view.querySelector('.buttonMute i').innerHTML = ''; - } - - if (showMuteButton) { - view.querySelector('.buttonMute').classList.remove('hide'); - } else { - view.querySelector('.buttonMute').classList.add('hide'); - } - - var nowPlayingVolumeSlider = context.querySelector('.nowPlayingVolumeSlider'); - var nowPlayingVolumeSliderContainer = context.querySelector('.nowPlayingVolumeSliderContainer'); - - // See bindEvents for why this is necessary - if (nowPlayingVolumeSlider) { - - if (showVolumeSlider) { - nowPlayingVolumeSliderContainer.classList.remove('hide'); - } else { - nowPlayingVolumeSliderContainer.classList.add('hide'); - } - - if (!nowPlayingVolumeSlider.dragging) { - nowPlayingVolumeSlider.value = volumeLevel || 0; - } - } - } - - function updatePlayPauseState(isPaused, isActive) { - - var context = dlg; - - var btnPlayPause = context.querySelector('.btnPlayPause'); - if (isPaused) { - btnPlayPause.querySelector('i').innerHTML = 'play_arrow'; - } else { - btnPlayPause.querySelector('i').innerHTML = 'pause'; - } - - buttonVisible(btnPlayPause, isActive); - } - - function updateTimeDisplay(positionTicks, runtimeTicks) { - - // See bindEvents for why this is necessary - var context = dlg; - var positionSlider = context.querySelector('.nowPlayingPositionSlider'); - - if (positionSlider && !positionSlider.dragging) { - if (runtimeTicks) { - - var pct = positionTicks / runtimeTicks; - pct *= 100; - - positionSlider.value = pct; - - } else { - - positionSlider.value = 0; - } - } - - if (positionTicks == null) { - context.querySelector('.positionTime').innerHTML = '--:--'; - } else { - context.querySelector('.positionTime').innerHTML = datetime.getDisplayRunningTime(positionTicks); - } - - if (runtimeTicks != null) { - context.querySelector('.runtime').innerHTML = datetime.getDisplayRunningTime(runtimeTicks); - } else { - context.querySelector('.runtime').innerHTML = '--:--'; - } - } - - function getPlaylistItems(player) { - - return playbackManager.getPlaylist(player); - - return ApiClient.getItems(Dashboard.getCurrentUserId(), { - - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Audio", - Recursive: true, - Fields: "PrimaryImageAspectRatio,SortName,MediaSourceCount", - StartIndex: 0, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - Limit: 100 - - }).then(function (result) { - - return result.Items; - }); - } - - function loadPlaylist(context, player) { - - getPlaylistItems(player).then(function (items) { - - var html = ''; - - html += listView.getListViewHtml({ - items: items, - smallIcon: true, - action: 'setplaylistindex', - enableUserDataButtons: false, - rightButtons: [ - { - icon: '', - title: globalize.translate('ButtonRemove'), - id: 'remove' - }], - dragHandle: true - }); - - if (items.length) { - context.querySelector('.playlistSection').classList.remove('hide'); - } else { - context.querySelector('.playlistSection').classList.add('hide'); - } - - var itemsContainer = context.querySelector('.playlist'); - - itemsContainer.innerHTML = html; - - var playlistItemId = playbackManager.getCurrentPlaylistItemId(player); - - if (playlistItemId) { - - var img = itemsContainer.querySelector('.listItem[data-playlistItemId="' + playlistItemId + '"] .listItemImage'); - if (img) { - - img.classList.remove('lazy'); - img.classList.add('playlistIndexIndicatorImage'); - } - } - - imageLoader.lazyChildren(itemsContainer); - }); - } - - function onPlaybackStart(e, state) { - - console.log('remotecontrol event: ' + e.type); - - var player = this; - onStateChanged.call(player, e, state); - } - - function onRepeatModeChange(e) { - - var player = this; - - updateRepeatModeDisplay(playbackManager.getRepeatMode(player)); - } - - function onPlaylistUpdate(e) { - - var player = this; - - loadPlaylist(dlg, player); - } - - function onPlaylistItemRemoved(e, info) { - - var context = dlg; - - var playlistItemIds = info.playlistItemIds; - - for (var i = 0, length = playlistItemIds.length; i < length; i++) { - - var listItem = context.querySelector('.listItem[data-playlistItemId="' + playlistItemIds[i] + '"]'); - - if (listItem) { - listItem.parentNode.removeChild(listItem); - } - } - } - - function onPlaybackStopped(e, stopInfo) { - - console.log('remotecontrol event: ' + e.type); - var player = this; - - if (!stopInfo.nextMediaType) { - updatePlayerState(dlg, {}); - loadPlaylist(dlg); - } - } - - function onPlayPauseStateChanged(e) { - - var player = this; - updatePlayPauseState(player.paused(), true); - } - - function onStateChanged(event, state) { - - //console.log('nowplaying event: ' + e.type); - var player = this; - - updatePlayerState(dlg, state); - loadPlaylist(dlg, player); - } - - function onTimeUpdate(e) { - - // Try to avoid hammering the document with changes - var now = new Date().getTime(); - if ((now - lastUpdateTime) < 700) { - - return; - } - lastUpdateTime = now; - - var player = this; - currentRuntimeTicks = playbackManager.duration(player); - updateTimeDisplay(playbackManager.currentTime(player), currentRuntimeTicks); - } - - function onVolumeChanged(e) { - - var player = this; - - updatePlayerVolumeState(dlg, player.isMuted(), player.getVolume()); - } - - function releaseCurrentPlayer() { - - var player = currentPlayer; - - if (player) { - - events.off(player, 'playbackstart', onPlaybackStart); - events.off(player, 'statechange', onStateChanged); - events.off(player, 'repeatmodechange', onRepeatModeChange); - events.off(player, 'playlistitemremove', onPlaylistUpdate); - events.off(player, 'playlistitemmove', onPlaylistUpdate); - events.off(player, 'playbackstop', onPlaybackStopped); - events.off(player, 'volumechange', onVolumeChanged); - events.off(player, 'pause', onPlayPauseStateChanged); - events.off(player, 'playing', onPlayPauseStateChanged); - events.off(player, 'timeupdate', onTimeUpdate); - - currentPlayer = null; - } - } - - function bindToPlayer(context, player) { - - releaseCurrentPlayer(); - - currentPlayer = player; - - if (!player) { - return; - } - - playbackManager.getPlayerState(player).then(function (state) { - - onStateChanged.call(player, { type: 'init' }, state); - }); - - events.on(player, 'playbackstart', onPlaybackStart); - events.on(player, 'statechange', onStateChanged); - events.on(player, 'repeatmodechange', onRepeatModeChange); - events.on(player, 'playlistitemremove', onPlaylistItemRemoved); - events.on(player, 'playlistitemmove', onPlaylistUpdate); - events.on(player, 'playbackstop', onPlaybackStopped); - events.on(player, 'volumechange', onVolumeChanged); - events.on(player, 'pause', onPlayPauseStateChanged); - events.on(player, 'playing', onPlayPauseStateChanged); - events.on(player, 'timeupdate', onTimeUpdate); - - var playerInfo = playbackManager.getPlayerInfo(); - - var supportedCommands = playerInfo.supportedCommands; - currentPlayerSupportedCommands = supportedCommands; - - updateSupportedCommands(context, supportedCommands); - } - - function updateCastIcon(context) { - - var info = playbackManager.getPlayerInfo(); - var btnCast = context.querySelector('.btnCast'); - - if (info && !info.isLocalPlayer) { - - btnCast.querySelector('i').innerHTML = 'cast_connected'; - btnCast.classList.add('btnActiveCast'); - } else { - btnCast.querySelector('i').innerHTML = 'cast'; - btnCast.classList.remove('btnActiveCast'); - } - } - - function onBtnCommandClick() { - if (currentPlayer) { - - if (this.classList.contains('repeatToggleButton')) { - toggleRepeat(currentPlayer); - } else { - playbackManager.sendCommand({ - Name: this.getAttribute('data-command') - - }, currentPlayer); - } - } - } - - function getSaveablePlaylistItems() { - - return getPlaylistItems(currentPlayer).then(function (items) { - - return items.filter(function (i) { - return i.Id && i.ServerId; - }); - }); - } - - function savePlaylist() { - - require(['playlistEditor'], function (playlistEditor) { - - getSaveablePlaylistItems().then(function (items) { - - var serverId = items.length ? items[0].ServerId : ApiClient.serverId(); - - new playlistEditor().show({ - items: items.map(function(i) { - return i.Id; - }), - serverId: serverId, - enableAddToPlayQueue: false, - defaultValue: 'new' - }); - }); - }); - } - - function bindEvents(context) { - - var btnCommand = context.querySelectorAll('.btnCommand'); - for (var i = 0, length = btnCommand.length; i < length; i++) { - btnCommand[i].addEventListener('click', onBtnCommandClick); - } - - context.querySelector('.btnToggleFullscreen').addEventListener('click', function (e) { - - if (currentPlayer) { - playbackManager.sendCommand({ - Name: e.target.getAttribute('data-command') - - }, currentPlayer); - } - }); - - context.querySelector('.btnAudioTracks').addEventListener('click', function (e) { - - if (currentPlayer && lastPlayerState && lastPlayerState.NowPlayingItem) { - - showAudioMenu(context, currentPlayer, e.target, lastPlayerState.NowPlayingItem); - } - }); - - context.querySelector('.btnSubtitles').addEventListener('click', function (e) { - - if (currentPlayer && lastPlayerState && lastPlayerState.NowPlayingItem) { - - showSubtitleMenu(context, currentPlayer, e.target, lastPlayerState.NowPlayingItem); - } - }); - - context.querySelector('.btnStop').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.stop(currentPlayer); - } - }); - - context.querySelector('.btnPlayPause').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.playPause(currentPlayer); - } - }); - - context.querySelector('.btnNextTrack').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.nextTrack(currentPlayer); - } - }); - - context.querySelector('.btnPreviousTrack').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.previousTrack(currentPlayer); - } - }); - - context.querySelector('.nowPlayingPositionSlider').addEventListener('change', function () { - - var value = this.value; - - if (currentPlayer) { - - var newPercent = parseFloat(value); - playbackManager.seekPercent(newPercent, currentPlayer); - } - }); - - context.querySelector('.nowPlayingPositionSlider').getBubbleText = function (value) { - - var state = lastPlayerState; - - if (!state || !state.NowPlayingItem || !currentRuntimeTicks) { - return '--:--'; - } - - var ticks = currentRuntimeTicks; - ticks /= 100; - ticks *= value; - - return datetime.getDisplayRunningTime(ticks); - }; - - context.querySelector('.nowPlayingVolumeSlider').addEventListener('change', function () { - - playbackManager.setVolume(this.value, currentPlayer); - }); - - context.querySelector('.buttonMute').addEventListener('click', function () { - - playbackManager.toggleMute(currentPlayer); - }); - - var playlistContainer = context.querySelector('.playlist'); - - playlistContainer.addEventListener('action-remove', function (e) { - - playbackManager.removeFromPlaylist([e.detail.playlistItemId], currentPlayer); - }); - playlistContainer.addEventListener('itemdrop', function (e) { - - var newIndex = e.detail.newIndex; - var playlistItemId = e.detail.playlistItemId; - - playbackManager.movePlaylistItem(playlistItemId, newIndex, currentPlayer); - }); - - context.querySelector('.btnSavePlaylist').addEventListener('click', savePlaylist); - } - - function onPlayerChange() { - - var context = dlg; - updateCastIcon(context); - bindToPlayer(context, playbackManager.getCurrentPlayer()); - } - - function onMessageSubmit(e) { - - var form = e.target; - - playbackManager.sendCommand({ - Name: 'DisplayMessage', - Arguments: { - - Header: form.querySelector('#txtMessageTitle').value, - Text: form.querySelector('#txtMessageText', form).value - } - - }, currentPlayer); - - form.querySelector('input').value = ''; - require(['toast'], function (toast) { - toast('Message sent.'); - }); - - e.preventDefault(); - e.stopPropagation(); - return false; - } - - function onSendStringSubmit(e) { - - var form = e.target; - - playbackManager.sendCommand({ - Name: 'SendString', - Arguments: { - - String: form.querySelector('#txtTypeText', form).value - } - - }, currentPlayer); - - form.querySelector('input').value = ''; - require(['toast'], function (toast) { - toast('Text sent.'); - }); - - e.preventDefault(); - e.stopPropagation(); - return false; - } - - function init(ownerView, context) { - - bindEvents(context); - - context.querySelector('.sendMessageForm').addEventListener('submit', onMessageSubmit); - context.querySelector('.typeTextForm').addEventListener('submit', onSendStringSubmit); - - context.querySelector('.btnCast').addEventListener('click', function () { - var btn = this; - require(['playerSelectionMenu'], function (playerSelectionMenu) { - playerSelectionMenu.show(btn); - }); - }); - - context.querySelector('.btnExitRemoteControl').addEventListener('click', function () { - history.back(); - }); - - //context.querySelector('.btnSlideshow').addEventListener('click', function () { - // showSlideshowMenu(context); - //}); - - events.on(playbackManager, 'playerchange', onPlayerChange); - - if (appHost.supports('remotecontrol')) { - context.querySelector('.btnCast').classList.remove('hide'); - } - } - - function onDialogClosed(e) { - - releaseCurrentPlayer(); - - events.off(playbackManager, 'playerchange', onPlayerChange); - - lastPlayerState = null; - } - - function onShow(context, tab) { - - currentImgUrl = null; - - bindToPlayer(context, playbackManager.getCurrentPlayer()); - - updateCastIcon(context); - } - - self.init = function (ownerView, context) { - - dlg = context; - - init(ownerView, dlg); - }; - - self.onShow = function () { - onShow(dlg, window.location.hash); - }; - - self.destroy = function () { - onDialogClosed(); - }; - - }; -}); \ No newline at end of file +define(["browser","datetime","backdrop","libraryBrowser","listView","userdataButtons","imageLoader","playbackManager","nowPlayingHelper","events","connectionManager","apphost","globalize","cardStyle","emby-itemscontainer","css!css/nowplaying.css"],function(browser,datetime,backdrop,libraryBrowser,listView,userdataButtons,imageLoader,playbackManager,nowPlayingHelper,events,connectionManager,appHost,globalize){"use strict";function showAudioMenu(context,player,button,item){var currentIndex=playbackManager.getAudioStreamIndex(player),streams=(item.MediaStreams||[]).filter(function(i){return"Audio"==i.Type}),menuItems=streams.map(function(s){var menuItem={name:s.DisplayTitle,id:s.Index};return s.Index==currentIndex&&(menuItem.selected=!0),menuItem});require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:button,callback:function(id){playbackManager.setAudioStreamIndex(parseInt(id),player)}})})}function showSubtitleMenu(context,player,button,item){var currentIndex=playbackManager.getSubtitleStreamIndex(player),streams=(item.MediaStreams||[]).filter(function(i){return"Subtitle"==i.Type}),menuItems=streams.map(function(s){var menuItem={name:s.DisplayTitle,id:s.Index};return s.Index==currentIndex&&(menuItem.selected=!0),menuItem});menuItems.unshift({id:-1,name:globalize.translate("ButtonOff"),selected:null==currentIndex}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:button,callback:function(id){playbackManager.setSubtitleStreamIndex(parseInt(id),player)}})})}function hasStreams(item,type){return item&&item.MediaStreams&&item.MediaStreams.filter(function(i){return i.Type==type}).length>0}function getNowPlayingNameHtml(nowPlayingItem,includeNonNameInfo){var names=nowPlayingHelper.getNowPlayingNames(nowPlayingItem,includeNonNameInfo);return names.map(function(i){return i.text}).join("
")}function seriesImageUrl(item,options){if("Episode"!==item.Type)return null;if(options=options||{},options.type=options.type||"Primary","Primary"===options.type&&item.SeriesPrimaryImageTag)return options.tag=item.SeriesPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if("Thumb"===options.type){if(item.SeriesThumbImageTag)return options.tag=item.SeriesThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if(item.ParentThumbImageTag)return options.tag=item.ParentThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId,options)}return null}function imageUrl(item,options){return options=options||{},options.type=options.type||"Primary",item.ImageTags&&item.ImageTags[options.type]?(options.tag=item.ImageTags[options.type],connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId||item.Id,options)):item.AlbumId&&item.AlbumPrimaryImageTag?(options.tag=item.AlbumPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId,options)):null}function updateNowPlayingInfo(context,state){var item=state.NowPlayingItem,displayName=item?getNowPlayingNameHtml(item).replace("
"," - "):"";context.querySelector(".nowPlayingPageTitle").innerHTML=displayName,displayName.length>0?context.querySelector(".nowPlayingPageTitle").classList.remove("hide"):context.querySelector(".nowPlayingPageTitle").classList.add("hide");var url=item?seriesImageUrl(item,{maxHeight:300})||imageUrl(item,{maxHeight:300}):null;url!==currentImgUrl&&(setImageUrl(context,url),item?(backdrop.setBackdrops([item]),ApiClient.getItem(Dashboard.getCurrentUserId(),item.Id).then(function(fullItem){userdataButtons.fill({item:fullItem,includePlayed:!1,style:"icon",element:context.querySelector(".nowPlayingPageUserDataButtons")})})):(backdrop.clear(),userdataButtons.destroy({element:context.querySelector(".nowPlayingPageUserDataButtons")})))}function setImageUrl(context,url){currentImgUrl=url;var imgContainer=context.querySelector(".nowPlayingPageImageContainer");url?(imgContainer.innerHTML='',imgContainer.classList.remove("hide")):(imgContainer.classList.add("hide"),imgContainer.innerHTML="")}function buttonEnabled(btn,enabled){btn.disabled=!enabled}function buttonVisible(btn,enabled){enabled?btn.classList.remove("hide"):btn.classList.add("hide")}function updateSupportedCommands(context,commands){for(var all=context.querySelectorAll(".btnCommand"),i=0,length=all.length;irepeat",toggleRepeatButton.classList.add("nowPlayingPageRepeatActive")):"RepeatOne"==repeatMode?(toggleRepeatButton.innerHTML="repeat_one",toggleRepeatButton.classList.add("nowPlayingPageRepeatActive")):(toggleRepeatButton.innerHTML="repeat",toggleRepeatButton.classList.remove("nowPlayingPageRepeatActive"))}function updatePlayerVolumeState(context,isMuted,volumeLevel){var view=context,supportedCommands=currentPlayerSupportedCommands,showMuteButton=!0,showVolumeSlider=!0;supportedCommands.indexOf("Mute")===-1&&(showMuteButton=!1),supportedCommands.indexOf("SetVolume")===-1&&(showVolumeSlider=!1),currentPlayer.isLocalPlayer&&appHost.supports("physicalvolumecontrol")&&(showMuteButton=!1,showVolumeSlider=!1),isMuted?(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Unmute")),view.querySelector(".buttonMute i").innerHTML=""):(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Mute")),view.querySelector(".buttonMute i").innerHTML=""),showMuteButton?view.querySelector(".buttonMute").classList.remove("hide"):view.querySelector(".buttonMute").classList.add("hide");var nowPlayingVolumeSlider=context.querySelector(".nowPlayingVolumeSlider"),nowPlayingVolumeSliderContainer=context.querySelector(".nowPlayingVolumeSliderContainer");nowPlayingVolumeSlider&&(showVolumeSlider?nowPlayingVolumeSliderContainer.classList.remove("hide"):nowPlayingVolumeSliderContainer.classList.add("hide"),nowPlayingVolumeSlider.dragging||(nowPlayingVolumeSlider.value=volumeLevel||0))}function updatePlayPauseState(isPaused,isActive){var context=dlg,btnPlayPause=context.querySelector(".btnPlayPause");isPaused?btnPlayPause.querySelector("i").innerHTML="play_arrow":btnPlayPause.querySelector("i").innerHTML="pause",buttonVisible(btnPlayPause,isActive)}function updateTimeDisplay(positionTicks,runtimeTicks){var context=dlg,positionSlider=context.querySelector(".nowPlayingPositionSlider");if(positionSlider&&!positionSlider.dragging)if(runtimeTicks){var pct=positionTicks/runtimeTicks;pct*=100,positionSlider.value=pct}else positionSlider.value=0;null==positionTicks?context.querySelector(".positionTime").innerHTML="--:--":context.querySelector(".positionTime").innerHTML=datetime.getDisplayRunningTime(positionTicks),null!=runtimeTicks?context.querySelector(".runtime").innerHTML=datetime.getDisplayRunningTime(runtimeTicks):context.querySelector(".runtime").innerHTML="--:--"}function getPlaylistItems(player){return playbackManager.getPlaylist(player)}function loadPlaylist(context,player){getPlaylistItems(player).then(function(items){var html="";html+=listView.getListViewHtml({items:items,smallIcon:!0,action:"setplaylistindex",enableUserDataButtons:!1,rightButtons:[{icon:"",title:globalize.translate("ButtonRemove"),id:"remove"}],dragHandle:!0}),items.length?context.querySelector(".playlistSection").classList.remove("hide"):context.querySelector(".playlistSection").classList.add("hide");var itemsContainer=context.querySelector(".playlist");itemsContainer.innerHTML=html;var playlistItemId=playbackManager.getCurrentPlaylistItemId(player);if(playlistItemId){var img=itemsContainer.querySelector('.listItem[data-playlistItemId="'+playlistItemId+'"] .listItemImage');img&&(img.classList.remove("lazy"),img.classList.add("playlistIndexIndicatorImage"))}imageLoader.lazyChildren(itemsContainer)})}function onPlaybackStart(e,state){console.log("remotecontrol event: "+e.type);var player=this;onStateChanged.call(player,e,state)}function onRepeatModeChange(e){var player=this;updateRepeatModeDisplay(playbackManager.getRepeatMode(player))}function onPlaylistUpdate(e){var player=this;loadPlaylist(dlg,player)}function onPlaylistItemRemoved(e,info){for(var context=dlg,playlistItemIds=info.playlistItemIds,i=0,length=playlistItemIds.length;i b.name) { - return 1; - } - if (a.name < b.name) { - return -1; - } - // a must be equal to b - return 0; - }); - - $('#selectCountry', page).html(countryList.map(function (c) { - - return ''; - - }).join('')).val(info.Country || ''); - - $(page.querySelector('.txtZipCode')).trigger('change'); - - }, function () { - - Dashboard.alert({ - message: Globalize.translate('ErrorGettingTvLineups') - }); - }); - - Dashboard.hideLoadingMsg(); - } - - function submitLoginForm() { - - Dashboard.showLoadingMsg(); - - require(["cryptojs-sha1"], function () { - - var info = { - Type: 'SchedulesDirect', - Username: page.querySelector('.txtUser').value, - EnableAllTuners: true, - Password: CryptoJS.SHA1(page.querySelector('.txtPass').value).toString() - }; - - var id = providerId; - - if (id) { - info.Id = id; - } - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('LiveTv/ListingProviders', { - ValidateLogin: true - }), - data: JSON.stringify(info), - contentType: "application/json", - dataType: 'json' - - }).then(function (result) { - - Dashboard.processServerConfigurationUpdateResult(); - providerId = result.Id; - reload(); - - }, function () { - Dashboard.alert({ - message: Globalize.translate('ErrorSavingTvProvider') - }); - }); - }); - } - - function submitListingsForm() { - - var selectedListingsId = $('#selectListing', page).val(); - - if (!selectedListingsId) { - Dashboard.alert({ - message: Globalize.translate('ErrorPleaseSelectLineup') - }); - return; - } - - Dashboard.showLoadingMsg(); - - var id = providerId; - - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - var info = config.ListingProviders.filter(function (i) { - return i.Id == id; - })[0]; - - info.ZipCode = page.querySelector('.txtZipCode').value; - info.Country = $('#selectCountry', page).val(); - info.ListingsId = selectedListingsId; - info.EnableAllTuners = page.querySelector('.chkAllTuners').checked; - info.EnabledTuners = info.EnableAllTuners ? [] : $('.chkTuner', page).get().filter(function (i) { - return i.checked; - }).map(function (i) { - return i.getAttribute('data-id'); - }); - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('LiveTv/ListingProviders', { - ValidateListings: true - }), - data: JSON.stringify(info), - contentType: "application/json" - - }).then(function (result) { - - Dashboard.hideLoadingMsg(); - if (options.showConfirmation !== false) { - Dashboard.processServerConfigurationUpdateResult(); - } - Events.trigger(self, 'submitted'); - - }, function () { - Dashboard.hideLoadingMsg(); - Dashboard.alert({ - message: Globalize.translate('ErrorAddingListingsToSchedulesDirect') - }); - }); - - }); - } - - function refreshListings(value) { - - if (!value) { - $('#selectListing', page).html(''); - return; - } - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "GET", - url: ApiClient.getUrl('LiveTv/ListingProviders/Lineups', { - Id: providerId, - Location: value, - Country: $('#selectCountry', page).val() - }), - dataType: 'json' - - }).then(function (result) { - - $('#selectListing', page).html(result.map(function (o) { - - return ''; - - })); - - if (listingsId) { - $('#selectListing', page).val(listingsId); - } - - Dashboard.hideLoadingMsg(); - - }, function (result) { - - Dashboard.alert({ - message: Globalize.translate('ErrorGettingTvLineups') - }); - refreshListings(''); - Dashboard.hideLoadingMsg(); - }); - } - - function getTunerName(providerId) { - - providerId = providerId.toLowerCase(); - - switch (providerId) { - - case 'm3u': - return 'M3U Playlist'; - case 'hdhomerun': - return 'HDHomerun'; - case 'satip': - return 'DVB'; - default: - return 'Unknown'; - } - } - - function refreshTunerDevices(page, providerInfo, devices) { - - var html = ''; - - for (var i = 0, length = devices.length; i < length; i++) { - - var device = devices[i]; - - html += '
'; - - var enabledTuners = providerInfo.EnabledTuners || []; - var isChecked = providerInfo.EnableAllTuners || enabledTuners.indexOf(device.Id) != -1; - var checkedAttribute = isChecked ? ' checked' : ''; - html += ''; - - html += '
'; - html += '
'; - html += device.FriendlyName || getTunerName(device.Type); - html += '
'; - - html += '
'; - html += device.Url; - html += '
'; - html += '
'; - - html += '
'; - } - - page.querySelector('.tunerList').innerHTML = html; - } - - self.submit = function () { - page.querySelector('.btnSubmitListingsContainer').click(); - }; - - self.init = function () { - - options = options || {}; - - if (options.showCancelButton !== false) { - page.querySelector('.btnCancel').classList.remove('hide'); - } else { - page.querySelector('.btnCancel').classList.add('hide'); - } - - if (options.showSubmitButton !== false) { - page.querySelector('.btnSubmitListings').classList.remove('hide'); - } else { - page.querySelector('.btnSubmitListings').classList.add('hide'); - } - - $('.formLogin', page).on('submit', function () { - submitLoginForm(); - return false; - }); - - $('.formListings', page).on('submit', function () { - submitListingsForm(); - return false; - }); - - $('.txtZipCode', page).on('change', function () { - refreshListings(this.value); - }); - - page.querySelector('.chkAllTuners').addEventListener('change', function (e) { - if (e.target.checked) { - page.querySelector('.selectTunersSection').classList.add('hide'); - } else { - page.querySelector('.selectTunersSection').classList.remove('hide'); - } - }); - - $('.createAccountHelp', page).html(Globalize.translate('MessageCreateAccountAt', 'http://www.schedulesdirect.org')); - - reload(); - }; - } -}); \ No newline at end of file +define(["jQuery","emby-checkbox","listViewStyle","emby-input","emby-select"],function($){"use strict";return function(page,providerId,options){function reload(){Dashboard.showLoadingMsg(),ApiClient.getNamedConfiguration("livetv").then(function(config){var info=config.ListingProviders.filter(function(i){return i.Id==providerId})[0]||{};listingsId=info.ListingsId,$("#selectListing",page).val(info.ListingsId||""),page.querySelector(".txtUser").value=info.Username||"",page.querySelector(".txtPass").value="",page.querySelector(".txtZipCode").value=info.ZipCode||"",info.Username&&info.Password?page.querySelector(".listingsSection").classList.remove("hide"):page.querySelector(".listingsSection").classList.add("hide"),page.querySelector(".chkAllTuners").checked=info.EnableAllTuners,page.querySelector(".chkAllTuners").checked?page.querySelector(".selectTunersSection").classList.add("hide"):page.querySelector(".selectTunersSection").classList.remove("hide"),setCountry(info),refreshTunerDevices(page,info,config.TunerHosts)})}function setCountry(info){ApiClient.getJSON(ApiClient.getUrl("LiveTv/ListingProviders/SchedulesDirect/Countries")).then(function(result){var i,length,countryList=[];for(var region in result){var countries=result[region];if(countries.length&&"ZZZ"!==region)for(i=0,length=countries.length;ib.name?1:a.name'+c.name+""}).join("")).val(info.Country||""),$(page.querySelector(".txtZipCode")).trigger("change")},function(){Dashboard.alert({message:Globalize.translate("ErrorGettingTvLineups")})}),Dashboard.hideLoadingMsg()}function submitLoginForm(){Dashboard.showLoadingMsg(),require(["cryptojs-sha1"],function(){var info={Type:"SchedulesDirect",Username:page.querySelector(".txtUser").value,EnableAllTuners:!0,Password:CryptoJS.SHA1(page.querySelector(".txtPass").value).toString()},id=providerId;id&&(info.Id=id),ApiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/ListingProviders",{ValidateLogin:!0}),data:JSON.stringify(info),contentType:"application/json",dataType:"json"}).then(function(result){Dashboard.processServerConfigurationUpdateResult(),providerId=result.Id,reload()},function(){Dashboard.alert({message:Globalize.translate("ErrorSavingTvProvider")})})})}function submitListingsForm(){var selectedListingsId=$("#selectListing",page).val();if(!selectedListingsId)return void Dashboard.alert({message:Globalize.translate("ErrorPleaseSelectLineup")});Dashboard.showLoadingMsg();var id=providerId;ApiClient.getNamedConfiguration("livetv").then(function(config){var info=config.ListingProviders.filter(function(i){return i.Id==id})[0];info.ZipCode=page.querySelector(".txtZipCode").value,info.Country=$("#selectCountry",page).val(),info.ListingsId=selectedListingsId,info.EnableAllTuners=page.querySelector(".chkAllTuners").checked,info.EnabledTuners=info.EnableAllTuners?[]:$(".chkTuner",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-id")}),ApiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/ListingProviders",{ValidateListings:!0}),data:JSON.stringify(info),contentType:"application/json"}).then(function(result){Dashboard.hideLoadingMsg(),options.showConfirmation!==!1&&Dashboard.processServerConfigurationUpdateResult(),Events.trigger(self,"submitted")},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("ErrorAddingListingsToSchedulesDirect")})})})}function refreshListings(value){return value?(Dashboard.showLoadingMsg(),void ApiClient.ajax({type:"GET",url:ApiClient.getUrl("LiveTv/ListingProviders/Lineups",{Id:providerId,Location:value,Country:$("#selectCountry",page).val()}),dataType:"json"}).then(function(result){$("#selectListing",page).html(result.map(function(o){return'"})),listingsId&&$("#selectListing",page).val(listingsId),Dashboard.hideLoadingMsg()},function(result){Dashboard.alert({message:Globalize.translate("ErrorGettingTvLineups")}),refreshListings(""),Dashboard.hideLoadingMsg()})):void $("#selectListing",page).html("")}function getTunerName(providerId){switch(providerId=providerId.toLowerCase()){case"m3u":return"M3U Playlist";case"hdhomerun":return"HDHomerun";case"satip":return"DVB";default:return"Unknown"}}function refreshTunerDevices(page,providerInfo,devices){for(var html="",i=0,length=devices.length;i';var enabledTuners=providerInfo.EnabledTuners||[],isChecked=providerInfo.EnableAllTuners||enabledTuners.indexOf(device.Id)!=-1,checkedAttribute=isChecked?" checked":"";html+='",html+='
',html+='
',html+=device.FriendlyName||getTunerName(device.Type),html+="
",html+='
',html+=device.Url,html+="
",html+="
",html+="
"}page.querySelector(".tunerList").innerHTML=html}var listingsId,self=this;self.submit=function(){page.querySelector(".btnSubmitListingsContainer").click()},self.init=function(){options=options||{},options.showCancelButton!==!1?page.querySelector(".btnCancel").classList.remove("hide"):page.querySelector(".btnCancel").classList.add("hide"),options.showSubmitButton!==!1?page.querySelector(".btnSubmitListings").classList.remove("hide"):page.querySelector(".btnSubmitListings").classList.add("hide"),$(".formLogin",page).on("submit",function(){return submitLoginForm(),!1}),$(".formListings",page).on("submit",function(){return submitListingsForm(),!1}),$(".txtZipCode",page).on("change",function(){refreshListings(this.value)}),page.querySelector(".chkAllTuners").addEventListener("change",function(e){e.target.checked?page.querySelector(".selectTunersSection").classList.add("hide"):page.querySelector(".selectTunersSection").classList.remove("hide")}),$(".createAccountHelp",page).html(Globalize.translate("MessageCreateAccountAt",'http://www.schedulesdirect.org')),reload()}}}); \ No newline at end of file diff --git a/dashboard-ui/components/tvproviders/xmltv.js b/dashboard-ui/components/tvproviders/xmltv.js index aba03764ef..8992938821 100644 --- a/dashboard-ui/components/tvproviders/xmltv.js +++ b/dashboard-ui/components/tvproviders/xmltv.js @@ -1,232 +1 @@ -define(['jQuery', 'registrationServices', 'emby-checkbox', 'emby-input', 'listViewStyle', 'paper-icon-button-light'], function ($, registrationServices) { - 'use strict'; - - return function (page, providerId, options) { - - var self = this; - - function getListingProvider(config, id) { - - if (config && id) { - - var result = config.ListingProviders.filter(function (i) { - return i.Id == id; - })[0]; - - if (result) { - return Promise.resolve(result); - } - - return getListingProvider(); - } - - return ApiClient.getJSON(ApiClient.getUrl('LiveTv/ListingProviders/Default')); - } - - function reload() { - - Dashboard.showLoadingMsg(); - - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - getListingProvider(config, providerId).then(function (info) { - page.querySelector('.txtPath').value = info.Path || ''; - page.querySelector('.txtKids').value = (info.KidsCategories || []).join('|'); - page.querySelector('.txtNews').value = (info.NewsCategories || []).join('|'); - page.querySelector('.txtSports').value = (info.SportsCategories || []).join('|'); - page.querySelector('.txtMovies').value = (info.MovieCategories || []).join('|'); - page.querySelector('.txtMoviePrefix').value = info.MoviePrefix || ''; - - page.querySelector('.chkAllTuners').checked = info.EnableAllTuners; - - if (page.querySelector('.chkAllTuners').checked) { - page.querySelector('.selectTunersSection').classList.add('hide'); - } else { - page.querySelector('.selectTunersSection').classList.remove('hide'); - } - - refreshTunerDevices(page, info, config.TunerHosts); - Dashboard.hideLoadingMsg(); - }); - }); - } - - function getCategories(txtInput) { - - var value = txtInput.value; - - return value ? value.split('|') : []; - } - - function submitListingsForm() { - - Dashboard.showLoadingMsg(); - - var id = providerId; - - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - var info = config.ListingProviders.filter(function (i) { - return i.Id == id; - })[0] || {}; - - info.Type = 'xmltv'; - - info.Path = page.querySelector('.txtPath').value; - - info.MoviePrefix = page.querySelector('.txtMoviePrefix').value || null; - - info.MovieCategories = getCategories(page.querySelector('.txtMovies')); - info.KidsCategories = getCategories(page.querySelector('.txtKids')); - info.NewsCategories = getCategories(page.querySelector('.txtNews')); - info.SportsCategories = getCategories(page.querySelector('.txtSports')); - - info.EnableAllTuners = page.querySelector('.chkAllTuners').checked; - info.EnabledTuners = info.EnableAllTuners ? [] : $('.chkTuner', page).get().filter(function (i) { - return i.checked; - }).map(function (i) { - return i.getAttribute('data-id'); - }); - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('LiveTv/ListingProviders', { - ValidateListings: true - }), - data: JSON.stringify(info), - contentType: "application/json" - - }).then(function (result) { - - Dashboard.hideLoadingMsg(); - if (options.showConfirmation !== false) { - Dashboard.processServerConfigurationUpdateResult(); - } - Events.trigger(self, 'submitted'); - - }, function () { - Dashboard.hideLoadingMsg(); - Dashboard.alert({ - message: Globalize.translate('ErrorAddingXmlTvFile') - }); - }); - - }); - } - - function getTunerName(providerId) { - - providerId = providerId.toLowerCase(); - - switch (providerId) { - - case 'm3u': - return 'M3U Playlist'; - case 'hdhomerun': - return 'HDHomerun'; - case 'satip': - return 'DVB'; - default: - return 'Unknown'; - } - } - - function refreshTunerDevices(page, providerInfo, devices) { - - var html = ''; - - for (var i = 0, length = devices.length; i < length; i++) { - - var device = devices[i]; - - html += '
'; - - var enabledTuners = providerInfo.EnabledTuners || []; - var isChecked = providerInfo.EnableAllTuners || enabledTuners.indexOf(device.Id) != -1; - var checkedAttribute = isChecked ? ' checked' : ''; - html += ''; - - html += '
'; - html += '
'; - html += device.FriendlyName || getTunerName(device.Type); - html += '
'; - - html += '
'; - html += device.Url; - html += '
'; - html += '
'; - - html += '
'; - } - - page.querySelector('.tunerList').innerHTML = html; - } - - self.submit = function () { - page.querySelector('.btnSubmitListings').click(); - }; - - function onSelectPathClick(e) { - var page = $(e.target).parents('.xmltvForm')[0]; - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - includeFiles: true, - callback: function (path) { - - if (path) { - var txtPath = page.querySelector('.txtPath'); - txtPath.value = path; - txtPath.focus(); - } - picker.close(); - } - }); - }); - } - - self.init = function () { - - options = options || {}; - - if (options.showCancelButton !== false) { - page.querySelector('.btnCancel').classList.remove('hide'); - } else { - page.querySelector('.btnCancel').classList.add('hide'); - } - - if (options.showSubmitButton !== false) { - page.querySelector('.btnSubmitListings').classList.remove('hide'); - } else { - page.querySelector('.btnSubmitListings').classList.add('hide'); - } - - page.querySelector('.premiereHelp').innerHTML = Globalize.translate('XmlTvPremiere', 24); - - $('form', page).on('submit', function () { - submitListingsForm(); - return false; - }); - - page.querySelector('#btnSelectPath').addEventListener("click", onSelectPathClick); - - page.querySelector('.lnkPremiere').addEventListener('click', function (e) { - registrationServices.showPremiereInfo(); - e.preventDefault(); - }); - - page.querySelector('.chkAllTuners').addEventListener('change', function (e) { - if (e.target.checked) { - page.querySelector('.selectTunersSection').classList.add('hide'); - } else { - page.querySelector('.selectTunersSection').classList.remove('hide'); - } - }); - - reload(); - }; - } -}); \ No newline at end of file +define(["jQuery","registrationServices","emby-checkbox","emby-input","listViewStyle","paper-icon-button-light"],function($,registrationServices){"use strict";return function(page,providerId,options){function getListingProvider(config,id){if(config&&id){var result=config.ListingProviders.filter(function(i){return i.Id==id})[0];return result?Promise.resolve(result):getListingProvider()}return ApiClient.getJSON(ApiClient.getUrl("LiveTv/ListingProviders/Default"))}function reload(){Dashboard.showLoadingMsg(),ApiClient.getNamedConfiguration("livetv").then(function(config){getListingProvider(config,providerId).then(function(info){page.querySelector(".txtPath").value=info.Path||"",page.querySelector(".txtKids").value=(info.KidsCategories||[]).join("|"),page.querySelector(".txtNews").value=(info.NewsCategories||[]).join("|"),page.querySelector(".txtSports").value=(info.SportsCategories||[]).join("|"),page.querySelector(".txtMovies").value=(info.MovieCategories||[]).join("|"),page.querySelector(".txtMoviePrefix").value=info.MoviePrefix||"",page.querySelector(".chkAllTuners").checked=info.EnableAllTuners,page.querySelector(".chkAllTuners").checked?page.querySelector(".selectTunersSection").classList.add("hide"):page.querySelector(".selectTunersSection").classList.remove("hide"),refreshTunerDevices(page,info,config.TunerHosts),Dashboard.hideLoadingMsg()})})}function getCategories(txtInput){var value=txtInput.value;return value?value.split("|"):[]}function submitListingsForm(){Dashboard.showLoadingMsg();var id=providerId;ApiClient.getNamedConfiguration("livetv").then(function(config){var info=config.ListingProviders.filter(function(i){return i.Id==id})[0]||{};info.Type="xmltv",info.Path=page.querySelector(".txtPath").value,info.MoviePrefix=page.querySelector(".txtMoviePrefix").value||null,info.MovieCategories=getCategories(page.querySelector(".txtMovies")),info.KidsCategories=getCategories(page.querySelector(".txtKids")),info.NewsCategories=getCategories(page.querySelector(".txtNews")),info.SportsCategories=getCategories(page.querySelector(".txtSports")),info.EnableAllTuners=page.querySelector(".chkAllTuners").checked,info.EnabledTuners=info.EnableAllTuners?[]:$(".chkTuner",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-id")}),ApiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/ListingProviders",{ValidateListings:!0}),data:JSON.stringify(info),contentType:"application/json"}).then(function(result){Dashboard.hideLoadingMsg(),options.showConfirmation!==!1&&Dashboard.processServerConfigurationUpdateResult(),Events.trigger(self,"submitted")},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("ErrorAddingXmlTvFile")})})})}function getTunerName(providerId){switch(providerId=providerId.toLowerCase()){case"m3u":return"M3U Playlist";case"hdhomerun":return"HDHomerun";case"satip":return"DVB";default:return"Unknown"}}function refreshTunerDevices(page,providerInfo,devices){for(var html="",i=0,length=devices.length;i';var enabledTuners=providerInfo.EnabledTuners||[],isChecked=providerInfo.EnableAllTuners||enabledTuners.indexOf(device.Id)!=-1,checkedAttribute=isChecked?" checked":"";html+='",html+='
',html+='
',html+=device.FriendlyName||getTunerName(device.Type),html+="
",html+='
',html+=device.Url,html+="
",html+="
",html+=""}page.querySelector(".tunerList").innerHTML=html}function onSelectPathClick(e){var page=$(e.target).parents(".xmltvForm")[0];require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({includeFiles:!0,callback:function(path){if(path){var txtPath=page.querySelector(".txtPath");txtPath.value=path,txtPath.focus()}picker.close()}})})}var self=this;self.submit=function(){page.querySelector(".btnSubmitListings").click()},self.init=function(){options=options||{},options.showCancelButton!==!1?page.querySelector(".btnCancel").classList.remove("hide"):page.querySelector(".btnCancel").classList.add("hide"),options.showSubmitButton!==!1?page.querySelector(".btnSubmitListings").classList.remove("hide"):page.querySelector(".btnSubmitListings").classList.add("hide"),page.querySelector(".premiereHelp").innerHTML=Globalize.translate("XmlTvPremiere",24),$("form",page).on("submit",function(){return submitListingsForm(),!1}),page.querySelector("#btnSelectPath").addEventListener("click",onSelectPathClick),page.querySelector(".lnkPremiere").addEventListener("click",function(e){registrationServices.showPremiereInfo(),e.preventDefault()}),page.querySelector(".chkAllTuners").addEventListener("change",function(e){e.target.checked?page.querySelector(".selectTunersSection").classList.add("hide"):page.querySelector(".selectTunersSection").classList.remove("hide")}),reload()}}}); \ No newline at end of file diff --git a/dashboard-ui/components/viewcontainer-lite.js b/dashboard-ui/components/viewcontainer-lite.js index 6300519722..11362a4354 100644 --- a/dashboard-ui/components/viewcontainer-lite.js +++ b/dashboard-ui/components/viewcontainer-lite.js @@ -1,462 +1 @@ -define(['browser'], function (browser) { - 'use strict'; - - var mainAnimatedPages = document.querySelector('.mainAnimatedPages'); - var allPages = []; - var currentUrls = []; - var pageContainerCount = 3; - var selectedPageIndex = -1; - - function enableAnimation() { - - if (browser.tv) { - return false; - } - if (browser.safari) { - // Right now they don't look good. Haven't figured out why yet. - return false; - } - - return true; - } - - function loadView(options) { - - if (options.cancel) { - return; - } - - cancelActiveAnimations(); - - var selected = selectedPageIndex; - var previousAnimatable = selected == -1 ? null : allPages[selected]; - var pageIndex = selected + 1; - - if (pageIndex >= pageContainerCount) { - pageIndex = 0; - } - - var newViewInfo = normalizeNewView(options); - var newView = newViewInfo.elem; - - var dependencies = typeof (newView) == 'string' ? null : newView.getAttribute('data-require'); - dependencies = dependencies ? dependencies.split(',') : []; - - var isPluginpage = options.url.toLowerCase().indexOf('/configurationpage?') != -1; - - if (isPluginpage) { - dependencies.push('jqmpopup'); - dependencies.push('legacy/dashboard'); - dependencies.push('legacy/selectmenu'); - dependencies.push('jqmlistview'); - dependencies.push('fnchecked'); - } - - if (isPluginpage || (newView.classList && newView.classList.contains('type-interior'))) { - dependencies.push('scripts/notifications'); - dependencies.push('css!css/notifications.css'); - dependencies.push('dashboardcss'); - } - - return new Promise(function (resolve, reject) { - - require(dependencies, function () { - - var currentPage = allPages[pageIndex]; - - if (currentPage) { - triggerDestroy(currentPage); - } - - var view = newView; - - if (typeof (view) == 'string') { - view = document.createElement('div'); - view.innerHTML = newView; - } - - view.classList.add('mainAnimatedPage'); - - if (currentPage) { - if (newViewInfo.hasScript && window.$) { - // TODO: figure this out without jQuery - view = $(view).appendTo(mainAnimatedPages)[0]; - mainAnimatedPages.removeChild(currentPage); - } else { - mainAnimatedPages.replaceChild(view, currentPage); - } - } else { - if (newViewInfo.hasScript && window.$) { - // TODO: figure this out without jQuery - view = $(view).appendTo(mainAnimatedPages)[0]; - } else { - mainAnimatedPages.appendChild(view); - } - } - - if (typeof (newView) != 'string') { - enhanceNewView(dependencies, view); - } - - if (options.type) { - view.setAttribute('data-type', options.type); - } - - var properties = []; - if (options.fullscreen) { - properties.push('fullscreen'); - } - - if (properties.length) { - view.setAttribute('data-properties', properties.join(',')); - } - - var animatable = view; - allPages[pageIndex] = view; - - if (onBeforeChange) { - onBeforeChange(view, false, options); - } - - beforeAnimate(allPages, pageIndex, selected); - // animate here - animate(animatable, previousAnimatable, options.transition, options.isBack).then(function () { - - selectedPageIndex = pageIndex; - currentUrls[pageIndex] = options.url; - if (!options.cancel && previousAnimatable) { - afterAnimate(allPages, pageIndex); - } - - // Temporary hack - // If a view renders UI in viewbeforeshow the lazy image loader will think the images aren't visible and won't load images - // The views need to be updated to start loading data in beforeshow, but not render until show - document.dispatchEvent(new CustomEvent('scroll', {})); - - if (window.$) { - $.mobile = $.mobile || {}; - $.mobile.activePage = view; - } - - resolve(view); - }); - }); - }); - } - - function enhanceNewView(dependencies, newView) { - - var hasJqm = false; - - for (var i = 0, length = dependencies.length; i < length; i++) { - if (dependencies[i].indexOf('jqm') == 0) { - hasJqm = true; - break; - } - } - - if (hasJqm && window.$) { - $(newView).trigger('create'); - } - } - - function replaceAll(str, find, replace) { - - return str.split(find).join(replace); - } - - function parseHtml(html, hasScript) { - - if (hasScript) { - html = replaceAll(html, '', ''); - } - - var wrapper = document.createElement('div'); - wrapper.innerHTML = html; - return wrapper.querySelector('div[data-role="page"]'); - } - - function normalizeNewView(options) { - - if (options.view.indexOf('data-role="page"') == -1) { - return options.view; - } - - var hasScript = options.view.indexOf('=pageContainerCount&&(pageIndex=0);var newViewInfo=normalizeNewView(options),newView=newViewInfo.elem,dependencies="string"==typeof newView?null:newView.getAttribute("data-require");dependencies=dependencies?dependencies.split(","):[];var isPluginpage=options.url.toLowerCase().indexOf("/configurationpage?")!=-1;return isPluginpage&&(dependencies.push("jqmpopup"),dependencies.push("legacy/dashboard"),dependencies.push("legacy/selectmenu"),dependencies.push("jqmlistview"),dependencies.push("fnchecked")),(isPluginpage||newView.classList&&newView.classList.contains("type-interior"))&&(dependencies.push("scripts/notifications"),dependencies.push("css!css/notifications.css"),dependencies.push("dashboardcss")),new Promise(function(resolve,reject){require(dependencies,function(){var currentPage=allPages[pageIndex];currentPage&&triggerDestroy(currentPage);var view=newView;"string"==typeof view&&(view=document.createElement("div"),view.innerHTML=newView),view.classList.add("mainAnimatedPage"),currentPage?newViewInfo.hasScript&&window.$?(view=$(view).appendTo(mainAnimatedPages)[0],mainAnimatedPages.removeChild(currentPage)):mainAnimatedPages.replaceChild(view,currentPage):newViewInfo.hasScript&&window.$?view=$(view).appendTo(mainAnimatedPages)[0]:mainAnimatedPages.appendChild(view),"string"!=typeof newView&&enhanceNewView(dependencies,view),options.type&&view.setAttribute("data-type",options.type);var properties=[];options.fullscreen&&properties.push("fullscreen"),properties.length&&view.setAttribute("data-properties",properties.join(","));var animatable=view;allPages[pageIndex]=view,onBeforeChange&&onBeforeChange(view,!1,options),beforeAnimate(allPages,pageIndex,selected),animate(animatable,previousAnimatable,options.transition,options.isBack).then(function(){selectedPageIndex=pageIndex,currentUrls[pageIndex]=options.url,!options.cancel&&previousAnimatable&&afterAnimate(allPages,pageIndex),document.dispatchEvent(new CustomEvent("scroll",{})),window.$&&($.mobile=$.mobile||{},$.mobile.activePage=view),resolve(view)})})})}}function enhanceNewView(dependencies,newView){for(var hasJqm=!1,i=0,length=dependencies.length;i-->",""));var wrapper=document.createElement("div");return wrapper.innerHTML=html,wrapper.querySelector('div[data-role="page"]')}function normalizeNewView(options){if(options.view.indexOf('data-role="page"')==-1)return options.view;var hasScript=options.view.indexOf(" .table { - width: 100%; -} - -.autoorganizetable th { - padding: 0.4em; -} - -.autoorganizetable > .table > tbody > tr > td { - padding: 0.4em; -} - -.autoorganizetable .fileCell { - word-wrap: break-word; - word-break: break-all; -} - -.autoorganizetable > .table > thead > th { - text-align: left; -} - -.autoorganizetable tbody tr:nth-child(odd) td, -.autoorganizetable tbody tr:nth-child(odd) th { - background-color: #eeeeee; /* non-RGBA fallback */ - background-color: rgba(0,0,0,.04); -} - - -@media screen and (max-width: 800px) { - .autoorganizetable > .table { - margin-bottom: 0; - background-color: transparent; - } - - .autoorganizetable .spinnerCell { - display: none !important; - } - - .autoorganizetable > .table > thead, - .autoorganizetable > .table > tfoot { - display: none; - } - - .autoorganizetable > .table > tbody { - display: block; - } - - .autoorganizetable > .table > tbody > tr { - display: block; - border: 1px solid #e0e0e0; - border-radius: 2px; - margin-bottom: 1.6rem; - } - - .autoorganizetable > .table > tbody > tr > td { - background-color: #eeeeee; /* non-RGBA fallback */ - background-color: rgba(0,0,0,.04); - display: block; - vertical-align: middle; - text-align: left; - text-overflow: ellipsis; - padding: 0.4em; - } - - .autoorganizetable > .table > tbody > tr > td[data-title]:before { - content: attr(data-title); - float: left; - font-size: inherit; - font-weight: bold; - min-width: 20%; - } -} +.autoorganizetable>.table{width:100%}.autoorganizetable th,.autoorganizetable>.table>tbody>tr>td{padding:.4em}.autoorganizetable .fileCell{word-wrap:break-word;word-break:break-all}.autoorganizetable>.table>thead>th{text-align:left}.autoorganizetable tbody tr:nth-child(odd) td,.autoorganizetable tbody tr:nth-child(odd) th{background-color:#eee;background-color:rgba(0,0,0,.04)}@media screen and (max-width:800px){.autoorganizetable>.table{margin-bottom:0;background-color:transparent}.autoorganizetable .spinnerCell{display:none!important}.autoorganizetable>.table>tfoot,.autoorganizetable>.table>thead{display:none}.autoorganizetable>.table>tbody{display:block}.autoorganizetable>.table>tbody>tr{display:block;border:1px solid #e0e0e0;-webkit-border-radius:2px;border-radius:2px;margin-bottom:1.6rem}.autoorganizetable>.table>tbody>tr>td{background-color:#eee;background-color:rgba(0,0,0,.04);display:block;vertical-align:middle;text-align:left;-o-text-overflow:ellipsis;text-overflow:ellipsis;padding:.4em}.autoorganizetable>.table>tbody>tr>td[data-title]:before{content:attr(data-title);float:left;font-size:inherit;font-weight:700;min-width:20%}} \ No newline at end of file diff --git a/dashboard-ui/css/chromecast.css b/dashboard-ui/css/chromecast.css index 54a3f2f533..b2d8ba312d 100644 --- a/dashboard-ui/css/chromecast.css +++ b/dashboard-ui/css/chromecast.css @@ -1,17 +1 @@ -.btnActiveCast { - color: #52B54B !important; -} - -.headerSelectedPlayer { - font-weight: normal; - max-width: 160px; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} - -@media all and (max-width: 600px) { - .headerSelectedPlayer { - display: none; - } -} +.btnActiveCast{color:#52B54B!important}.headerSelectedPlayer{font-weight:400;max-width:160px;-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}@media all and (max-width:600px){.headerSelectedPlayer{display:none}} \ No newline at end of file diff --git a/dashboard-ui/css/dashboard.css b/dashboard-ui/css/dashboard.css index c7bfeb52b3..92ba21be09 100644 --- a/dashboard-ui/css/dashboard.css +++ b/dashboard-ui/css/dashboard.css @@ -1,578 +1 @@ -.dashboardFooter { - margin-top: 50px; - text-align: center; -} - - .dashboardFooter a { - text-decoration: none; - font-weight: normal; - margin: 0 .7em; - } - - .dashboardFooter .appLinks a { - margin: .25em; - } - - .dashboardFooter .appLinks img { - height: 16px; - } - -/* - * Gradient Shadow - */ - -/* All HTML5 progress enabled browsers */ -progress { - /* Turns off styling - not usually needed, but good to know. */ - appearance: none; - -moz-appearance: none; - -webkit-appearance: none; - /* gets rid of default border in Firefox and Opera. */ - border: solid #cccccc 2px; - border-radius: 4px; - margin: 0; -} - - /* Polyfill */ - progress[role]:after { - background-image: none; /* removes default background from polyfill */ - } - -/* - * Background of the progress bar background - */ - -/* Firefox and Polyfill */ -progress { - background: #cccccc !important; /* !important only needed in polyfill */ -} - - /* Chrome */ - progress::-webkit-progress-bar { - background: #cccccc; - } - - /* - * Background of the progress bar value - */ - - /* Firefox */ - progress::-moz-progress-bar { - border-radius: 5px; - background-image: -moz-linear-gradient( center bottom, rgb(43,194,83) 37%, rgb(84,240,84) 69% ); - } - - /* Chrome */ - progress::-webkit-progress-value { - border-radius: 5px; - background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(43,194,83)), color-stop(1, rgb(84,240,84)) ); - background-image: -webkit-linear-gradient( center bottom, rgb(43,194,83) 37%, rgb(84,240,84) 69% ); - } - - /* Polyfill */ - progress[aria-valuenow]:before { - border-radius: 5px; - background-image: -moz-linear-gradient( center bottom, rgb(43,194,83) 37%, rgb(84,240,84) 69% ); - background-image: -ms-linear-gradient( center bottom, rgb(43,194,83) 37%, rgb(84,240,84) 69% ); - background-image: -o-linear-gradient( center bottom, rgb(43,194,83) 37%, rgb(84,240,84) 69% ); - } - -/* Tabs (e.g. advanced metadata page) */ -.localnav { - margin-bottom: 30px !important; -} - -@media all and (min-width: 800px) { - - .type-interior > .ui-content, .type-interior > .ui-panel-content-wrap > .ui-content { - padding-right: 0; - padding-left: 0; - padding-top: 0; - overflow: hidden; - } -} - -.dashboardDocument .lnkMySync { - display: none !important; -} - -.dashboardDocument .dashboardEntryHeaderButton { - display: none !important; -} - -.dashboardDocument .lnkManageServer { - display: none !important; -} - -.dashboardDocument .headerVoiceButton { - display: none !important; -} - -.dashboardDocument .btnCast, .dashboardDocument .headerSelectedPlayer { - display: none !important; -} - -.adminDrawer { - background: #fff !important; -} - -.adminDrawer .sidebarLink { - color: #333 !important; -} - -.adminDrawer .sidebarHeader { - color: #666 !important; - font-weight: 500 !important; -} - -.adminDrawer .sidebarLink:hover { - color: #00897B !important; -} - -.adminDrawer .sidebarLink.selectedSidebarLink { - background: #52B54B !important; - color: #fff !important; -} - -.adminDrawerLogo { - padding: 1.5em 1em 1.2em; - border-bottom: 1px solid #e0e0e0; - margin-bottom: 1em; - display: block; -} - - .adminDrawerLogo img { - height: 30px; - } - -@media all and (max-width: 640px) { - - .dashboardDocument .headerAppsButton { - display: none; - } -} - -/* Links */ -.ui-body-a a { - color: #388E3C /*{a-link-color}*/; - font-weight: 500; -} - -div[data-role="controlgroup"] a[data-role='button'] { - display: inline-block !important; - margin: 0 !important; - -webkit-box-shadow: none !important; - -moz-box-shadow: none !important; - box-shadow: none !important; - border-radius: 0; -} - - div[data-role="controlgroup"] a[data-role='button']:first-child { - border-bottom-left-radius: .3125em; - border-top-left-radius: .3125em; - } - - div[data-role="controlgroup"] a[data-role='button']:last-child { - border-bottom-right-radius: .3125em; - border-top-right-radius: .3125em; - } - - div[data-role="controlgroup"] a[data-role='button'] + a[data-role='button'] { - border-left-width: 0 !important; - margin: 0 0 0 -3px !important; - } - -div[data-role="controlgroup"] a.ui-btn-active { - background: #38c !important; - color: #fff !important; -} - -.header .imageLink { - display: inline-block; -} - - .header .imageLink img { - height: 28px; - vertical-align: middle; - } - -.ulForm { - margin: -1em !important; - margin-bottom: 20px !important; -} - - .ulForm li:not(.ui-li-divider) { - background: none; - border: 0 !important; - } - -.popup .ulForm { - margin-bottom: 0 !important; -} - -.content-primary { - padding-top: 70px; -} - -.withTabs .content-primary { - padding-top: 115px; -} - -.mainDrawerPanel:not([narrow]) .content-primary { - padding-top: 90px; - padding-bottom: 3em; -} - -@media all and (min-width: 800px) { - - .mainDrawerPanel:not([narrow]) .content-primary { - padding-right: 1.5em; - padding-left: 1.5em; - } -} - -@media all and (min-width: 1200px) { - - .mainDrawerPanel:not([narrow]) .content-primary { - padding-left: 2em; - } -} - -.mainDrawerPanel:not([narrow]) .withTabs .content-primary { - padding-top: 125px !important; -} - -.mainDrawerPanel:not([narrow]) .content-primary ul:first-child { - margin-top: 0; -} - -@media all and (max-width: 1439px) { - - .dashboardHomeRightColumn { - margin-top: 1em; - } -} - -.dashboardContent { - margin-top: -10px; -} - -.dashboardHomeRightColumn { - vertical-align: top; -} - -@media all and (min-width: 1440px) { - - .dashboardHomeLeftColumn { - width: 600px; - display: inline-block; - vertical-align: top; - } - - .dashboardHomeRightColumn { - vertical-align: top; - } - - .firstDashboardHomeRightColumn { - display: inline-block; - width: 440px; - margin-left: 2em; - min-width: 300px; - } -} - -@media all and (min-width: 1580px) { - - .dashboardHomeRightColumn { - display: inline-block; - margin-left: 1em; - width: 300px; - min-width: 300px; - } -} - -@media all and (min-width: 1680px) { - - .dashboardHomeRightColumn { - width: 350px; - min-width: 350px; - } -} - - -@media all and (min-width: 1880px) { - - .dashboardHomeRightColumn { - max-width: 440px; - margin-left: 2em; - min-width: 440px; - } -} - -.premiumBanner img { - position: absolute; - text-align: right; - top: 0; - right: 0; - width: 60px; - height: 60px; -} - -.wizardContent { - max-width: 800px; - padding: .5em 2em 1em; - margin: 0 auto; - background: #fff; -} - -.wizardNavigation { - text-align: right; -} - -.wizardContent form { - max-width: 100%; -} - -.wizardContent h2 img { - height: 35px; - vertical-align: middle; - margin-right: .5em; - position: relative; - top: -3px; -} - -.scheduledTaskPaperIconItem { - outline: none !important; -} - -@media all and (min-width: 420px) { - - .activeSession { - width: 50% !important; - } -} - -.sessionNowPlayingContent { - background-size: cover; - background-repeat: no-repeat; - background-position: center center; - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; -} - -.sessionNowPlayingInnerContent { - background-color: rgba(0, 0, 0, .6); - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - color: #fff; - font-weight: 400; -} - -.sessionAppInfo { - padding: .5em; - overflow: hidden; -} - -.sessionAppName { - vertical-align: top; - max-width: 200px; -} - -.sessionNowPlayingInfo { - position: absolute; - left: 0; - bottom: 11px; - padding: .5em; - max-width: 150px; - overflow: hidden; - text-overflow: ellipsis; -} - -.sessionAppInfo img { - max-width: 32px; - max-height: 32px; - margin-right: 5px; -} - -.activeSession .playbackProgress { - position: absolute; - right: 0; - bottom: 0; - left: 0; - height: 7px; - width: 100%; - opacity: .95; -} - -.activeSession:not(.playingSession) .sessionNowPlayingContent { - display: none; -} - -.activeSession:not(.playingSession) .sessionNowPlayingInnerContent { - background-color: #fff; - color: #000; -} - -.activeSession:not(.playingSession) .sessionNowPlayingInfo { - bottom: 0; -} - -.sessionNowPlayingTime { - color: #fff; - position: absolute; - right: 10px; - bottom: 19px; -} - -.sessionNowPlayingStreamInfo { - white-space: nowrap; - font-size: 90%; -} - -.activeSession .transcodingProgress { - right: 0; - bottom: 0; - left: 0; - height: 5px; - width: 100%; - opacity: .9; - z-index: 999; - position: absolute; -} - -/* All HTML5 progress enabled browsers */ -.transcodingProgress, .playbackProgress { - /* Turns off styling - not usually needed, but good to know. */ - appearance: none; - -moz-appearance: none; - -webkit-appearance: none; - /* gets rid of default border in Firefox and Opera. */ - border: 0; - margin: 0; - height: 14px; - border: 0 solid #222; - border-radius: 0; - width: 50px; - margin-right: 5px; - background: #000 !important; /* !important only needed in polyfill */ -} - - /* Chrome */ - .playbackProgress::-webkit-progress-bar, .transcodingProgress::-webkit-progress-bar { - background: #000; - } - - -.transcodingSession .playbackProgress { - bottom: 5px; -} - -/* Firefox */ -.transcodingProgress::-moz-progress-bar { - border-radius: 0; - background-image: -moz-linear-gradient( center bottom, rgb(221, 73, 25) 37%, rgb(221, 73, 25) 69% ) !important; -} - -/* Chrome */ -.transcodingProgress::-webkit-progress-value { - border-radius: 0; - background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(221, 73, 25)), color-stop(1, rgb(221, 73, 25)) ) !important; - background-image: -webkit-linear-gradient( center bottom, rgb(221, 73, 25) 37%, rgb(221, 73, 25) 69% ) !important; -} - -/* Polyfill */ -.transcodingProgress[aria-valuenow]:before { - border-radius: 0; - background-image: -moz-linear-gradient( center bottom, rgb(221, 73, 25) 37%, rgb(221, 73, 25) 69% ) !important; - background-image: -ms-linear-gradient( center bottom, rgb(221, 73, 25) 37%, rgb(221, 73, 25) 69% ) !important; - background-image: -o-linear-gradient( center bottom, rgb(221, 73, 25) 37%, rgb(221, 73, 25) 69% ) !important; -} - -/* Firefox */ -.playbackProgress::-moz-progress-bar { - border-radius: 0; - background-image: none; - background-color: #52B54B; -} - -/* Chrome */ -.playbackProgress::-webkit-progress-value { - border-radius: 0; - background-image: none; - background-color: #52B54B; -} - -/* Polyfill */ -.playbackProgress[aria-valuenow]:before { - border-radius: 0; - background-image: none; - background-color: #52B54B; -} - -@media all and (max-width: 550px) { - - .sessionAppName { - max-width: 160px; - } -} - -@media all and (max-width: 500px) { - - .sessionAppName { - max-width: 150px; - } -} - -.disabledUser { - -webkit-filter: grayscale(100%); - filter: grayscale(100%); -} - -.disabledUserBanner { - margin: 0 0 2em; -} - -.appLinks a { - text-decoration: none !important; -} - - .appLinks a + a { - margin-left: 5px; - } - -.appLinks img { - height: 36px; -} - -.supporterMembershipDisabled .tabSupporterMembership { - display: none; -} - -a[data-role='button'] { - -webkit-font-smoothing: antialiased; - -webkit-user-select: none; - background-clip: padding-box; - border-radius: .3125em; - border: 1px solid #ddd !important; - color: rgb(51, 51, 51) !important; - cursor: pointer !important; - font-family: inherit !important; - font-size: inherit !important; - font-weight: 500 !important; - margin: 0 .25em !important; - display: inline-block; - padding: .8em 1em; - text-align: center; - text-decoration: none !important; - background: #f6f6f6 !important; - font-size: 16px; - -webkit-box-shadow: 0 1px 3px /*{global-box-shadow-size}*/ rgba(0,0,0,.15) /*{global-box-shadow-color}*/; - -moz-box-shadow: 0 1px 3px /*{global-box-shadow-size}*/ rgba(0,0,0,.15) /*{global-box-shadow-color}*/; - box-shadow: 0 1px 3px /*{global-box-shadow-size}*/ rgba(0,0,0,.15) /*{global-box-shadow-color}*/; -} +.dashboardFooter{margin-top:50px;text-align:center}.dashboardFooter a{text-decoration:none;font-weight:400;margin:0 .7em}.dashboardFooter .appLinks a{margin:.25em}.dashboardFooter .appLinks img{height:16px}progress{appearance:none;-moz-appearance:none;-webkit-appearance:none;border:2px solid #ccc;-webkit-border-radius:4px;border-radius:4px;margin:0;background:#ccc!important}progress[role]:after{background-image:none}progress::-webkit-progress-bar{background:#ccc}progress::-moz-progress-bar{border-radius:5px;background-image:-moz-linear-gradient(center bottom,#2bc253 37%,#54f054 69%)}progress::-webkit-progress-value{-webkit-border-radius:5px;border-radius:5px;background-image:-webkit-gradient(linear,left bottom,left top,color-stop(0,#2bc253),color-stop(1,#54f054));background-image:-webkit-linear-gradient(center bottom,#2bc253 37%,#54f054 69%)}progress[aria-valuenow]:before{-webkit-border-radius:5px;border-radius:5px;background-image:-o-linear-gradient(center bottom,#2bc253 37%,#54f054 69%)}.localnav{margin-bottom:30px!important}@media all and (min-width:800px){.type-interior>.ui-content,.type-interior>.ui-panel-content-wrap>.ui-content{padding-right:0;padding-left:0;padding-top:0;overflow:hidden}}.dashboardDocument .btnCast,.dashboardDocument .dashboardEntryHeaderButton,.dashboardDocument .headerSelectedPlayer,.dashboardDocument .headerVoiceButton,.dashboardDocument .lnkManageServer,.dashboardDocument .lnkMySync{display:none!important}.adminDrawer{background:#fff!important}.adminDrawer .sidebarLink{color:#333!important}.adminDrawer .sidebarHeader{color:#666!important;font-weight:500!important}.adminDrawer .sidebarLink:hover{color:#00897B!important}.adminDrawer .sidebarLink.selectedSidebarLink{background:#52B54B!important;color:#fff!important}.adminDrawerLogo{padding:1.5em 1em 1.2em;border-bottom:1px solid #e0e0e0;margin-bottom:1em;display:block}.adminDrawerLogo img{height:30px}@media all and (max-width:640px){.dashboardDocument .headerAppsButton{display:none}}.ui-body-a a{color:#388E3C;font-weight:500}div[data-role=controlgroup] a[data-role=button]{display:inline-block!important;margin:0!important;-webkit-box-shadow:none!important;box-shadow:none!important;-webkit-border-radius:0;border-radius:0}div[data-role=controlgroup] a[data-role=button]:first-child{-webkit-border-bottom-left-radius:.3125em;border-bottom-left-radius:.3125em;-webkit-border-top-left-radius:.3125em;border-top-left-radius:.3125em}div[data-role=controlgroup] a[data-role=button]:last-child{-webkit-border-bottom-right-radius:.3125em;border-bottom-right-radius:.3125em;-webkit-border-top-right-radius:.3125em;border-top-right-radius:.3125em}div[data-role=controlgroup] a[data-role=button]+a[data-role=button]{border-left-width:0!important;margin:0 0 0 -3px!important}div[data-role=controlgroup] a.ui-btn-active{background:#38c!important;color:#fff!important}.header .imageLink{display:inline-block}.header .imageLink img{height:28px;vertical-align:middle}.ulForm{margin:-1em -1em 20px!important}.ulForm li:not(.ui-li-divider){background:0 0;border:0!important}.popup .ulForm{margin-bottom:0!important}.content-primary{padding-top:70px}.withTabs .content-primary{padding-top:115px}.mainDrawerPanel:not([narrow]) .content-primary{padding-top:90px;padding-bottom:3em}@media all and (min-width:800px){.mainDrawerPanel:not([narrow]) .content-primary{padding-right:1.5em;padding-left:1.5em}}@media all and (min-width:1200px){.mainDrawerPanel:not([narrow]) .content-primary{padding-left:2em}}.mainDrawerPanel:not([narrow]) .withTabs .content-primary{padding-top:125px!important}.mainDrawerPanel:not([narrow]) .content-primary ul:first-child{margin-top:0}@media all and (max-width:1439px){.dashboardHomeRightColumn{margin-top:1em}}.dashboardContent{margin-top:-10px}.dashboardHomeRightColumn{vertical-align:top}@media all and (min-width:1440px){.dashboardHomeLeftColumn{width:600px;display:inline-block;vertical-align:top}.dashboardHomeRightColumn{vertical-align:top}.firstDashboardHomeRightColumn{display:inline-block;width:440px;margin-left:2em;min-width:300px}}@media all and (min-width:1580px){.dashboardHomeRightColumn{display:inline-block;margin-left:1em;width:300px;min-width:300px}}.activeSession:not(.playingSession) .sessionNowPlayingContent,.supporterMembershipDisabled .tabSupporterMembership{display:none}@media all and (min-width:1680px){.dashboardHomeRightColumn{width:350px;min-width:350px}}@media all and (min-width:1880px){.dashboardHomeRightColumn{max-width:440px;margin-left:2em;min-width:440px}}.premiumBanner img{position:absolute;text-align:right;top:0;right:0;width:60px;height:60px}.wizardContent{max-width:800px;padding:.5em 2em 1em;margin:0 auto;background:#fff}.sessionAppInfo,.sessionNowPlayingInfo{padding:.5em;overflow:hidden}.wizardNavigation{text-align:right}.wizardContent form{max-width:100%}.wizardContent h2 img{height:35px;vertical-align:middle;margin-right:.5em;position:relative;top:-3px}.scheduledTaskPaperIconItem{outline:0!important}@media all and (min-width:420px){.activeSession{width:50%!important}}.sessionNowPlayingContent{-webkit-background-size:cover;background-size:cover;background-repeat:no-repeat;background-position:center center;position:absolute;top:0;left:0;right:0;bottom:0}.sessionNowPlayingInnerContent{background-color:rgba(0,0,0,.6);position:absolute;top:0;left:0;right:0;bottom:0;color:#fff;font-weight:400}.sessionAppName{vertical-align:top;max-width:200px}.sessionNowPlayingInfo{position:absolute;left:0;bottom:11px;max-width:150px;-o-text-overflow:ellipsis;text-overflow:ellipsis}.sessionAppInfo img{max-width:32px;max-height:32px;margin-right:5px}.activeSession .playbackProgress{position:absolute;right:0;bottom:0;left:0;height:7px;width:100%;opacity:.95}.activeSession:not(.playingSession) .sessionNowPlayingInnerContent{background-color:#fff;color:#000}.activeSession:not(.playingSession) .sessionNowPlayingInfo{bottom:0}.sessionNowPlayingTime{color:#fff;position:absolute;right:10px;bottom:19px}.sessionNowPlayingStreamInfo{white-space:nowrap;font-size:90%}.activeSession .transcodingProgress{right:0;bottom:0;left:0;height:5px;width:100%;opacity:.9;z-index:999;position:absolute}.playbackProgress,.transcodingProgress{appearance:none;-moz-appearance:none;-webkit-appearance:none;margin:0 5px 0 0;height:14px;border:0 solid #222;-webkit-border-radius:0;border-radius:0;width:50px;background:#000!important}.playbackProgress::-webkit-progress-bar,.transcodingProgress::-webkit-progress-bar{background:#000}.transcodingSession .playbackProgress{bottom:5px}.transcodingProgress::-moz-progress-bar{border-radius:0;background-image:-moz-linear-gradient(center bottom,#dd4919 37%,#dd4919 69%)!important}.transcodingProgress::-webkit-progress-value{-webkit-border-radius:0;border-radius:0;background-image:-webkit-gradient(linear,left bottom,left top,color-stop(0,#dd4919),color-stop(1,#dd4919))!important;background-image:-webkit-linear-gradient(center bottom,#dd4919 37%,#dd4919 69%)!important}.transcodingProgress[aria-valuenow]:before{-webkit-border-radius:0;border-radius:0;background-image:-o-linear-gradient(center bottom,#dd4919 37%,#dd4919 69%)!important}.playbackProgress::-moz-progress-bar{border-radius:0;background-image:none;background-color:#52B54B}.playbackProgress::-webkit-progress-value{-webkit-border-radius:0;border-radius:0;background-image:none;background-color:#52B54B}.playbackProgress[aria-valuenow]:before{-webkit-border-radius:0;border-radius:0;background-image:none;background-color:#52B54B}@media all and (max-width:550px){.sessionAppName{max-width:160px}}@media all and (max-width:500px){.sessionAppName{max-width:150px}}.disabledUser{-webkit-filter:grayscale(100%);filter:grayscale(100%)}.disabledUserBanner{margin:0 0 2em}.appLinks a{text-decoration:none!important}.appLinks a+a{margin-left:5px}.appLinks img{height:36px}a[data-role=button]{-webkit-font-smoothing:antialiased;-webkit-user-select:none;-webkit-background-clip:padding-box;-webkit-border-radius:.3125em;border-radius:.3125em;border:1px solid #ddd!important;color:#333!important;cursor:pointer!important;font-family:inherit!important;font-size:inherit!important;font-weight:500!important;margin:0 .25em!important;display:inline-block;padding:.8em 1em;text-align:center;text-decoration:none!important;background:#f6f6f6!important;-webkit-box-shadow:0 1px 3px rgba(0,0,0,.15);box-shadow:0 1px 3px rgba(0,0,0,.15)} \ No newline at end of file diff --git a/dashboard-ui/css/detailtable.css b/dashboard-ui/css/detailtable.css index 5b0adec10c..3d847ffadf 100644 --- a/dashboard-ui/css/detailtable.css +++ b/dashboard-ui/css/detailtable.css @@ -1,87 +1 @@ -.detailTableContainer { - width: 100%; - text-align: center; -} - -.detailTable { - border-collapse: collapse; - border-spacing: 0; - text-align: left; - width: 100%; - margin: 0 auto; -} - -.stretchedDetailTable { - width: 100%; -} - -.detailTable a { - text-decoration: none; -} - - .detailTable a:hover { - text-decoration: underline; - } - -.detailTable td { - border-spacing: 0; - padding: 5px 5px; -} - -.detailTable th { - border-spacing: 0; - padding: 5px; - font-weight: bold; - text-align: left; - vertical-align: top; -} - -.userDataCell { - width: 130px; - text-align: right; -} - -.tabletColumn, .desktopColumn { - display: none; -} - -.detailTable .btnPlay { - margin: 0; -} - -.detailTableButtonsCell { - white-space: nowrap; -} - - .detailTableButtonsCell button { - margin-top: 0; - margin-bottom: 0; - } - - .detailTableButtonsCell button + button { - margin-left: .5em; - } - -@media all and (min-width: 600px) { - .tabletColumn { - display: table-cell; - } -} - -@media all and (min-width: 1100px) { - .desktopColumn { - display: table-cell; - } -} - -.detailTable tbody tr:nth-child(odd) td, -.detailTable tbody tr:nth-child(odd) th { - background-color: #eeeeee; /* non-RGBA fallback */ - background-color: rgba(0,0,0,.1); -} - -.stripedTable tbody tr:nth-child(odd) td, -.stripedTable tbody tr:nth-child(odd) th { - background-color: #eeeeee; /* non-RGBA fallback */ - background-color: rgba(0,0,0,.04); -} +.detailTableContainer{width:100%;text-align:center}.detailTable,.detailTable th{border-spacing:0;text-align:left}.detailTable{border-collapse:collapse;width:100%;margin:0 auto}.stretchedDetailTable{width:100%}.detailTable a{text-decoration:none}.detailTable a:hover{text-decoration:underline}.detailTable td{border-spacing:0;padding:5px}.detailTable th{padding:5px;font-weight:700;vertical-align:top}.userDataCell{width:130px;text-align:right}.desktopColumn,.tabletColumn{display:none}.detailTable .btnPlay{margin:0}.detailTableButtonsCell{white-space:nowrap}.detailTableButtonsCell button{margin-top:0;margin-bottom:0}.detailTableButtonsCell button+button{margin-left:.5em}@media all and (min-width:600px){.tabletColumn{display:table-cell}}@media all and (min-width:1100px){.desktopColumn{display:table-cell}}.detailTable tbody tr:nth-child(odd) td,.detailTable tbody tr:nth-child(odd) th{background-color:#eee;background-color:rgba(0,0,0,.1)}.stripedTable tbody tr:nth-child(odd) td,.stripedTable tbody tr:nth-child(odd) th{background-color:#eee;background-color:rgba(0,0,0,.04)} \ No newline at end of file diff --git a/dashboard-ui/css/librarybrowser.css b/dashboard-ui/css/librarybrowser.css index 6a596a5ab2..1f6fb0a508 100644 --- a/dashboard-ui/css/librarybrowser.css +++ b/dashboard-ui/css/librarybrowser.css @@ -1,815 +1 @@ -.hidingAnimatedTab { - visibility: hidden; -} - -.headerArrowImage { - height: 20px; - margin-left: .5em; -} - -.background-theme-b .backgroundContainer, .dialog.background-theme-b { - background-color: #121314; -} - - .background-theme-b .backgroundContainer.withBackdrop { - background-color: rgba(6, 6, 6, .94) !important; - background: linear-gradient(to right, rgba(0, 0, 0, .99), rgba(0, 0, 0, .94), rgba(0, 0, 0, .5)) !important; - } - -.ui-body-b { - /* Need the important tag for paper dialogs with this class */ - color: #fff !important; -} - -.pageWithAbsoluteTabs { - background-color: transparent !important; -} - -.backdropContainer { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - z-index: -1; -} - -.backdropImage { - /*-webkit-filter: blur(20px); - -moz-filter: blur(20px); - -o-filter: blur(20px); - -ms-filter: blur(20px); - filter: blur(20px);*/ -} - -.libraryPage .header { - padding-bottom: 0; -} - -.pageTabContent { - contain: style; -} - -.libraryPage > .ui-content { - padding-top: 10px; -} - -.pageWithAbsoluteTabs .pageTabContent { - padding-top: 2.6em; -} - -/*.pageWithAbsoluteTabs .pageTabContent { - padding-left: .5em !important; - padding-right: .5em !important; -}*/ - -.flexPageTabContent.is-active { - display: flex !important; -} - -@media all and (max-width: 600px) { - - .libraryPage > .ui-content { - padding-left: .5em !important; - padding-right: .5em !important; - } -} - -.listHeader { - margin: .25em 0; - padding-left: 2px; - line-height: 1.25em; - line-height: initial; -} - -@media all and (max-width: 500px) { - - .listHeader { - padding-left: 5px; - } -} - -.listHeader + button { - margin-left: 2em; -} - -.ehsContent, .ehsContent .pageTabContent { - margin: 0 auto; -} - -.homePageSection { - margin-bottom: 3.6em; -} - -.sectionHeaderButton { - vertical-align: middle; - margin: 0 0 .25em 1.5em; - position: relative; - top: 8px; -} - -.viewPanelTabs { - margin-bottom: 2em; -} - -@media all and (min-width: 800px) { - - .hiddenSectionOnNonMobile { - display: none; - } -} - -@media all and (min-width: 1200px) { - - .paddedItemsContainer { - padding: 0 .8em; - } -} - -.ehsContent:not(.fullWidth), .ehsContent .pageTabContent { - width: 98%; -} - -@media all and (min-width: 1200px) { - - .ehsContent:not(.fullWidth), .ehsContent .pageTabContent { - width: 96%; - } -} - -.homePageSection h1 { - padding-left: .55em; -} - -.homePageSection .itemsContainer { - padding-left: .7em; - padding-right: .7em; -} - -@media all and (min-width: 1200px) { - - .homePageSection h1 { - padding-left: 2.2vw; - } - - .homePageSection .itemsContainer { - padding-left: 2vw; - padding-right: 2vw; - } -} - -.detailPageContent { - border-spacing: 0; - border-collapse: collapse; -} - -.viewSettings { - margin: 0 0 .25em; - text-align: center; -} - -.listPaging { - text-align: center; -} - -.viewControls + .listTopPaging { - margin-left: .5em !important; -} - -.criticReview { - margin: 1.5em 0; - background: #222; - padding: .8em .8em .8em 55px; - border-radius: 5px; - position: relative; -} - - .criticReview:first-child { - margin-top: .5em; - } - - .criticReview img { - width: 30px; - } - -.criticRatingScore { - margin-bottom: .5em; -} - -.itemTag { - display: inline-block; - background-color: #333; - border-radius: 4px; - padding: 5px 7px; - margin: 0 5px 5px 0; - color: #fff !important; - text-decoration: none; - font-weight: normal !important; -} - -.itemOverview { - white-space: pre-wrap; -} - -a.itemTag:hover { - background-color: #2489ce; -} - -.itemLinks { - text-align: center; - padding: 0; -} - - .itemLinks p { - margin: .5em 0; - } - -.reviewerName { - color: #ccc; - margin-top: .5em; -} - -.reviewLink { - margin-top: .5em; -} - -.reviewDate { - margin-left: 1em; -} - -.reviewScore { - position: absolute; - left: .8em; -} - -span.itemCommunityRating:not(:empty) + .userDataIcons { - margin-left: 1.25em; -} - -.itemBackdrop { - background-size: cover; - background-position: center 15%; - background-repeat: no-repeat; - height: 45vh; - position: relative; -} - -.noSecondaryNavPage .itemBackdrop { - margin-top: -50px; -} - -.noBackdrop { - background: #181818; - height: 170px !important; -} - -.withBackdrop + .mainDrawerPanel .noBackdrop { - background-color: transparent; -} - -.itemBackdropContent { - position: absolute; - bottom: 0; - left: 0; - right: 0; - background-color: rgba(0,0,0,0.7); - min-height: 120px; -} - -.noBackdrop .itemBackdropContent { - background-color: transparent; -} - -.desktopMiscInfoContainer { - position: absolute; - bottom: 10px; -} - -.detailUserDataIcons { - display: flex; - align-items: center; -} - -.detailImageContainer { - margin-right: 2em; - width: 280px; - flex-shrink: 0; -} - -.detailPagePrimaryContent { - position: relative; - flex-grow: 1; -} - -.detailLogo { - width: 300px; - height: 70px; - position: absolute; - top: 13.5%; - right: 19.5%; - background-repeat: no-repeat; - background-position: center center; - background-size: contain; -} - -@media all and (max-width: 1400px) { - - .detailLogo { - right: 5%; - } -} - -@media all and (max-width: 1200px) { - - .detailLogo { - right: 2%; - } -} - -@media all and (max-width: 1100px) { - - .detailLogo { - display: none; - } -} - -.itemDetailImage { - border: solid 1px transparent; - width: 100%; -} - -.thumbDetailImageContainer { - width: 400px; -} - -.itemDetailImage.loaded { - -moz-box-shadow: 0px 0 20px #000; - -webkit-box-shadow: 0px 0 20px #000; - box-shadow: 0px 0 20px #000; - border: solid 1px #222; -} - -.itemDetailGalleryLink img:hover { - -moz-box-shadow: 0 0 20px 3px #52B54B; - -webkit-box-shadow: 0 0 20px 3px #52B54B; - box-shadow: 0 0 20px 3px #52B54B; -} - -@media all and (max-width: 800px) { - - .detailPageContent { - position: relative; - } - - .detailImageContainer { - position: absolute; - top: -90px; - left: 5%; - width: auto; - } - - .itemDetailImage { - height: 120px; - width: auto !important; - } - - .btnPlaySimple { - display: none !important; - } -} - -@media all and (min-width: 800px) { - - .itemBackdrop { - display: none; - } - - .detailPagePrimaryContainer { - display: flex; - margin-bottom: 3.6em; - } -} - -@media all and (max-width: 1200px) { - - .lnkSibling { - display: none !important; - } -} - -.parentName { - display: block; - margin-bottom: .5em; -} - -.emby-button.detailFloatingButton { - width: 56px !important; - height: 56px !important; - bottom: -28px; - position: absolute; - right: 5%; - background-color: #52B54B !important; - z-index: 1; -} - -.emby-button.btnFloatingRecord { - background-color: #cc3333 !important; -} - -@media all and (max-width: 800px) { - - .parentName { - margin-bottom: 1em; - } - - .itemBackdropContent { - min-height: 0; - } -} - -@media all and (min-width: 500px) { - - .mobileDetails { - display: none; - } -} - -@media all and (max-width: 500px) { - - .desktopDetails { - display: none !important; - } -} - -.itemName { - font-weight: normal !important; - margin: .5em 0; -} - -.empty { - margin: 0; -} - -.detailSection { - vertical-align: top; - margin-bottom: 3em; -} - -.detailCollapsibleSection:not(.hide) + .detailCollapsibleSection { - margin-top: -2em; -} - -.detailPageCollabsible { - margin-top: 0; -} - -.detailSection h1 { - margin-bottom: .25em; - position: relative; -} - -.detailSectionHeader { - background-clip: border-box; - padding: 0 0 .25em .25em; - background-color: transparent; - border-radius: 0; - margin-bottom: .5em; - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; - position: relative; - margin: 1.5em 0 1em; - display: flex; - align-items: center; -} - - .detailSectionHeader > h1 { - margin: 0; - } - -.detailSectionHeaderButton { - margin-left: 1em; -} - -.mainDetailButtons { - padding: .5em 0; - display: flex; - align-items: center; - flex-wrap: wrap; -} - - .mainDetailButtons button, .recordingFields button { - margin-left: 0; - margin-right: .5em; - flex-shrink: 0; - } - - .mainDetailButtons.hide + .recordingFields { - margin-top: 1.5em !important; - } - - .mainDetailButtons > .raised { - justify-content: center; - } - -@media all and (min-width: 400px) { - - .mainDetailButtons > .raised { - padding-left: 1.5em; - padding-right: 1.5em; - } -} - -.detailImageProgressContainer { - position: absolute; - bottom: 4px; - right: 1px; - left: 1px; - text-align: center; -} - -.viewControls, .listTopPaging { - display: inline-block; -} - -@media all and (max-width: 800px) { - - .editorMenuLink { - display: none; - } -} - -.itemMiscInfo { - text-overflow: ellipsis; - overflow: hidden; - display: flex; - flex-wrap: wrap; - align-items: center; -} - -@media all and (max-width: 500px) { - - .mobileDetails .itemMiscInfo { - text-align: center; - justify-content: center; - } - - .itemMiscInfo .endsAt { - display: none; - } -} - -.detailPageContent { - padding: 3em 3% 0; -} - -@media all and (min-width: 750px) { - .detailPageContent { - padding: 3em 3% 0; - } -} - -@media all and (min-width: 1200px) { - .detailPageContent { - padding: 3em 5% 0; - } -} - -.detailPageParentLink { - font-weight: inherit !important; -} - -.mediaInfoContent { - line-height: 1.5em; -} - -.mediaInfoStream { - margin: 1em 3em 1em 0; - display: inline-block; - color: #bbb; - vertical-align: top; -} - -.mediaInfoStreamType { - display: block; - color: #fff; - margin-bottom: 1em; -} - -.mediaInfoAttribute { - color: #fff; - display: inline-block; -} - -.mediaInfoLabel { - color: #aaa; - margin-right: 1em; - display: inline-block; -} - -.posterRibbon { - display: block; - position: absolute; - top: 5px; - right: 5px; - text-align: center; - padding: 5px 6px; - border-radius: 10px; - color: #fff; - background: rgb(0, 143, 187); - background: rgba(0, 143, 187, .8); - line-height: initial; -} - -.offlinePosterRibbon { - background: rgba(248, 58, 34, .8); -} - -.unairedPosterRibbon { - background: rgba(255, 106, 0, .8); -} - -.missingPosterRibbon { - background: rgba(248, 58, 34, .8); -} - -.recordingProgressBar::-moz-progress-bar { - background-color: #cc3333; -} - -.recordingProgressBar::-webkit-progress-value { - background-color: #cc3333; -} - -.recordingProgressBar[aria-valuenow]:before { - background-color: #cc3333; -} - -.timelineHeader { - margin-bottom: .25em; - line-height: 1.25em; - line-height: initial; -} - -.itemsContainer { - margin: 0 auto; -} - -.alphabetPicker { - position: fixed; - right: 0; - bottom: 0; - text-align: center; - font-size: 90%; - display: none; - line-height: 1; -} - -.layout-desktop .absolutePageTabContent .alphabetPicker { - right: 20px; -} - -@media all and (max-height: 500px) { - - .alphabetPicker { - display: none !important; - } -} - -@media all and (min-height: 500px) { - - .itemsContainerWithAlphaPicker { - margin-right: 20px; - } - - .absolutePageTabContent .itemsContainerWithAlphaPicker { - margin-right: 30px; - } -} - -@media all and (min-height: 500px) { - - .alphabetPicker { - bottom: 5px; - } -} - -@media all and (min-width: 1200px) { - - .itemsContainerWithAlphaPicker, .absolutePageTabContent .itemsContainerWithAlphaPicker { - margin-right: 0; - } -} - -@media all and (max-height: 700px) { - - .alphaPicker-vertical .alphaPickerButton { - padding-top: 1px !important; - padding-bottom: 1px !important; - } -} - -@media all and (max-height: 600px) { - - .alphaPicker-vertical .alphaPickerButton { - padding-top: 0 !important; - padding-bottom: 0 !important; - } -} - -@media all and (max-height: 530px) { - - .alphabetPicker { - font-size: 80%; - } -} - -@media all and (max-height: 480px) { - - .alphabetPicker { - font-size: 76%; - } -} - -@media all and (min-height: 900px) { - - .alphabetPicker { - bottom: 120px; - } -} - -@media all and (min-height: 1000px) { - - .alphabetPicker { - bottom: 200px; - } -} - -@media all and (max-width: 1200px) { - - .listViewUserDataButtons { - display: none !important; - } -} - -.userProfileSettingsForm { - max-width: 700px; -} - -@media all and (max-width: 700px) { - - .userProfileSettingsForm .detailSection { - margin-left: .5em; - margin-right: .5em; - } -} - -@media all and (max-width: 800px) { - - .detailsHiddenOnMobile { - display: none; - } -} - -#criticReviewsContent.hiddenScrollX { - white-space: nowrap; -} - - #criticReviewsContent.hiddenScrollX .paperList { - min-width: 240px; - width: 90%; - max-width: 500px; - display: inline-block; - vertical-align: top; - margin: 0 4px 0 0; - } - -.btnSyncComplete { - background: #673AB7 !important; -} - - .btnSyncComplete i { - border-radius: 1000px; - } - -.bulletSeparator { - margin: 0 .35em; -} - -.mediaInfoIcons { - display: flex; - align-items: center; - margin: 1.5em 0 1em; - flex-wrap: wrap; -} - -.mediaInfoText { - padding: .3em .5em !important; - margin-right: .5em; - margin-bottom: .5em; - font-size: 94% !important; -} - -.mediaInfoText-upper { - text-transform: uppercase; -} +.itemTag,.ui-body-b{color:#fff!important}.itemName,.itemTag{font-weight:400!important}.detailSectionHeader,.itemMiscInfo{-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden}.alphabetPicker,.itemLinks,.listPaging,.posterRibbon,.viewSettings{text-align:center}.hidingAnimatedTab{visibility:hidden}.headerArrowImage{height:20px;margin-left:.5em}.background-theme-b .backgroundContainer,.dialog.background-theme-b{background-color:#121314}.background-theme-b .backgroundContainer.withBackdrop{background-color:rgba(6,6,6,.94)!important;background:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.99)),color-stop(rgba(0,0,0,.94)),to(rgba(0,0,0,.5)))!important;background:-webkit-linear-gradient(left,rgba(0,0,0,.99),rgba(0,0,0,.94),rgba(0,0,0,.5))!important;background:-o-linear-gradient(left,rgba(0,0,0,.99),rgba(0,0,0,.94),rgba(0,0,0,.5))!important;background:linear-gradient(to right,rgba(0,0,0,.99),rgba(0,0,0,.94),rgba(0,0,0,.5))!important}.pageWithAbsoluteTabs{background-color:transparent!important}.backdropContainer{position:fixed;top:0;left:0;right:0;bottom:0;z-index:-1}.libraryPage .header{padding-bottom:0}.pageTabContent{contain:style}.libraryPage>.ui-content{padding-top:10px}.pageWithAbsoluteTabs .pageTabContent{padding-top:2.6em}.flexPageTabContent.is-active{display:-webkit-box!important;display:-webkit-flex!important;display:flex!important}@media all and (max-width:600px){.libraryPage>.ui-content{padding-left:.5em!important;padding-right:.5em!important}}.listHeader{margin:.25em 0;padding-left:2px;line-height:1.25em;line-height:initial}@media all and (max-width:500px){.listHeader{padding-left:5px}}.listHeader+button{margin-left:2em}.ehsContent,.ehsContent .pageTabContent{margin:0 auto}.homePageSection{margin-bottom:3.6em}.sectionHeaderButton{vertical-align:middle;margin:0 0 .25em 1.5em;position:relative;top:8px}.viewPanelTabs{margin-bottom:2em}@media all and (min-width:800px){.hiddenSectionOnNonMobile{display:none}}.ehsContent .pageTabContent,.ehsContent:not(.fullWidth){width:98%}@media all and (min-width:1200px){.paddedItemsContainer{padding:0 .8em}.ehsContent .pageTabContent,.ehsContent:not(.fullWidth){width:96%}}.homePageSection h1{padding-left:.55em}.homePageSection .itemsContainer{padding-left:.7em;padding-right:.7em}@media all and (min-width:1200px){.homePageSection h1{padding-left:2.2vw}.homePageSection .itemsContainer{padding-left:2vw;padding-right:2vw}}.viewSettings{margin:0 0 .25em}.viewControls+.listTopPaging{margin-left:.5em!important}.criticReview{margin:1.5em 0;background:#222;padding:.8em .8em .8em 55px;-webkit-border-radius:5px;border-radius:5px;position:relative}.criticReview:first-child{margin-top:.5em}.criticReview img{width:30px}.criticRatingScore{margin-bottom:.5em}.itemTag{display:inline-block;background-color:#333;-webkit-border-radius:4px;border-radius:4px;padding:5px 7px;margin:0 5px 5px 0;text-decoration:none}.detailSectionHeader,.detailUserDataIcons{display:-webkit-box;display:-webkit-flex;-webkit-box-align:center}.itemOverview{white-space:pre-wrap}a.itemTag:hover{background-color:#2489ce}.itemLinks{padding:0}.itemLinks p{margin:.5em 0}.reviewLink,.reviewerName{margin-top:.5em}.reviewerName{color:#ccc}.reviewDate{margin-left:1em}.reviewScore{position:absolute;left:.8em}span.itemCommunityRating:not(:empty)+.userDataIcons{margin-left:1.25em}.itemBackdrop{-webkit-background-size:cover;background-size:cover;background-position:center 15%;background-repeat:no-repeat;height:45vh;position:relative}.noSecondaryNavPage .itemBackdrop{margin-top:-50px}.noBackdrop{background:#181818;height:170px!important}.withBackdrop+.mainDrawerPanel .noBackdrop{background-color:transparent}.itemBackdropContent{position:absolute;bottom:0;left:0;right:0;background-color:rgba(0,0,0,.7);min-height:120px}.noBackdrop .itemBackdropContent{background-color:transparent}.desktopMiscInfoContainer{position:absolute;bottom:10px}.detailUserDataIcons{display:flex;-webkit-align-items:center;align-items:center}.detailImageContainer{margin-right:2em;width:280px;-webkit-flex-shrink:0;flex-shrink:0}.detailPagePrimaryContent{position:relative;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1}.detailLogo{width:300px;height:70px;position:absolute;top:13.5%;right:19.5%;background-repeat:no-repeat;background-position:center center;-webkit-background-size:contain;background-size:contain}@media all and (max-width:1400px){.detailLogo{right:5%}}@media all and (max-width:1100px){.detailLogo{display:none}}.itemDetailImage{border:1px solid transparent;width:100%}.thumbDetailImageContainer{width:400px}.itemDetailImage.loaded{-webkit-box-shadow:0 0 20px #000;box-shadow:0 0 20px #000;border:1px solid #222}.itemDetailGalleryLink img:hover{-webkit-box-shadow:0 0 20px 3px #52B54B;box-shadow:0 0 20px 3px #52B54B}@media all and (max-width:800px){.detailPageContent{position:relative}.detailImageContainer{position:absolute;top:-90px;left:5%;width:auto}.itemDetailImage{height:120px;width:auto!important}.btnPlaySimple{display:none!important}}@media all and (min-width:800px){.itemBackdrop{display:none}.detailPagePrimaryContainer{display:-webkit-box;display:-webkit-flex;display:flex;margin-bottom:3.6em}}@media all and (max-width:1200px){.detailLogo{right:2%}.lnkSibling{display:none!important}}.parentName{display:block;margin-bottom:.5em}.emby-button.detailFloatingButton{width:56px!important;height:56px!important;bottom:-28px;position:absolute;right:5%;background-color:#52B54B!important;z-index:1}.emby-button.btnFloatingRecord{background-color:#c33!important}@media all and (max-width:800px){.parentName{margin-bottom:1em}.itemBackdropContent{min-height:0}}@media all and (min-width:500px){.mobileDetails{display:none}}@media all and (max-width:500px){.desktopDetails{display:none!important}}.itemName{margin:.5em 0}.empty{margin:0}.detailSection{vertical-align:top;margin-bottom:3em}.detailCollapsibleSection:not(.hide)+.detailCollapsibleSection{margin-top:-2em}.detailPageCollabsible{margin-top:0}.detailSection h1{margin-bottom:.25em;position:relative}.detailSectionHeader{-webkit-background-clip:border-box;background-clip:border-box;padding:0 0 .25em .25em;background-color:transparent;-webkit-border-radius:0;border-radius:0;white-space:nowrap;position:relative;margin:1.5em 0 1em;display:flex;-webkit-align-items:center;align-items:center}.detailSectionHeader>h1{margin:0}.detailSectionHeaderButton{margin-left:1em}.mainDetailButtons{padding:.5em 0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-flex-wrap:wrap;flex-wrap:wrap}.mainDetailButtons button,.recordingFields button{margin-left:0;margin-right:.5em;-webkit-flex-shrink:0;flex-shrink:0}.mainDetailButtons.hide+.recordingFields{margin-top:1.5em!important}.mainDetailButtons>.raised{-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}@media all and (min-width:400px){.mainDetailButtons>.raised{padding-left:1.5em;padding-right:1.5em}}.detailImageProgressContainer{position:absolute;bottom:4px;right:1px;left:1px;text-align:center}.listTopPaging,.viewControls{display:inline-block}@media all and (max-width:800px){.editorMenuLink{display:none}}.itemMiscInfo{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-webkit-align-items:center;align-items:center}@media all and (max-width:500px){.mobileDetails .itemMiscInfo{text-align:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.itemMiscInfo .endsAt{display:none}}.detailPageContent{border-spacing:0;border-collapse:collapse;padding:3em 3% 0}@media all and (min-width:750px){.detailPageContent{padding:3em 3% 0}}@media all and (min-width:1200px){.detailPageContent{padding:3em 5% 0}}.detailPageParentLink{font-weight:inherit!important}.mediaInfoContent{line-height:1.5em}.mediaInfoStream{margin:1em 3em 1em 0;display:inline-block;color:#bbb;vertical-align:top}.mediaInfoStreamType{display:block;color:#fff;margin-bottom:1em}.mediaInfoAttribute{color:#fff;display:inline-block}.mediaInfoLabel{color:#aaa;margin-right:1em;display:inline-block}.posterRibbon{display:block;position:absolute;top:5px;right:5px;padding:5px 6px;-webkit-border-radius:10px;border-radius:10px;color:#fff;background:#008fbb;background:rgba(0,143,187,.8);line-height:initial}.offlinePosterRibbon{background:rgba(248,58,34,.8)}.unairedPosterRibbon{background:rgba(255,106,0,.8)}.missingPosterRibbon{background:rgba(248,58,34,.8)}.recordingProgressBar::-moz-progress-bar{background-color:#c33}.recordingProgressBar::-webkit-progress-value{background-color:#c33}.recordingProgressBar[aria-valuenow]:before{background-color:#c33}.timelineHeader{margin-bottom:.25em;line-height:1.25em;line-height:initial}.itemsContainer{margin:0 auto}.alphabetPicker{position:fixed;right:0;bottom:0;font-size:90%;display:none;line-height:1}.layout-desktop .absolutePageTabContent .alphabetPicker{right:20px}@media all and (max-height:500px){.alphabetPicker{display:none!important}}@media all and (min-height:500px){.itemsContainerWithAlphaPicker{margin-right:20px}.absolutePageTabContent .itemsContainerWithAlphaPicker{margin-right:30px}.alphabetPicker{bottom:5px}}@media all and (min-width:1200px){.absolutePageTabContent .itemsContainerWithAlphaPicker,.itemsContainerWithAlphaPicker{margin-right:0}}@media all and (max-height:700px){.alphaPicker-vertical .alphaPickerButton{padding-top:1px!important;padding-bottom:1px!important}}@media all and (max-height:600px){.alphaPicker-vertical .alphaPickerButton{padding-top:0!important;padding-bottom:0!important}}@media all and (max-height:530px){.alphabetPicker{font-size:80%}}@media all and (max-height:480px){.alphabetPicker{font-size:76%}}@media all and (min-height:900px){.alphabetPicker{bottom:120px}}@media all and (min-height:1000px){.alphabetPicker{bottom:200px}}@media all and (max-width:1200px){.listViewUserDataButtons{display:none!important}}.userProfileSettingsForm{max-width:700px}@media all and (max-width:700px){.userProfileSettingsForm .detailSection{margin-left:.5em;margin-right:.5em}}@media all and (max-width:800px){.detailsHiddenOnMobile{display:none}}#criticReviewsContent.hiddenScrollX{white-space:nowrap}#criticReviewsContent.hiddenScrollX .paperList{min-width:240px;width:90%;max-width:500px;display:inline-block;vertical-align:top;margin:0 4px 0 0}.btnSyncComplete{background:#673AB7!important}.btnSyncComplete i{-webkit-border-radius:1000px;border-radius:1000px}.bulletSeparator{margin:0 .35em}.mediaInfoIcons{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin:1.5em 0 1em;-webkit-flex-wrap:wrap;flex-wrap:wrap}.mediaInfoText{padding:.3em .5em!important;margin-right:.5em;margin-bottom:.5em;font-size:94%!important}.mediaInfoText-upper{text-transform:uppercase} \ No newline at end of file diff --git a/dashboard-ui/css/librarymenu.css b/dashboard-ui/css/librarymenu.css index 05e5bfeb92..5f4dfc3cd6 100644 --- a/dashboard-ui/css/librarymenu.css +++ b/dashboard-ui/css/librarymenu.css @@ -1,341 +1 @@ -.libraryPage { - padding-top: 50px !important; -} - - .libraryPage:not(.noSecondaryNavPage) { - padding-top: 95px !important; - } - -.pageWithAbsoluteTabs:not(.noSecondaryNavPage) { - padding-top: 98px !important; -} - -.absolutePageTabContent { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - /* If this is raised, make sure it does not overlap bottom footer */ - z-index: 1; - margin: 0 !important; - /* Page needs to supply padding */ - top: 102px !important; - transition: transform 200ms ease-out; -} - - .absolutePageTabContent.headroomUnpinned { - transform: translateY(-92px); - bottom: -92px !important; - } - -.pageTabContent:not(.is-active) { - display: none !important; -} - -.sidebarDivider { - height: 1px; - background: #eaeaea; - margin: .5em 0; -} - -.headerUserImage { - background-size: contain; - background-repeat: no-repeat; - background-position: center center; - border-radius: 1000px; - vertical-align: middle; - display: inline-block; -} - -.headerUserButtonRound img { - border-radius: 1000px; -} - -.viewMenuBar paper-icon-button { - vertical-align: middle; -} - -.headerButton { - flex-shrink: 0; -} - -.menuArrow { - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAbklEQ…yGDxkLaBtENI9kPMk0gaoW0Dyj0aWowFLYNYzWB6MWMAAAq1H3+Mhu2hQAAAAASUVORK5CYII=); - height: 24px; - width: 24px; - display: inline-block; -} - -.hideMainDrawer .mainDrawerButton { - display: none; -} - -.libraryMenuButtonText { - text-decoration: none; - display: inline-flex; - vertical-align: middle; - padding-left: 0 !important; - cursor: default; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - align-items: center; - margin: 0 0 0 .5em; - /* Avoid pushing right header off the screen */ - flex-shrink: 1; -} - -.viewMenuBar { - position: fixed; - right: 0; - left: 0; - z-index: 999; - top: 0; - border: 0; - height: 50px; - display: flex; - flex-direction: column; -} - -.hiddenViewMenuBar .viewMenuBar { - display: none; -} - -.libraryViewNav { - overflow: hidden; - z-index: 999; - text-align: center; - text-transform: uppercase; - white-space: nowrap; - padding: 0 0 0; - display: flex; - display: block; - text-align: center; - margin: 0 auto; - align-items: center; - font-size: 13px; -} - -.ui-body-b .libraryViewNav { - position: fixed; - right: 0; - left: 0; - top: 50px; -} - -.libraryViewNav.bottom { - top: auto !important; - bottom: 0; -} - -.viewMenuBar, .ui-body-b .libraryViewNav { - background-color: #222326; - color: #fff; -} - - .viewMenuBar .primaryIcons { - display: flex; - flex-grow: 1; - width: 100%; - align-items: center; - } - -.dashboardDocument { - font-size: 13px; -} - - .dashboardDocument .viewMenuBar { - height: auto; - } - - .dashboardDocument .viewMenuBar .primaryIcons { - padding: .7em 0; - } - - .dashboardDocument.withTallToolbar .primaryIcons { - padding-bottom: 0; - } - -.viewMenuBarTabs { - width: 100%; -} - - .viewMenuBarTabs .paperTabLink { - padding-left: 1.5em; - padding-right: 1.5em; - } - -.viewMenuBar.semiTransparent { - background-color: rgba(15, 15, 15, .3); -} - -.viewMenuLink { - text-decoration: none; - color: #eee !important; - padding: 7px .5em 6px; - display: inline-block; - vertical-align: middle; -} - - .viewMenuLink:hover { - color: #fff; - } - - .viewMenuLink:hover img { - opacity: .5; - } - - .viewMenuLink img { - height: 24px; - vertical-align: top; - } - -.viewMenuSecondary { - margin-left: auto; - display: flex; - align-items: center; -} - -.selectedMediaFolder { - background-color: #f2f2f2 !important; -} - -.ui-panel.ui-body-b { - background-color: #1D1D20; -} - -@media all and (max-width: 800px) { - - /* The sidebar isn't visible at this size, so there's no way to navigate within the editor */ - .editorViewMenu { - display: none; - } -} - -.sidebarLink { - display: block; - text-decoration: none; - color: #111 !important; - font-weight: normal !important; - vertical-align: middle; - padding: 1em 0 1em 2.4em; -} - - .sidebarLink:hover { - background: #f2f2f2; - } - - .sidebarLink.selectedSidebarLink { - background: #f2f2f2 !important; - } - -.sidebarHeader { - padding-left: 1.4em; - margin: 1.2em 0 .7em; - color: #666; -} - -body:not(.dashboardDocument) .btnNotifications { - display: none !important; -} - -.darkDrawer { - background-color: #1C1C1F !important; - /*background-color: rgba(40,40,40,.8) !important; - -webkit-backdrop-filter: blur(5px); - backdrop-filter: blur(5px);*/ -} - - .darkDrawer .sidebarLinkText, .darkDrawer .sidebarLink { - color: #fff !important; - } - - .darkDrawer .sidebarHeader { - color: #bbb !important; - } - - .darkDrawer .sidebarDivider { - background: #262626 !important; - } - - .darkDrawer .sidebarLink:hover { - background: #252528; - } - - .darkDrawer .sidebarLink.selectedSidebarLink, .darkDrawer .selectedMediaFolder { - background: #252528 !important; - color: #52B54B !important; - } - -body:not(.dashboardDocument) .headerAppsButton { - display: none; -} - -.mainDrawer-scrollContainer { - padding-bottom: 10vh; -} - -.dashboardDocument .mainDrawerPanelContent { - transition: left ease-in-out 0.3s, padding ease-in-out 0.3s; - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; -} - -@media all and (min-width: 640px) { - - .mainDrawerPanel .viewMenuBarTabs { - width: auto; - padding-left: 272px; - } - - .viewMenuBarTabs .libraryViewNav { - text-align: left !important; - } - - .dashboardDocument .sidebarLink { - padding: .7em 0 .7em 2.4em; - } - - .dashboardDocument .mainDrawer { - z-index: inherit !important; - left: 0 !important; - top: 0 !important; - transform: none !important; - } - - .dashboardDocument .mainDrawer-scrollContainer { - margin-top: 50px !important; - } - - .dashboardDocument.withTallToolbar .mainDrawer-scrollContainer { - margin-top: 98px !important; - } - - .dashboardDocument .tmla-mask { - display: none !important; - } - - .dashboardDocument .mainDrawerButton { - display: none !important; - } - - .dashboardDocument .mainDrawerPanelContent { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 260px; - } - - .dashboardDocument .adminDrawerLogo { - display: none !important; - } - - .dashboardDocument .darkDrawer { - background-color: rgba(28,28,31,.3) !important; - } -} +.headerUserImage,.viewMenuBar paper-icon-button,.viewMenuLink{vertical-align:middle}.libraryPage{padding-top:50px!important}.libraryPage:not(.noSecondaryNavPage){padding-top:95px!important}.pageWithAbsoluteTabs:not(.noSecondaryNavPage){padding-top:98px!important}.absolutePageTabContent{position:absolute;left:0;right:0;bottom:0;z-index:1;margin:0!important;top:102px!important;-webkit-transition:-webkit-transform .2s ease-out;-o-transition:transform .2s ease-out;transition:transform .2s ease-out}.absolutePageTabContent.headroomUnpinned{-webkit-transform:translateY(-92px);transform:translateY(-92px);bottom:-92px!important}.pageTabContent:not(.is-active){display:none!important}.sidebarDivider{height:1px;background:#eaeaea;margin:.5em 0}.headerUserImage{-webkit-background-size:contain;background-size:contain;background-repeat:no-repeat;background-position:center center;-webkit-border-radius:1000px;border-radius:1000px;display:inline-block}.headerUserButtonRound img{-webkit-border-radius:1000px;border-radius:1000px}.headerButton{-webkit-flex-shrink:0;flex-shrink:0}.menuArrow{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAbklEQ…yGDxkLaBtENI9kPMk0gaoW0Dyj0aWowFLYNYzWB6MWMAAAq1H3+Mhu2hQAAAAASUVORK5CYII=);height:24px;width:24px;display:inline-block}.hideMainDrawer .mainDrawerButton{display:none}.libraryMenuButtonText{text-decoration:none;display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;vertical-align:middle;padding-left:0!important;cursor:default;white-space:nowrap;overflow:hidden;-o-text-overflow:ellipsis;text-overflow:ellipsis;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin:0 0 0 .5em;-webkit-flex-shrink:1;flex-shrink:1}.libraryViewNav,.viewMenuBar{z-index:999;display:-webkit-box;display:-webkit-flex}.viewMenuBar{position:fixed;right:0;left:0;top:0;border:0;height:50px;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column}.hiddenViewMenuBar .viewMenuBar{display:none}.libraryViewNav{overflow:hidden;text-transform:uppercase;white-space:nowrap;padding:0;display:flex;display:block;text-align:center;margin:0 auto;-webkit-box-align:center;-webkit-align-items:center;align-items:center;font-size:13px}.ui-body-b .libraryViewNav{position:fixed;right:0;left:0;top:50px}.libraryViewNav.bottom{top:auto!important;bottom:0}.ui-body-b .libraryViewNav,.viewMenuBar{background-color:#222326;color:#fff}.viewMenuBar .primaryIcons{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;width:100%;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.dashboardDocument{font-size:13px}.dashboardDocument .viewMenuBar{height:auto}.dashboardDocument .viewMenuBar .primaryIcons{padding:.7em 0}.dashboardDocument.withTallToolbar .primaryIcons{padding-bottom:0}.viewMenuBarTabs{width:100%}.viewMenuBarTabs .paperTabLink{padding-left:1.5em;padding-right:1.5em}.viewMenuBar.semiTransparent{background-color:rgba(15,15,15,.3)}.viewMenuLink{text-decoration:none;color:#eee!important;padding:7px .5em 6px;display:inline-block}.viewMenuLink:hover{color:#fff}.viewMenuLink:hover img{opacity:.5}.viewMenuLink img{height:24px;vertical-align:top}.viewMenuSecondary{margin-left:auto;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.selectedMediaFolder{background-color:#f2f2f2!important}.ui-panel.ui-body-b{background-color:#1D1D20}@media all and (max-width:800px){.editorViewMenu{display:none}}.sidebarLink{display:block;text-decoration:none;color:#111!important;font-weight:400!important;vertical-align:middle;padding:1em 0 1em 2.4em}.sidebarLink:hover{background:#f2f2f2}.sidebarLink.selectedSidebarLink{background:#f2f2f2!important}.sidebarHeader{padding-left:1.4em;margin:1.2em 0 .7em;color:#666}body:not(.dashboardDocument) .btnNotifications{display:none!important}.darkDrawer{background-color:#1C1C1F!important}.darkDrawer .sidebarLink,.darkDrawer .sidebarLinkText{color:#fff!important}.darkDrawer .sidebarHeader{color:#bbb!important}.darkDrawer .sidebarDivider{background:#262626!important}.darkDrawer .sidebarLink:hover{background:#252528}.darkDrawer .selectedMediaFolder,.darkDrawer .sidebarLink.selectedSidebarLink{background:#252528!important;color:#52B54B!important}body:not(.dashboardDocument) .headerAppsButton{display:none}.mainDrawer-scrollContainer{padding-bottom:10vh}.dashboardDocument .mainDrawerPanelContent{-webkit-transition:left ease-in-out .3s,padding ease-in-out .3s;-o-transition:left ease-in-out .3s,padding ease-in-out .3s;transition:left ease-in-out .3s,padding ease-in-out .3s;position:absolute;top:0;right:0;bottom:0;left:0}@media all and (min-width:640px){.dashboardDocument .adminDrawerLogo,.dashboardDocument .mainDrawerButton,.dashboardDocument .tmla-mask{display:none!important}.mainDrawerPanel .viewMenuBarTabs{width:auto;padding-left:272px}.viewMenuBarTabs .libraryViewNav{text-align:left!important}.dashboardDocument .sidebarLink{padding:.7em 0 .7em 2.4em}.dashboardDocument .mainDrawer{z-index:inherit!important;left:0!important;top:0!important;-webkit-transform:none!important;transform:none!important}.dashboardDocument .mainDrawer-scrollContainer{margin-top:50px!important}.dashboardDocument.withTallToolbar .mainDrawer-scrollContainer{margin-top:98px!important}.dashboardDocument .mainDrawerPanelContent{position:absolute;top:0;right:0;bottom:0;left:260px}.dashboardDocument .darkDrawer{background-color:rgba(28,28,31,.3)!important}} \ No newline at end of file diff --git a/dashboard-ui/css/livetv.css b/dashboard-ui/css/livetv.css index 56f8d61187..d35cb6d4bd 100644 --- a/dashboard-ui/css/livetv.css +++ b/dashboard-ui/css/livetv.css @@ -1,9 +1 @@ -/* Allow vertical space for anything that slides up at the bottom */ -.guideVerticalScroller { - padding-bottom: 160px; -} - -.tvGuideHeader.headroom--unpinned { - -webkit-transform: none; - transform: none; -} +.guideVerticalScroller{padding-bottom:160px}.tvGuideHeader.headroom--unpinned{-webkit-transform:none;transform:none} \ No newline at end of file diff --git a/dashboard-ui/css/metadataeditor.css b/dashboard-ui/css/metadataeditor.css index e03353eddb..699342c4bb 100644 --- a/dashboard-ui/css/metadataeditor.css +++ b/dashboard-ui/css/metadataeditor.css @@ -1,221 +1 @@ -.editorTab { - padding-bottom: 200px; -} - -.editPageContent { - padding: 0; -} - -.editPageInnerContent { - padding: 0 15px 100px; -} - -.editPageName { - margin: .5em 0 0; -} - -.editPageSidebar { - display: none; -} - -.libraryTree { - margin-left: .25em; -} - -.offlineEditorNode { - color: #cc3333; -} - -.editorNode img { - height: 18px; - margin: 0 .35em; - vertical-align: middle; - position: relative; - top: -2px; -} - -.remoteImageContainer { - display: inline-block; - margin: 5px; - vertical-align: top; -} - -.remoteImageDetails { - text-align: left; - background: #282828; - position: relative; - padding: 5px 5px 2px; -} - - .remoteImageDetails paper-icon-button { - position: absolute; - bottom: 0; - right: 0; - } - -.remoteImageDetailText { - padding: 5px 5px; -} - - .remoteImageDetailText + .remoteImageDetailText { - color: #ccc; - } - -.remoteImage { - background-position: center bottom; - background-repeat: no-repeat; - background-size: contain; - display: block; - /* For the box shadow so that the bottom border isnt underneath the text */ - z-index: 100000; - position: relative; -} - -.remotePosterImage { - width: 140px; - height: 210px; -} - -.remoteBackdropImage { - width: 272px; - height: 153px; -} - -.remoteBannerImage { - width: 272px; - height: 50px; -} - -.remoteDiscImage { - width: 180px; - height: 180px; -} - -@media all and (min-width: 600px) { - - .remotePosterImage { - width: 160px; - height: 240px; - } -} - -@media all and (min-width: 1200px) { - - .remotePosterImage { - width: 200px; - height: 300px; - } - - .remoteBackdropImage { - width: 320px; - height: 180px; - } - - .remoteDiscImage { - width: 240px; - height: 240px; - } - - .remoteBannerImage { - width: 544px; - height: 100px; - } -} - -.editorfieldDescription { - color: #ccc; -} - -.searchImage { - background-position: center bottom; - background-repeat: no-repeat; - background-size: contain; - display: block; -} - -.searchBackdropImageContainer { - width: 160px; -} - -.searchDiscImageContainer { - width: 150px; -} - -.searchPosterImageContainer { - width: 140px; -} - -.searchBackdropImageContainer .searchImage { - height: 90px; -} - -.searchDiscImageContainer .searchImage { - height: 150px; -} - -.searchPosterImageContainer .searchImage { - height: 210px; -} - -.searchImageContainer .remoteImageDetails { - overflow-x: hidden; - text-overflow: ellipsis; -} - -.jstree-anchor { - font-weight: normal !important; -} - -.jstree-wholerow-hovered { - background: #38c !important; - border-radius: 0 !important; - box-shadow: none !important; -} - -.jstree-default .jstree-hovered { - background: none !important; - border-radius: 0 !important; - box-shadow: none !important; - color: #fff !important; -} - -.jstree-default .jstree-wholerow-clicked { - background: #52B54B !important; -} - -@media all and (min-width: 600px) { - - .remoteBannerImage { - width: 450px; - height: 83px; - } -} - -@media all and (min-width: 800px) { - - .editPageSidebar { - position: fixed; - top: 54px; - bottom: 0; - left: 0; - width: 30%; - display: block; - border-right: 1px solid #555; - } - - .editPageInnerContent { - float: right; - width: 67.5%; - } -} - -@media all and (min-width: 1800px) { - - .editPageSidebar { - width: 25%; - } - - .editPageInnerContent { - width: 72.5%; - } -} \ No newline at end of file +.editorTab{padding-bottom:200px}.editPageContent{padding:0}.editPageInnerContent{padding:0 15px 100px}.editPageName{margin:.5em 0 0}.editPageSidebar{display:none}.libraryTree{margin-left:.25em}.offlineEditorNode{color:#c33}.editorfieldDescription,.remoteImageDetailText+.remoteImageDetailText{color:#ccc}.editorNode img{height:18px;margin:0 .35em;vertical-align:middle;position:relative;top:-2px}.remoteImageContainer{display:inline-block;margin:5px;vertical-align:top}.remoteImageDetails{text-align:left;background:#282828;position:relative;padding:5px 5px 2px}.remoteImage,.searchImage{background-position:center bottom;background-repeat:no-repeat;display:block}.remoteImageDetails paper-icon-button{position:absolute;bottom:0;right:0}.remoteImageDetailText{padding:5px}.remoteImage{-webkit-background-size:contain;background-size:contain;z-index:100000;position:relative}.remotePosterImage{width:140px;height:210px}.remoteBackdropImage{width:272px;height:153px}.remoteBannerImage{width:272px;height:50px}.remoteDiscImage{width:180px;height:180px}@media all and (min-width:600px){.remotePosterImage{width:160px;height:240px}}@media all and (min-width:1200px){.remotePosterImage{width:200px;height:300px}.remoteBackdropImage{width:320px;height:180px}.remoteDiscImage{width:240px;height:240px}.remoteBannerImage{width:544px;height:100px}}.searchImage{-webkit-background-size:contain;background-size:contain}.searchBackdropImageContainer{width:160px}.searchDiscImageContainer{width:150px}.searchPosterImageContainer{width:140px}.searchBackdropImageContainer .searchImage{height:90px}.searchDiscImageContainer .searchImage{height:150px}.searchPosterImageContainer .searchImage{height:210px}.searchImageContainer .remoteImageDetails{overflow-x:hidden;-o-text-overflow:ellipsis;text-overflow:ellipsis}.jstree-anchor{font-weight:400!important}.jstree-wholerow-hovered{background:#38c!important;-webkit-border-radius:0!important;border-radius:0!important;-webkit-box-shadow:none!important;box-shadow:none!important}.jstree-default .jstree-hovered{background:0 0!important;-webkit-border-radius:0!important;border-radius:0!important;-webkit-box-shadow:none!important;box-shadow:none!important;color:#fff!important}.jstree-default .jstree-wholerow-clicked{background:#52B54B!important}@media all and (min-width:600px){.remoteBannerImage{width:450px;height:83px}}@media all and (min-width:800px){.editPageSidebar{position:fixed;top:54px;bottom:0;left:0;width:30%;display:block;border-right:1px solid #555}.editPageInnerContent{float:right;width:67.5%}}@media all and (min-width:1800px){.editPageSidebar{width:25%}.editPageInnerContent{width:72.5%}} \ No newline at end of file diff --git a/dashboard-ui/css/notifications.css b/dashboard-ui/css/notifications.css index 0ac0205781..0763705f50 100644 --- a/dashboard-ui/css/notifications.css +++ b/dashboard-ui/css/notifications.css @@ -1,35 +1 @@ -.btnNotifications { - text-decoration: none !important; - outline: 0 !important; - vertical-align: middle; - width: auto; - margin: 0; - padding-top: 0; - padding-bottom: 0; -} - -.btnNotificationsInner { - color: #fff; - font-weight: 500; - position: relative; - border-radius: 1000px; - background: #444; - line-height: 28px; - min-width: 30px; - display: inline-flex; - align-items: center; - justify-content: center; - text-align: center; -} - -.levelNormal { - background-color: #43A047; -} - -.levelWarning { - background-color: #FF7537; -} - -.levelError { - background-color: #d14836; -} \ No newline at end of file +.btnNotifications{text-decoration:none!important;outline:0!important;vertical-align:middle;width:auto;margin:0;padding-top:0;padding-bottom:0}.btnNotificationsInner{color:#fff;font-weight:500;position:relative;-webkit-border-radius:1000px;border-radius:1000px;background:#444;line-height:28px;min-width:30px;display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;text-align:center}.levelNormal{background-color:#43A047}.levelWarning{background-color:#FF7537}.levelError{background-color:#d14836} \ No newline at end of file diff --git a/dashboard-ui/css/nowplaying.css b/dashboard-ui/css/nowplaying.css index 86982cf2a7..f472dc768c 100644 --- a/dashboard-ui/css/nowplaying.css +++ b/dashboard-ui/css/nowplaying.css @@ -1,172 +1 @@ -/*.nowPlayingPage { - padding-top: 1em !important; -}*/ - -.remoteControlContent { - padding: 1em 0 0; - max-width: 96%; -} - -.nowPlayingInfoContainer { - display: flex; - flex-direction: row; -} - -.nowPlayingPageTitle { - margin: 0 0 .5em .5em; -} - -.nowPlayingPositionSliderContainer { - margin: .7em 0 .7em 1em; -} - -.nowPlayingInfoButtons { - display: flex; - align-items: center; - flex-wrap: wrap; - font-size: 130%; -} - -.nowPlayingPageImageContainer { - width: 20%; - margin-right: .25em; - position: relative; - flex-shrink: 0; -} - -@media all and (min-width: 800px) { - - .nowPlayingPageImageContainer { - width: 16%; - } -} - -.nowPlayingInfoControls { - flex-grow: 1; - display: flex; - flex-direction: column; - justify-content: center; -} - -.nowPlayingPageImage { - /*position: absolute;*/ - bottom: 0; - left: 0; - right: 0; - width: 100%; - -moz-box-shadow: 0 0 1.9vh #000; - -webkit-box-shadow: 0 0 1.9vh #000; - box-shadow: 0 0 1.9vh #000; - border: solid 1px #222; - user-drag: none; - user-select: none; - -moz-user-select: none; - -webkit-user-drag: none; - -webkit-user-select: none; - -ms-user-select: none; -} - -@media all and (orientation: portrait) and (max-width: 800px) { - - .remoteControlContent { - padding-top: 0; - } - - .nowPlayingInfoContainer { - flex-direction: column !important; - align-items: center; - } - - .nowPlayingPageTitle { - text-align: center; - margin: .5em 0 .75em 0; - } - - .nowPlayingPositionSliderContainer { - margin: .7em 1em; - } - - .nowPlayingInfoButtons { - justify-content: center; - } - - .nowPlayingPageImageContainer { - width: auto; - margin-right: 0; - } - - .nowPlayingInfoControls { - margin-top: 1em; - } - - .nowPlayingPageImage { - width: auto; - height: 36vh; - } -} - -.nowPlayingTime { - display: flex; - align-items: center; - margin: 0 1em; -} - -.nowPlayingSecondaryButtons { - display: flex; - align-items: center; -} - -@media all and (min-width: 800px) { - - .nowPlayingSecondaryButtons { - flex-grow: 1; - justify-content: flex-end; - } -} - -@media all and (min-width: 1280px) { - - .nowPlayingPageImageContainer { - margin-right: .75em; - } -} - -.nowPlayingNavButtonContainer { - width: 400px; -} - -.nowPlayingPageRepeatActive { - color: #2ad !important; -} - -.smallBackdropPosterItem .cardOverlayInner > div { - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; -} - -.playlistIndexIndicatorImage { - background-size: initial !important; - background-image: url(images/ani_equalizer_white.gif) !important; -} - -.hideVideoButtons .videoButton { - display: none; -} - -.nowPlayingCastIcon { - font-size: 86%; -} - -.nowPlayingVolumeSliderContainer { - width: 6em; -} - - - -@media all and (max-width: 400px) { - - .playlist .listItemMediaInfo { - display: none !important; - } -} +.remoteControlContent{padding:1em 0 0;max-width:96%}.nowPlayingInfoContainer{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row}.nowPlayingPageTitle{margin:0 0 .5em .5em}.nowPlayingPositionSliderContainer{margin:.7em 0 .7em 1em}.nowPlayingInfoButtons{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-flex-wrap:wrap;flex-wrap:wrap;font-size:130%}.nowPlayingInfoControls,.nowPlayingTime{display:-webkit-box;display:-webkit-flex}.nowPlayingPageImageContainer{width:20%;margin-right:.25em;position:relative;-webkit-flex-shrink:0;flex-shrink:0}@media all and (min-width:800px){.nowPlayingPageImageContainer{width:16%}}.nowPlayingInfoControls{-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.nowPlayingPageImage{bottom:0;left:0;right:0;width:100%;-webkit-box-shadow:0 0 1.9vh #000;box-shadow:0 0 1.9vh #000;border:1px solid #222;user-drag:none;user-select:none;-moz-user-select:none;-webkit-user-drag:none;-webkit-user-select:none;-ms-user-select:none}@media all and (orientation:portrait) and (max-width:800px){.remoteControlContent{padding-top:0}.nowPlayingInfoContainer{-webkit-box-orient:vertical!important;-webkit-box-direction:normal!important;-webkit-flex-direction:column!important;flex-direction:column!important;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.nowPlayingPageTitle{text-align:center;margin:.5em 0 .75em}.nowPlayingPositionSliderContainer{margin:.7em 1em}.nowPlayingInfoButtons{-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.nowPlayingPageImageContainer{width:auto;margin-right:0}.nowPlayingInfoControls{margin-top:1em}.nowPlayingPageImage{width:auto;height:36vh}}.nowPlayingTime{display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin:0 1em}.nowPlayingSecondaryButtons{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}@media all and (min-width:800px){.nowPlayingSecondaryButtons{-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1;-webkit-box-pack:end;-webkit-justify-content:flex-end;justify-content:flex-end}}@media all and (min-width:1280px){.nowPlayingPageImageContainer{margin-right:.75em}}.nowPlayingNavButtonContainer{width:400px}.nowPlayingPageRepeatActive{color:#2ad!important}.smallBackdropPosterItem .cardOverlayInner>div{white-space:nowrap;-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden}.playlistIndexIndicatorImage{-webkit-background-size:initial initial!important;background-size:initial!important;background-image:url(images/ani_equalizer_white.gif)!important}.hideVideoButtons .videoButton{display:none}.nowPlayingCastIcon{font-size:86%}.nowPlayingVolumeSliderContainer{width:6em}@media all and (max-width:400px){.playlist .listItemMediaInfo{display:none!important}} \ No newline at end of file diff --git a/dashboard-ui/css/nowplayingbar.css b/dashboard-ui/css/nowplayingbar.css index f8da4f4727..79a980ae04 100644 --- a/dashboard-ui/css/nowplayingbar.css +++ b/dashboard-ui/css/nowplayingbar.css @@ -1,264 +1 @@ -.nowPlayingText { - display: inline-block; - position: relative; - top: -7px; - margin: 0 0 0 3px; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - vertical-align: middle; - text-align: left; - max-width: 130px; -} - -.mediaButton.active { - color: #52B54B; -} - -@media (min-width: 500px) { - .nowPlayingText { - max-width: 180px; - } -} - -@media (min-width: 600px) { - .nowPlayingText { - max-width: 200px; - } -} - -@media (min-width: 800px) { - .nowPlayingText { - margin-right: 30px; - } -} - -.nowPlayingBarInfoContainer { - display: flex; - align-items: center; -} - -.currentTime { - display: inline-block; - vertical-align: middle; - max-width: 110px; - margin-right: 2em; - font-weight: normal; -} - -/* Now playing bar */ -.nowPlayingBar { - /* Above everything, except for the video player and popup overlays */ - color: #fff; - text-align: center; - /*box-shadow: 0 -2px 2px 0 rgba(0,0,0,.14),-1px 5px 1px rgba(0,0,0,.12);*/ - will-change: transform; - contain: layout style; - font-size: 90%; - transition: transform 200ms ease-out; -} - -.nowPlayingBar-hidden { - transform: translate3d(0,100%,0); -} - -.hiddenNowPlayingBar .nowPlayingBar { - display: none !important; -} - -.nowPlayingBarTop { - display: flex; - flex-direction: row; - align-items: center; -} - -.mediaButton, .nowPlayingBarUserDataButtons .btnUserItemRating { - vertical-align: middle; - color: #e8e8e8; - margin: 0; - text-align: center; -} - - .mediaButton i { - height: 1em; - width: 1em; - font-size: 36px; - } - - .mediaButton.muteButton i, .mediaButton.unmuteButton i, .mediaButton.castButton i, .mediaButton.infoButton i { - font-size: 24px; - } - -.nowPlayingImage { - display: inline-block; - vertical-align: middle; - margin-right: 1em; -} - - .nowPlayingImage img { - vertical-align: bottom; - } - - .nowPlayingImage img { - height: 64px; - } - -.nowPlayingBar .nowPlayingImage { - width: 64px; - height: 64px; - background-position: center center; - background-repeat: no-repeat; - background-size: contain; -} - -.nowPlayingBarText { - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; - vertical-align: middle; - text-align: left; - max-width: 130px; - flex-grow: 1; -} - -.repeatActive { - color: #52B54B; -} - -@media (min-width: 500px) { - .nowPlayingBarText { - max-width: 180px; - } -} - -@media (min-width: 600px) { - .nowPlayingBarText { - max-width: 200px; - } -} - -@media (min-width: 700px) { - .nowPlayingBarText { - max-width: 240px; - } -} - -@media (min-width: 800px) { - .nowPlayingBarText { - max-width: 300px; - margin-right: 30px; - } -} - -@media (min-width: 900px) { - .nowPlayingBarText { - max-width: 400px; - } -} - -.nowPlayingBarCenter { - vertical-align: middle; - text-align: center; - margin-top: 6px; - /* Need this to make sure it's on top of nowPlayingBarPositionContainer so that buttons are fully clickable */ - z-index: 2; - position: absolute; - left: 200px; - right: 200px; - top: 0; -} - -.nowPlayingBarPositionContainer { - position: absolute !important; - left: 64px; - top: -8px; - right: 0; - z-index: 1; -} - - .nowPlayingBarPositionContainer .mdl-slider__background-upper { - background: #333; - } - -.headroom--unpinned .nowPlayingBarPositionContainer { - display: none; -} - -.noMediaProgress .nowPlayingBarPositionContainer { - display: none; -} - -.nowPlayingBarRight { - position: relative; - margin: 0 1em 0 auto; - /* Need this to make sure it's on top of nowPlayingBarPositionContainer so that buttons are fully clickable */ - z-index: 2; - display: flex; - align-items: center; -} - -.nowPlayingBarCurrentTime { - vertical-align: middle; - font-weight: normal; - text-align: center; - display: inline-block; - margin: 0 auto; - padding-left: 50px; -} - -.nowPlayingBarVolumeSliderContainer { - margin-right: 2em; -} - -.nowPlayingBarUserDataButtons { - display: inline-block; - margin-left: 2em; - margin-right: 2em; -} - - -@media all and (max-width: 1400px) { - - .nowPlayingBarUserDataButtons { - display: none; - } -} - -@media all and (max-width: 1100px) { - - .nowPlayingBarVolumeSliderContainer, .nowPlayingBar .muteButton, .nowPlayingBar .unmuteButton { - display: none !important; - } -} - -@media all and (max-width: 800px) { - - .nowPlayingBarCurrentTime { - padding-left: 0; - top: 22px; - right: 140px; - position: absolute; - } - - .nowPlayingBarCenter > *:not(.nowPlayingBarCurrentTime) { - display: none !important; - } - - .toggleRepeatButton { - display: none; - } -} - -@media all and (min-width: 800px) { - - .nowPlayingBarRight .playPauseButton { - display: none; - } -} - -@media all and (max-width: 600px) { - - .nowPlayingBarCurrentTime { - display: none; - } -} +.nowPlayingBarText,.nowPlayingText{overflow:hidden;white-space:nowrap;-o-text-overflow:ellipsis;text-overflow:ellipsis}.nowPlayingText{display:inline-block;position:relative;top:-7px;margin:0 0 0 3px;vertical-align:middle;text-align:left;max-width:130px}.mediaButton.active{color:#52B54B}@media (min-width:500px){.nowPlayingText{max-width:180px}}@media (min-width:600px){.nowPlayingText{max-width:200px}}@media (min-width:800px){.nowPlayingText{margin-right:30px}}.nowPlayingBarInfoContainer{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.currentTime{display:inline-block;vertical-align:middle;max-width:110px;margin-right:2em;font-weight:400}.nowPlayingBar{color:#fff;text-align:center;will-change:transform;contain:layout style;font-size:90%;-webkit-transition:-webkit-transform .2s ease-out;-o-transition:transform .2s ease-out;transition:transform .2s ease-out}.nowPlayingBar-hidden{-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}.hiddenNowPlayingBar .nowPlayingBar{display:none!important}.nowPlayingBarTop{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.mediaButton,.nowPlayingBarUserDataButtons .btnUserItemRating{vertical-align:middle;color:#e8e8e8;margin:0;text-align:center}.mediaButton i{height:1em;width:1em;font-size:36px}.mediaButton.castButton i,.mediaButton.infoButton i,.mediaButton.muteButton i,.mediaButton.unmuteButton i{font-size:24px}.nowPlayingImage{display:inline-block;vertical-align:middle;margin-right:1em}.nowPlayingImage img{vertical-align:bottom;height:64px}.nowPlayingBar .nowPlayingImage{width:64px;height:64px;background-position:center center;background-repeat:no-repeat;-webkit-background-size:contain;background-size:contain}.nowPlayingBarText{vertical-align:middle;text-align:left;max-width:130px;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1}.repeatActive{color:#52B54B}@media (min-width:500px){.nowPlayingBarText{max-width:180px}}@media (min-width:600px){.nowPlayingBarText{max-width:200px}}@media (min-width:700px){.nowPlayingBarText{max-width:240px}}@media (min-width:800px){.nowPlayingBarText{max-width:300px;margin-right:30px}}@media (min-width:900px){.nowPlayingBarText{max-width:400px}}.nowPlayingBarCenter{vertical-align:middle;text-align:center;margin-top:6px;z-index:2;position:absolute;left:200px;right:200px;top:0}.nowPlayingBarPositionContainer{position:absolute!important;left:64px;top:-8px;right:0;z-index:1}.nowPlayingBarPositionContainer .mdl-slider__background-upper{background:#333}.headroom--unpinned .nowPlayingBarPositionContainer,.noMediaProgress .nowPlayingBarPositionContainer{display:none}.nowPlayingBarRight{position:relative;margin:0 1em 0 auto;z-index:2;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.nowPlayingBarCurrentTime{vertical-align:middle;font-weight:400;text-align:center;display:inline-block;margin:0 auto;padding-left:50px}.nowPlayingBarVolumeSliderContainer{margin-right:2em}.nowPlayingBarUserDataButtons{display:inline-block;margin-left:2em;margin-right:2em}@media all and (max-width:1400px){.nowPlayingBarUserDataButtons{display:none}}@media all and (max-width:1100px){.nowPlayingBar .muteButton,.nowPlayingBar .unmuteButton,.nowPlayingBarVolumeSliderContainer{display:none!important}}@media all and (max-width:800px){.nowPlayingBarCurrentTime{padding-left:0;top:22px;right:140px;position:absolute}.nowPlayingBarCenter>:not(.nowPlayingBarCurrentTime){display:none!important}.toggleRepeatButton{display:none}}@media all and (min-width:800px){.nowPlayingBarRight .playPauseButton{display:none}}@media all and (max-width:600px){.nowPlayingBarCurrentTime{display:none}} \ No newline at end of file diff --git a/dashboard-ui/css/site.css b/dashboard-ui/css/site.css index 704d9e4de1..6bf9ffdbbb 100644 --- a/dashboard-ui/css/site.css +++ b/dashboard-ui/css/site.css @@ -1,344 +1 @@ -.backgroundContainer { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - contain: layout style; -} - -/* Links */ -.ui-body-b a { - color: #52B54B /*{b-link-color}*/; - font-weight: 500; -} - - .ui-body-b a:visited { - color: #52B54B /*{b-link-visited}*/; - } - - .ui-body-b a:hover { - color: #2E7D32 /*{b-link-hover}*/; - } - - .ui-body-b a:active { - color: #2E7D32 /*{b-link-active}*/; - } - -/* Remove IE mobile 300ms tap delay */ -html { - -ms-touch-action: manipulation; - touch-action: manipulation; - /* Prevent white flickering */ - background-color: #242424; - /* Normalize for different browsers */ - margin: 0; - padding: 0; - height: 100%; - font-family: -apple-system, BlinkMacSystemFont, "Roboto", "Segoe UI", "Oxygen-Sans", "Ubuntu", "Cantarell", "Helvetica Neue", 'Open Sans', sans-serif; - font-size: 88%; -} - -h1 { - font-family: -apple-system-headline, BlinkMacSystemFont, "Roboto", "Segoe UI", "Oxygen-Sans", "Ubuntu", "Cantarell", "Helvetica Neue", 'Open Sans', sans-serif; -} - -h2 { - font-family: -apple-system-subheadline, BlinkMacSystemFont, "Roboto", "Segoe UI", "Oxygen-Sans", "Ubuntu", "Cantarell", "Helvetica Neue", 'Open Sans', sans-serif; -} - -body { - overflow-y: scroll !important; - /* This is needed to prevent a horizontal scrollbar while neon-animated-pages are animating. */ - overflow-x: hidden; - /*Can't use this with safari or it causes some content to disappear*/ - /*-webkit-overflow-scrolling: touch;*/ - /* Remove the white default from jqm */ - background-color: transparent !important; - /* Normalize for different browsers */ - margin: 0; - padding: 0; - height: 100%; - -webkit-font-smoothing: antialiased; -} - - body.autoScrollY { - overflow-y: auto !important; - } - -.mainAnimatedPage { - /* Have to override because it breaks scrolling when dependant on window scroll */ - contain: style !important; -} - -/* Without this, no content will be displayed in mobile safari */ -.pageContainer { - overflow-x: visible !important; - /* jqm often wants to assign a background color to this */ - background-color: transparent !important; -} - -.bodyWithPopupOpen { - overflow-y: hidden !important; -} - -h1, h2, h3 { - margin-top: 1em; -} - -h1 { - font-weight: normal !important; - opacity: .7; - font-size: 1.72em; -} - -h2 { - font-weight: normal; -} - -h3 { - font-weight: normal; -} - -a, a:active, a:hover { - text-decoration: none; -} - -.libraryPage h1 a { - color: #fff !important; -} - -h1 a:hover { - text-decoration: underline; -} - -.ui-body-b a.accent { - color: #52B54B !important; -} - -.ui-body-a .paperList { - background-color: #fff; -} - -.ui-body-a [is="emby-select"] { - border-color: #ccc !important; -} - -.ui-body-a [is="emby-input"], .ui-body-a [is="emby-textarea"] { - background: none; - border-color: #ccc !important; -} - -.ui-body-a .secondaryText { - color: #ccc; -} - -.ui-body-b .secondaryText { - color: #aaa; -} - -div[data-role='page'] { - outline: none; -} - -/** - * Note: I have omitted any vendor-prefixes for clarity. - * Adding them is left as an exercise for the reader. - */ -.headroom { - transition: transform 180ms linear; -} - -.headroom--pinned { - transform: none; -} - -.headroom--unpinned:not(.headroomDisabled) { - transform: translateY(-100%); -} - -.libraryViewNav.headroom--unpinned:not(.headroomDisabled) { - transform: translateY(-210%); -} - -.hide { - display: none !important; -} - -/* - Header - */ -.header { - padding: 20px 0 0 20px; -} - -.imgLogoIcon { - height: 40px; - vertical-align: middle; -} - - .imgLogoIcon + span { - margin-left: 10px; - } - -@media all and (max-height: 800px) { - - .header { - display: none !important; - } -} - -.pageTitle { - margin-top: 0; - font-family: inherit; -} - -.fieldDescription { - padding-left: 2px; - font-weight: normal; - white-space: normal !important; -} - -.fieldDescription + .fieldDescription { - margin-top: 5px; -} - -.background-theme-a .backgroundContainer { - background-color: #f6f6f6; -} - -.dialog.background-theme-a { - background-color: #f0f0f0; -} - -.ui-content { - border-width: 0; - overflow: visible; - overflow-x: hidden; - padding: 1em; -} - -.page > .ui-content, .pageWithAbsoluteTabs .pageTabContent, .absolutePageTabContent .itemsContainer { - /* Need this so that the audio player doesn't cover content, but also for unveil lazy loading. */ - padding-bottom: 160px; -} - -@media all and (min-width: 800px) { - - /* - Forms - */ - form, .readOnlyContent { - max-width: 700px; - } - - .header { - padding-bottom: 15px; - } -} - -@media all and (min-width: 900px) { - - .page:not(.standalonePage) .header { - padding-top: 0; - } -} - -.supporterPromotionContainer { - margin: 0 0 2em; -} - -@media all and (min-width: 1280px) { - - .supporterPromotionContainer { - position: fixed; - top: 120px; - right: 0; - } -} - -.fullWidthContent .supporterPromotionContainer { - position: static !important; -} - -@media all and (min-width: 800px) { - - .supporterPromotionContainer { - display: flex; - flex-direction: row-reverse; - } - - .supporterPromotion { - text-align: center; - padding: 0 2em; - } - - .supporterPromotion button { - padding-left: 2em; - padding-right: 2em; - } -} - -.syncActivityForTarget { - margin: 0 0 3em 0; -} - -@media all and (min-width: 800px) { - - .syncActivityForTarget { - max-width: 600px; - margin: 0 3em 3em 0; - display: inline-block; - vertical-align: top; - min-width: 400px; - } -} - -.imageDropZone { - border: 2px dashed #bbb; - -moz-border-radius: 5px; - -webkit-border-radius: 5px; - border-radius: 5px; - padding: 25px; - text-align: center; - color: #bbb; -} - -.ui-body-a .emby-collapsible-button { - border-color: #ddd; -} - -.ui-body-a .collapseContent { - background-color: #fff; -} - -.ui-body-a .inputLabelUnfocused, .ui-body-a .textareaLabel { - color: #555; -} - -.ui-body-a .inputLabelFocused, .ui-body-a .textareaLabelFocused, .ui-body-a .selectLabelFocused { - color: green; -} - -.ui-body-a .selectLabelUnfocused, .ui-body-a .paperListLabel, .ui-body-a .fieldDescription { - color: #555; -} - - -.ui-body-a .visualCardBox-cardScalable, .ui-body-a .visualCardBox-cardFooter { - background-color: #fff; -} - -.ui-body-a .visualCardBox { - border: 0; - margin: 6px; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); -} - -.ui-body-a .cardFooter .cardText + .cardText { - opacity: .8; -} - -.ui-body-a .listItem .secondary { - color: #737373; -} +.ui-body-b a,.ui-body-b a:visited{color:#52B54B}body,html{margin:0;padding:0;height:100%}.backgroundContainer{position:fixed;top:0;left:0;right:0;bottom:0;contain:layout style}.ui-body-b a{font-weight:500}.ui-body-b a:active,.ui-body-b a:hover{color:#2E7D32}html{touch-action:manipulation;background-color:#242424;font-family:-apple-system,BlinkMacSystemFont,Roboto,"Segoe UI",Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",'Open Sans',sans-serif;font-size:88%}.pageContainer,body{background-color:transparent!important}h1{font-family:-apple-system-headline,BlinkMacSystemFont,Roboto,"Segoe UI",Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",'Open Sans',sans-serif;font-weight:400!important;opacity:.7;font-size:1.72em}h2{font-family:-apple-system-subheadline,BlinkMacSystemFont,Roboto,"Segoe UI",Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",'Open Sans',sans-serif}body{overflow-y:scroll!important;overflow-x:hidden;-webkit-font-smoothing:antialiased}body.autoScrollY{overflow-y:auto!important}.mainAnimatedPage{contain:style!important}.pageContainer{overflow-x:visible!important}.bodyWithPopupOpen{overflow-y:hidden!important}h1,h2,h3{margin-top:1em}h2,h3{font-weight:400}a,a:active,a:hover{text-decoration:none}.libraryPage h1 a{color:#fff!important}h1 a:hover{text-decoration:underline}.ui-body-b a.accent{color:#52B54B!important}.ui-body-a .paperList{background-color:#fff}.ui-body-a [is=emby-select]{border-color:#ccc!important}.ui-body-a [is=emby-input],.ui-body-a [is=emby-textarea]{background:0 0;border-color:#ccc!important}.ui-body-a .secondaryText{color:#ccc}.ui-body-b .secondaryText{color:#aaa}div[data-role=page]{outline:0}.headroom{-webkit-transition:-webkit-transform 180ms linear;-o-transition:transform 180ms linear;transition:transform 180ms linear}.headroom--pinned{-webkit-transform:none;transform:none}.headroom--unpinned:not(.headroomDisabled){-webkit-transform:translateY(-100%);transform:translateY(-100%)}.libraryViewNav.headroom--unpinned:not(.headroomDisabled){-webkit-transform:translateY(-210%);transform:translateY(-210%)}.hide{display:none!important}.header{padding:20px 0 0 20px}.imgLogoIcon{height:40px;vertical-align:middle}.imgLogoIcon+span{margin-left:10px}@media all and (max-height:800px){.header{display:none!important}}.pageTitle{margin-top:0;font-family:inherit}.fieldDescription{padding-left:2px;font-weight:400;white-space:normal!important}.fieldDescription+.fieldDescription{margin-top:5px}.background-theme-a .backgroundContainer{background-color:#f6f6f6}.dialog.background-theme-a{background-color:#f0f0f0}.ui-body-a .collapseContent,.ui-body-a .visualCardBox-cardFooter,.ui-body-a .visualCardBox-cardScalable{background-color:#fff}.ui-content{border-width:0;overflow:visible;overflow-x:hidden;padding:1em}.absolutePageTabContent .itemsContainer,.page>.ui-content,.pageWithAbsoluteTabs .pageTabContent{padding-bottom:160px}@media all and (min-width:900px){.page:not(.standalonePage) .header{padding-top:0}}.supporterPromotionContainer{margin:0 0 2em}@media all and (min-width:1280px){.supporterPromotionContainer{position:fixed;top:120px;right:0}}.fullWidthContent .supporterPromotionContainer{position:static!important}.syncActivityForTarget{margin:0 0 3em}@media all and (min-width:800px){.readOnlyContent,form{max-width:700px}.header{padding-bottom:15px}.supporterPromotionContainer{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:reverse;-webkit-flex-direction:row-reverse;flex-direction:row-reverse}.supporterPromotion{text-align:center;padding:0 2em}.supporterPromotion button{padding-left:2em;padding-right:2em}.syncActivityForTarget{max-width:600px;margin:0 3em 3em 0;display:inline-block;vertical-align:top;min-width:400px}}.imageDropZone{border:2px dashed #bbb;-webkit-border-radius:5px;border-radius:5px;padding:25px;text-align:center;color:#bbb}.ui-body-a .emby-collapsible-button{border-color:#ddd}.ui-body-a .inputLabelUnfocused,.ui-body-a .textareaLabel{color:#555}.ui-body-a .inputLabelFocused,.ui-body-a .selectLabelFocused,.ui-body-a .textareaLabelFocused{color:green}.ui-body-a .fieldDescription,.ui-body-a .paperListLabel,.ui-body-a .selectLabelUnfocused{color:#555}.ui-body-a .visualCardBox{border:0;margin:6px;-webkit-box-shadow:0 2px 4px rgba(0,0,0,.1);box-shadow:0 2px 4px rgba(0,0,0,.1)}.ui-body-a .cardFooter .cardText+.cardText{opacity:.8}.ui-body-a .listItem .secondary{color:#737373} \ No newline at end of file diff --git a/dashboard-ui/dashboard/aboutpage.js b/dashboard-ui/dashboard/aboutpage.js index 5f97d9149b..bdd05aa7ac 100644 --- a/dashboard-ui/dashboard/aboutpage.js +++ b/dashboard-ui/dashboard/aboutpage.js @@ -1,15 +1 @@ -define([], function () { - 'use strict'; - - return function (view, params) { - - var self = this; - - view.addEventListener('viewbeforeshow', function (e) { - - var elem = view.querySelector('#appVersionNumber'); - - elem.innerHTML = elem.innerHTML.replace('{0}', ConnectionManager.appVersion()); - }); - } -}); \ No newline at end of file +define([],function(){"use strict";return function(view,params){view.addEventListener("viewbeforeshow",function(e){var elem=view.querySelector("#appVersionNumber");elem.innerHTML=elem.innerHTML.replace("{0}",ConnectionManager.appVersion())})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/autoorganizelog.js b/dashboard-ui/dashboard/autoorganizelog.js index d375c9e9b8..4deb839b9d 100644 --- a/dashboard-ui/dashboard/autoorganizelog.js +++ b/dashboard-ui/dashboard/autoorganizelog.js @@ -1,423 +1 @@ -define(['serverNotifications', 'events', 'scripts/taskbutton', 'datetime', 'paper-icon-button-light'], function (serverNotifications, events, taskButton, datetime) { - 'use strict'; - - var query = { - - StartIndex: 0, - Limit: 50 - }; - - var currentResult; - var page; - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function showStatusMessage(id) { - - var item = currentResult.Items.filter(function (i) { - - return i.Id == id; - })[0]; - - Dashboard.alert({ - - title: getStatusText(item, false), - message: item.StatusMessage - }); - } - - function deleteOriginalFile(page, id) { - - var item = currentResult.Items.filter(function (i) { - - return i.Id == id; - })[0]; - - var message = Globalize.translate('MessageFileWillBeDeleted') + '

' + item.OriginalPath + '

' + Globalize.translate('MessageSureYouWishToProceed'); - - require(['confirm'], function (confirm) { - - confirm(message, Globalize.translate('HeaderDeleteFile')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.deleteOriginalFileFromOrganizationResult(id).then(function () { - - Dashboard.hideLoadingMsg(); - - reloadItems(page, true); - - }, Dashboard.processErrorResponse); - }); - }); - } - - function organizeFileWithCorrections(page, item) { - - showCorrectionPopup(page, item); - } - - function showCorrectionPopup(page, item) { - - require(['components/fileorganizer/fileorganizer'], function (fileorganizer) { - - fileorganizer.show(item).then(function () { - reloadItems(page, false); - }); - }); - } - - function organizeFile(page, id) { - - var item = currentResult.Items.filter(function (i) { - - return i.Id == id; - })[0]; - - if (!item.TargetPath) { - - if (item.Type == "Episode") { - organizeFileWithCorrections(page, item); - } - - return; - } - - var message = Globalize.translate('MessageFollowingFileWillBeMovedFrom') + '

' + item.OriginalPath + '

' + Globalize.translate('MessageDestinationTo') + '

' + item.TargetPath; - - if (item.DuplicatePaths.length) { - message += '

' + Globalize.translate('MessageDuplicatesWillBeDeleted'); - - message += '

' + item.DuplicatePaths.join('
'); - } - - message += '

' + Globalize.translate('MessageSureYouWishToProceed'); - - require(['confirm'], function (confirm) { - - confirm(message, Globalize.translate('HeaderOrganizeFile')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.performOrganization(id).then(function () { - - Dashboard.hideLoadingMsg(); - - reloadItems(page, true); - - }, Dashboard.processErrorResponse); - }); - }); - } - - function reloadItems(page, showSpinner) { - - if (showSpinner) { - Dashboard.showLoadingMsg(); - } - - ApiClient.getFileOrganizationResults(query).then(function (result) { - - currentResult = result; - renderResults(page, result); - - Dashboard.hideLoadingMsg(); - }, Dashboard.processErrorResponse); - } - - function getStatusText(item, enhance) { - - var status = item.Status; - - var color = null; - - if (status == 'SkippedExisting') { - status = Globalize.translate('StatusSkipped'); - } - else if (status == 'Failure') { - color = '#cc0000'; - status = Globalize.translate('StatusFailed'); - } - if (status == 'Success') { - color = 'green'; - status = Globalize.translate('StatusSuccess'); - } - - if (enhance) { - - if (item.StatusMessage) { - - return '' + status + ''; - } else { - return '' + status + ''; - } - } - - return status; - } - - function renderResults(page, result) { - - var rows = result.Items.map(function (item) { - - var html = ''; - - html += ''; - - html += renderItemRow(item); - - html += ''; - - return html; - }).join(''); - - var resultBody = page.querySelector('.resultBody'); - resultBody.innerHTML = rows; - - resultBody.addEventListener('click', handleItemClick); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false - }); - - var topPaging = page.querySelector('.listTopPaging'); - topPaging.innerHTML = pagingHtml; - - var bottomPaging = page.querySelector('.listBottomPaging'); - bottomPaging.innerHTML = pagingHtml; - - var btnNextTop = topPaging.querySelector(".btnNextPage"); - var btnNextBottom = bottomPaging.querySelector(".btnNextPage"); - var btnPrevTop = topPaging.querySelector(".btnPreviousPage"); - var btnPrevBottom = bottomPaging.querySelector(".btnPreviousPage"); - - if (btnNextTop) { - btnNextTop.addEventListener('click', function () { - query.StartIndex += query.Limit; - reloadItems(page, true); - }); - } - - if (btnNextBottom) { - btnNextBottom.addEventListener('click', function () { - query.StartIndex += query.Limit; - reloadItems(page, true); - }); - } - - if (btnPrevTop) { - btnPrevTop.addEventListener('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page, true); - }); - } - - if (btnPrevBottom) { - btnPrevBottom.addEventListener('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page, true); - }); - } - - var btnClearLog = page.querySelector('.btnClearLog'); - - if (result.TotalRecordCount) { - btnClearLog.classList.remove('hide'); - } else { - btnClearLog.classList.add('hide'); - } - } - - function renderItemRow(item) { - - var html = ''; - - html += ''; - var hide = item.IsInProgress ? '' : ' hide'; - html += ''; - html += ''; - - html += ''; - var date = datetime.parseISO8601Date(item.Date, true); - html += datetime.toLocaleDateString(date); - html += ''; - - html += ''; - var status = item.Status; - - if (item.IsInProgress) { - html += ''; - html += item.OriginalFileName; - html += ''; - } - else if (status == 'SkippedExisting') { - html += ''; - html += item.OriginalFileName; - html += ''; - } - else if (status == 'Failure') { - html += ''; - html += item.OriginalFileName; - html += ''; - } else { - html += ''; - html += item.OriginalFileName; - html += ''; - } - html += ''; - - html += ''; - html += item.TargetPath || ''; - html += ''; - - html += ''; - - if (item.Status != 'Success') { - - html += ''; - html += ''; - } - - html += ''; - - return html; - } - - function handleItemClick(e) { - - var id; - - var buttonStatus = parentWithClass(e.target, 'btnShowStatusMessage'); - if (buttonStatus) { - - id = buttonStatus.getAttribute('data-resultid'); - showStatusMessage(id); - } - - var buttonOrganize = parentWithClass(e.target, 'btnProcessResult'); - if (buttonOrganize) { - - id = buttonOrganize.getAttribute('data-resultid'); - organizeFile(e.view, id); - } - - var buttonDelete = parentWithClass(e.target, 'btnDeleteResult'); - if (buttonDelete) { - - id = buttonDelete.getAttribute('data-resultid'); - deleteOriginalFile(e.view, id); - } - } - - function onServerEvent(e, apiClient, data) { - - if (e.type == 'ScheduledTaskEnded') { - - if (data && data.Key == 'AutoOrganize') { - reloadItems(page, false); - } - } else if (e.type == 'AutoOrganize_ItemUpdated' && data) { - - updateItemStatus(page, data); - } else { - - reloadItems(page, false); - } - } - - function updateItemStatus(page, item) { - - var rowId = '#row' + item.Id; - var row = page.querySelector(rowId); - - if (row) { - - row.innerHTML = renderItemRow(item); - } - } - - function getTabs() { - return [ - { - href: 'autoorganizelog.html', - name: Globalize.translate('TabActivityLog') - }, - { - href: 'autoorganizetv.html', - name: Globalize.translate('TabTV') - }, - { - href: 'autoorganizesmart.html', - name: Globalize.translate('TabSmartMatches') - }]; - } - - - return function (view, params) { - - page = view; - - var clearButton = view.querySelector('.btnClearLog'); - clearButton.addEventListener('click', function () { - - ApiClient.clearOrganizationLog().then(function () { - query.StartIndex = 0; - reloadItems(view, true); - }, Dashboard.processErrorResponse); - }); - - view.addEventListener('viewshow', function (e) { - - LibraryMenu.setTabs('autoorganize', 0, getTabs); - - reloadItems(view, true); - - events.on(serverNotifications, 'AutoOrganize_LogReset', onServerEvent); - events.on(serverNotifications, 'AutoOrganize_ItemUpdated', onServerEvent); - events.on(serverNotifications, 'AutoOrganize_ItemRemoved', onServerEvent); - events.on(serverNotifications, 'AutoOrganize_ItemAdded', onServerEvent); - events.on(serverNotifications, 'ScheduledTaskEnded', onServerEvent); - - // on here - taskButton({ - mode: 'on', - progressElem: view.querySelector('.organizeProgress'), - panel: view.querySelector('.organizeTaskPanel'), - taskKey: 'AutoOrganize', - button: view.querySelector('.btnOrganize') - }); - }); - - view.addEventListener('viewhide', function (e) { - - currentResult = null; - - events.off(serverNotifications, 'AutoOrganize_LogReset', onServerEvent); - events.off(serverNotifications, 'AutoOrganize_ItemUpdated', onServerEvent); - events.off(serverNotifications, 'AutoOrganize_ItemRemoved', onServerEvent); - events.off(serverNotifications, 'AutoOrganize_ItemAdded', onServerEvent); - events.off(serverNotifications, 'ScheduledTaskEnded', onServerEvent); - - // off here - taskButton({ - mode: 'off', - button: view.querySelector('.btnOrganize') - }); - }); - }; -}); \ No newline at end of file +define(["serverNotifications","events","scripts/taskbutton","datetime","paper-icon-button-light"],function(serverNotifications,events,taskButton,datetime){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function showStatusMessage(id){var item=currentResult.Items.filter(function(i){return i.Id==id})[0];Dashboard.alert({title:getStatusText(item,!1),message:item.StatusMessage})}function deleteOriginalFile(page,id){var item=currentResult.Items.filter(function(i){return i.Id==id})[0],message=Globalize.translate("MessageFileWillBeDeleted")+"

"+item.OriginalPath+"

"+Globalize.translate("MessageSureYouWishToProceed");require(["confirm"],function(confirm){confirm(message,Globalize.translate("HeaderDeleteFile")).then(function(){Dashboard.showLoadingMsg(),ApiClient.deleteOriginalFileFromOrganizationResult(id).then(function(){Dashboard.hideLoadingMsg(),reloadItems(page,!0)},Dashboard.processErrorResponse)})})}function organizeFileWithCorrections(page,item){showCorrectionPopup(page,item)}function showCorrectionPopup(page,item){require(["components/fileorganizer/fileorganizer"],function(fileorganizer){fileorganizer.show(item).then(function(){reloadItems(page,!1)})})}function organizeFile(page,id){var item=currentResult.Items.filter(function(i){return i.Id==id})[0];if(!item.TargetPath)return void("Episode"==item.Type&&organizeFileWithCorrections(page,item));var message=Globalize.translate("MessageFollowingFileWillBeMovedFrom")+"

"+item.OriginalPath+"

"+Globalize.translate("MessageDestinationTo")+"

"+item.TargetPath;item.DuplicatePaths.length&&(message+="

"+Globalize.translate("MessageDuplicatesWillBeDeleted"),message+="

"+item.DuplicatePaths.join("
")),message+="

"+Globalize.translate("MessageSureYouWishToProceed"),require(["confirm"],function(confirm){confirm(message,Globalize.translate("HeaderOrganizeFile")).then(function(){Dashboard.showLoadingMsg(),ApiClient.performOrganization(id).then(function(){Dashboard.hideLoadingMsg(),reloadItems(page,!0)},Dashboard.processErrorResponse)})})}function reloadItems(page,showSpinner){showSpinner&&Dashboard.showLoadingMsg(),ApiClient.getFileOrganizationResults(query).then(function(result){currentResult=result,renderResults(page,result),Dashboard.hideLoadingMsg()},Dashboard.processErrorResponse)}function getStatusText(item,enhance){var status=item.Status,color=null;return"SkippedExisting"==status?status=Globalize.translate("StatusSkipped"):"Failure"==status&&(color="#cc0000",status=Globalize.translate("StatusFailed")),"Success"==status&&(color="green",status=Globalize.translate("StatusSuccess")),enhance?item.StatusMessage?''+status+"":''+status+"":status}function renderResults(page,result){var rows=result.Items.map(function(item){var html="";return html+='',html+=renderItemRow(item),html+=""}).join(""),resultBody=page.querySelector(".resultBody");resultBody.innerHTML=rows,resultBody.addEventListener("click",handleItemClick);var pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1}),topPaging=page.querySelector(".listTopPaging");topPaging.innerHTML=pagingHtml;var bottomPaging=page.querySelector(".listBottomPaging");bottomPaging.innerHTML=pagingHtml;var btnNextTop=topPaging.querySelector(".btnNextPage"),btnNextBottom=bottomPaging.querySelector(".btnNextPage"),btnPrevTop=topPaging.querySelector(".btnPreviousPage"),btnPrevBottom=bottomPaging.querySelector(".btnPreviousPage");btnNextTop&&btnNextTop.addEventListener("click",function(){query.StartIndex+=query.Limit,reloadItems(page,!0)}),btnNextBottom&&btnNextBottom.addEventListener("click",function(){query.StartIndex+=query.Limit,reloadItems(page,!0)}),btnPrevTop&&btnPrevTop.addEventListener("click",function(){query.StartIndex-=query.Limit,reloadItems(page,!0)}),btnPrevBottom&&btnPrevBottom.addEventListener("click",function(){query.StartIndex-=query.Limit,reloadItems(page,!0)});var btnClearLog=page.querySelector(".btnClearLog");result.TotalRecordCount?btnClearLog.classList.remove("hide"):btnClearLog.classList.add("hide")}function renderItemRow(item){var html="";html+="";var hide=item.IsInProgress?"":" hide";html+='',html+="",html+='';var date=datetime.parseISO8601Date(item.Date,!0);html+=datetime.toLocaleDateString(date),html+="",html+='';var status=item.Status;return item.IsInProgress?(html+='',html+=item.OriginalFileName,html+=""):"SkippedExisting"==status?(html+='',html+=item.OriginalFileName,html+=""):"Failure"==status?(html+='',html+=item.OriginalFileName,html+=""):(html+='',html+=item.OriginalFileName,html+=""),html+="",html+='',html+=item.TargetPath||"",html+="",html+='',"Success"!=item.Status&&(html+='',html+=''),html+=""}function handleItemClick(e){var id,buttonStatus=parentWithClass(e.target,"btnShowStatusMessage");buttonStatus&&(id=buttonStatus.getAttribute("data-resultid"),showStatusMessage(id));var buttonOrganize=parentWithClass(e.target,"btnProcessResult");buttonOrganize&&(id=buttonOrganize.getAttribute("data-resultid"),organizeFile(e.view,id));var buttonDelete=parentWithClass(e.target,"btnDeleteResult");buttonDelete&&(id=buttonDelete.getAttribute("data-resultid"),deleteOriginalFile(e.view,id))}function onServerEvent(e,apiClient,data){"ScheduledTaskEnded"==e.type?data&&"AutoOrganize"==data.Key&&reloadItems(page,!1):"AutoOrganize_ItemUpdated"==e.type&&data?updateItemStatus(page,data):reloadItems(page,!1)}function updateItemStatus(page,item){var rowId="#row"+item.Id,row=page.querySelector(rowId);row&&(row.innerHTML=renderItemRow(item))}function getTabs(){return[{href:"autoorganizelog.html",name:Globalize.translate("TabActivityLog")},{href:"autoorganizetv.html",name:Globalize.translate("TabTV")},{href:"autoorganizesmart.html",name:Globalize.translate("TabSmartMatches")}]}var currentResult,page,query={StartIndex:0,Limit:50};return function(view,params){page=view;var clearButton=view.querySelector(".btnClearLog");clearButton.addEventListener("click",function(){ApiClient.clearOrganizationLog().then(function(){query.StartIndex=0,reloadItems(view,!0)},Dashboard.processErrorResponse)}),view.addEventListener("viewshow",function(e){LibraryMenu.setTabs("autoorganize",0,getTabs),reloadItems(view,!0),events.on(serverNotifications,"AutoOrganize_LogReset",onServerEvent),events.on(serverNotifications,"AutoOrganize_ItemUpdated",onServerEvent),events.on(serverNotifications,"AutoOrganize_ItemRemoved",onServerEvent),events.on(serverNotifications,"AutoOrganize_ItemAdded",onServerEvent),events.on(serverNotifications,"ScheduledTaskEnded",onServerEvent),taskButton({mode:"on",progressElem:view.querySelector(".organizeProgress"),panel:view.querySelector(".organizeTaskPanel"),taskKey:"AutoOrganize",button:view.querySelector(".btnOrganize")})}),view.addEventListener("viewhide",function(e){currentResult=null,events.off(serverNotifications,"AutoOrganize_LogReset",onServerEvent),events.off(serverNotifications,"AutoOrganize_ItemUpdated",onServerEvent),events.off(serverNotifications,"AutoOrganize_ItemRemoved",onServerEvent),events.off(serverNotifications,"AutoOrganize_ItemAdded",onServerEvent),events.off(serverNotifications,"ScheduledTaskEnded",onServerEvent),taskButton({mode:"off",button:view.querySelector(".btnOrganize")})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/autoorganizesmart.js b/dashboard-ui/dashboard/autoorganizesmart.js index 5c0d760e92..bd21108a63 100644 --- a/dashboard-ui/dashboard/autoorganizesmart.js +++ b/dashboard-ui/dashboard/autoorganizesmart.js @@ -1,178 +1 @@ -define(['listViewStyle'], function () { - 'use strict'; - - var query = { - - StartIndex: 0, - Limit: 100000 - }; - - var currentResult; - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function reloadList(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getSmartMatchInfos(query).then(function (infos) { - - currentResult = infos; - - populateList(page, infos); - - Dashboard.hideLoadingMsg(); - - }, function () { - - Dashboard.hideLoadingMsg(); - }); - } - - function populateList(page, result) { - - var infos = result.Items; - - if (infos.length > 0) { - infos = infos.sort(function (a, b) { - - a = a.OrganizerType + " " + (a.DisplayName || a.ItemName); - b = b.OrganizerType + " " + (b.DisplayName || b.ItemName); - - if (a == b) { - return 0; - } - - if (a < b) { - return -1; - } - - return 1; - }); - } - - var html = ""; - - if (infos.length) { - html += '
'; - } - - for (var i = 0, length = infos.length; i < length; i++) { - - var info = infos[i]; - - html += '
'; - - html += '
'; - html += 'folder'; - html += '
'; - - html += '
'; - html += "

" + (info.DisplayName || info.ItemName) + "

"; - html += '
'; - - html += '
'; - - var matchStringIndex = 0; - - html += info.MatchStrings.map(function (m) { - - var matchStringHtml = ''; - - matchStringHtml += '
'; - - matchStringHtml += '
'; - - matchStringHtml += "
" + m + "
"; - - matchStringHtml += '
'; - - matchStringHtml += ''; - - matchStringHtml += '
'; - matchStringIndex++; - - return matchStringHtml; - - }).join(''); - } - - if (infos.length) { - html += "
"; - } - - var matchInfos = page.querySelector('.divMatchInfos'); - matchInfos.innerHTML = html; - } - - function getTabs() { - return [ - { - href: 'autoorganizelog.html', - name: Globalize.translate('TabActivityLog') - }, - { - href: 'autoorganizetv.html', - name: Globalize.translate('TabTV') - }, - { - href: 'autoorganizesmart.html', - name: Globalize.translate('TabSmartMatches') - }]; - } - - return function (view, params) { - - var self = this; - - var divInfos = view.querySelector('.divMatchInfos'); - - divInfos.addEventListener('click', function (e) { - - var button = parentWithClass(e.target, 'btnDeleteMatchEntry'); - - if (button) { - - var index = parseInt(button.getAttribute('data-index')); - var matchIndex = parseInt(button.getAttribute('data-matchindex')); - - var info = currentResult.Items[index]; - var entries = [ - { - Name: info.ItemName, - Value: info.MatchStrings[matchIndex] - }]; - - ApiClient.deleteSmartMatchEntries(entries).then(function () { - - reloadList(view); - - }, Dashboard.processErrorResponse); - } - }); - - view.addEventListener('viewshow', function (e) { - - LibraryMenu.setTabs('autoorganize', 2, getTabs); - Dashboard.showLoadingMsg(); - - reloadList(view); - }); - - view.addEventListener('viewhide', function (e) { - - currentResult = null; - }); - }; -}); \ No newline at end of file +define(["listViewStyle"],function(){"use strict";function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function reloadList(page){Dashboard.showLoadingMsg(),ApiClient.getSmartMatchInfos(query).then(function(infos){currentResult=infos,populateList(page,infos),Dashboard.hideLoadingMsg()},function(){Dashboard.hideLoadingMsg()})}function populateList(page,result){var infos=result.Items;infos.length>0&&(infos=infos.sort(function(a,b){return a=a.OrganizerType+" "+(a.DisplayName||a.ItemName),b=b.OrganizerType+" "+(b.DisplayName||b.ItemName),a==b?0:a',html+='
',html+='folder',html+="
",html+='
',html+="

"+(info.DisplayName||info.ItemName)+"

",html+="
",html+="";var matchStringIndex=0;html+=info.MatchStrings.map(function(m){var matchStringHtml="";return matchStringHtml+='
',matchStringHtml+='
',matchStringHtml+="
"+m+"
",matchStringHtml+="
",matchStringHtml+='',matchStringHtml+="
",matchStringIndex++,matchStringHtml}).join("")}infos.length&&(html+="");var matchInfos=page.querySelector(".divMatchInfos");matchInfos.innerHTML=html}function getTabs(){return[{href:"autoorganizelog.html",name:Globalize.translate("TabActivityLog")},{href:"autoorganizetv.html",name:Globalize.translate("TabTV")},{href:"autoorganizesmart.html",name:Globalize.translate("TabSmartMatches")}]}var currentResult,query={StartIndex:0,Limit:1e5};return function(view,params){var divInfos=view.querySelector(".divMatchInfos");divInfos.addEventListener("click",function(e){var button=parentWithClass(e.target,"btnDeleteMatchEntry");if(button){var index=parseInt(button.getAttribute("data-index")),matchIndex=parseInt(button.getAttribute("data-matchindex")),info=currentResult.Items[index],entries=[{Name:info.ItemName,Value:info.MatchStrings[matchIndex]}];ApiClient.deleteSmartMatchEntries(entries).then(function(){reloadList(view)},Dashboard.processErrorResponse)}}),view.addEventListener("viewshow",function(e){LibraryMenu.setTabs("autoorganize",2,getTabs),Dashboard.showLoadingMsg(),reloadList(view)}),view.addEventListener("viewhide",function(e){currentResult=null})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/autoorganizetv.js b/dashboard-ui/dashboard/autoorganizetv.js index 54d24c2b52..d93ab1b5eb 100644 --- a/dashboard-ui/dashboard/autoorganizetv.js +++ b/dashboard-ui/dashboard/autoorganizetv.js @@ -1,182 +1 @@ -define([], function () { - 'use strict'; - - function getEpisodeFileName(value, enableMultiEpisode) { - - var seriesName = "Series Name"; - var episodeTitle = "Episode Four"; - - var result = value.replace('%sn', seriesName) - .replace('%s.n', seriesName.replace(' ', '.')) - .replace('%s_n', seriesName.replace(' ', '_')) - .replace('%s', '1') - .replace('%0s', '01') - .replace('%00s', '001') - .replace('%ext', 'mkv') - .replace('%en', episodeTitle) - .replace('%e.n', episodeTitle.replace(' ', '.')) - .replace('%e_n', episodeTitle.replace(' ', '_')); - - if (enableMultiEpisode) { - result = result - .replace('%ed', '5') - .replace('%0ed', '05') - .replace('%00ed', '005'); - } - - return result - .replace('%e', '4') - .replace('%0e', '04') - .replace('%00e', '004'); - } - - function loadPage(view, config) { - - var tvOptions = config.TvOptions; - - view.querySelector('#chkEnableTvSorting').checked = tvOptions.IsEnabled; - view.querySelector('#chkOverwriteExistingEpisodes').checked = tvOptions.OverwriteExistingEpisodes; - view.querySelector('#chkDeleteEmptyFolders').checked = tvOptions.DeleteEmptyFolders; - - view.querySelector('#txtMinFileSize').value = tvOptions.MinFileSizeMb; - view.querySelector('#txtSeasonFolderPattern').value = tvOptions.SeasonFolderPattern; - view.querySelector('#txtSeasonZeroName').value = tvOptions.SeasonZeroFolderName; - view.querySelector('#txtWatchFolder').value = tvOptions.WatchLocations[0] || ''; - - view.querySelector('#txtEpisodePattern').value = tvOptions.EpisodeNamePattern; - view.querySelector('#txtMultiEpisodePattern').value = tvOptions.MultiEpisodeNamePattern; - - view.querySelector('#txtDeleteLeftOverFiles').value = tvOptions.LeftOverFileExtensionsToDelete.join(';'); - - view.querySelector('#copyOrMoveFile').value = tvOptions.CopyOriginalFile.toString(); - } - - function onSubmit(view) { - - ApiClient.getNamedConfiguration('autoorganize').then(function (config) { - - var tvOptions = config.TvOptions; - - tvOptions.IsEnabled = view.querySelector('#chkEnableTvSorting').checked; - tvOptions.OverwriteExistingEpisodes = view.querySelector('#chkOverwriteExistingEpisodes').checked; - tvOptions.DeleteEmptyFolders = view.querySelector('#chkDeleteEmptyFolders').checked; - - tvOptions.MinFileSizeMb = view.querySelector('#txtMinFileSize').value; - tvOptions.SeasonFolderPattern = view.querySelector('#txtSeasonFolderPattern').value; - tvOptions.SeasonZeroFolderName = view.querySelector('#txtSeasonZeroName').value; - - tvOptions.EpisodeNamePattern = view.querySelector('#txtEpisodePattern').value; - tvOptions.MultiEpisodeNamePattern = view.querySelector('#txtMultiEpisodePattern').value; - - tvOptions.LeftOverFileExtensionsToDelete = view.querySelector('#txtDeleteLeftOverFiles').value.split(';'); - - var watchLocation = view.querySelector('#txtWatchFolder').value; - tvOptions.WatchLocations = watchLocation ? [watchLocation] : []; - - tvOptions.CopyOriginalFile = view.querySelector('#copyOrMoveFile').value; - - ApiClient.updateNamedConfiguration('autoorganize', config).then(Dashboard.processServerConfigurationUpdateResult, Dashboard.processErrorResponse); - }); - - return false; - } - - function getTabs() { - return [ - { - href: 'autoorganizelog.html', - name: Globalize.translate('TabActivityLog') - }, - { - href: 'autoorganizetv.html', - name: Globalize.translate('TabTV') - }, - { - href: 'autoorganizesmart.html', - name: Globalize.translate('TabSmartMatches') - }]; - } - - return function (view, params) { - - - function updateSeasonPatternHelp() { - - var value = view.querySelector('#txtSeasonFolderPattern').value; - value = value.replace('%s', '1').replace('%0s', '01').replace('%00s', '001'); - - var replacementHtmlResult = Globalize.translate('OrganizePatternResult').replace('{0}', value); - - view.querySelector('.seasonFolderFieldDescription').innerHTML = replacementHtmlResult; - } - - function updateEpisodePatternHelp() { - - var value = view.querySelector('#txtEpisodePattern').value; - var fileName = getEpisodeFileName(value, false); - - var replacementHtmlResult = Globalize.translate('OrganizePatternResult').replace('{0}', fileName); - - view.querySelector('.episodePatternDescription').innerHTML = replacementHtmlResult; - } - - function updateMultiEpisodePatternHelp() { - - var value = view.querySelector('#txtMultiEpisodePattern').value; - var fileName = getEpisodeFileName(value, true); - - var replacementHtmlResult = Globalize.translate('OrganizePatternResult').replace('{0}', fileName); - - view.querySelector('.multiEpisodePatternDescription').innerHTML = replacementHtmlResult; - } - - function selectWatchFolder(e) { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - - view.querySelector('#txtWatchFolder').value = path; - } - picker.close(); - }, - header: Globalize.translate('HeaderSelectWatchFolder'), - instruction: Globalize.translate('HeaderSelectWatchFolderHelp') - }); - }); - } - - view.querySelector('#txtSeasonFolderPattern').addEventListener('change', updateSeasonPatternHelp); - view.querySelector('#txtSeasonFolderPattern').addEventListener('keyup', updateSeasonPatternHelp); - view.querySelector('#txtEpisodePattern').addEventListener('change', updateEpisodePatternHelp); - view.querySelector('#txtEpisodePattern').addEventListener('keyup', updateEpisodePatternHelp); - view.querySelector('#txtMultiEpisodePattern').addEventListener('change', updateMultiEpisodePatternHelp); - view.querySelector('#txtMultiEpisodePattern').addEventListener('keyup', updateMultiEpisodePatternHelp); - view.querySelector('#btnSelectWatchFolder').addEventListener('click', selectWatchFolder); - - view.querySelector('.libraryFileOrganizerForm').addEventListener('submit', function (e) { - - e.preventDefault(); - onSubmit(view); - return false; - }); - - view.addEventListener('viewshow', function (e) { - - LibraryMenu.setTabs('autoorganize', 1, getTabs); - - ApiClient.getNamedConfiguration('autoorganize').then(function (config) { - loadPage(view, config); - updateSeasonPatternHelp(); - updateEpisodePatternHelp(); - updateMultiEpisodePatternHelp(); - }); - }); - }; -}); \ No newline at end of file +define([],function(){"use strict";function getEpisodeFileName(value,enableMultiEpisode){var seriesName="Series Name",episodeTitle="Episode Four",result=value.replace("%sn",seriesName).replace("%s.n",seriesName.replace(" ",".")).replace("%s_n",seriesName.replace(" ","_")).replace("%s","1").replace("%0s","01").replace("%00s","001").replace("%ext","mkv").replace("%en",episodeTitle).replace("%e.n",episodeTitle.replace(" ",".")).replace("%e_n",episodeTitle.replace(" ","_"));return enableMultiEpisode&&(result=result.replace("%ed","5").replace("%0ed","05").replace("%00ed","005")),result.replace("%e","4").replace("%0e","04").replace("%00e","004")}function loadPage(view,config){var tvOptions=config.TvOptions;view.querySelector("#chkEnableTvSorting").checked=tvOptions.IsEnabled,view.querySelector("#chkOverwriteExistingEpisodes").checked=tvOptions.OverwriteExistingEpisodes,view.querySelector("#chkDeleteEmptyFolders").checked=tvOptions.DeleteEmptyFolders,view.querySelector("#txtMinFileSize").value=tvOptions.MinFileSizeMb,view.querySelector("#txtSeasonFolderPattern").value=tvOptions.SeasonFolderPattern,view.querySelector("#txtSeasonZeroName").value=tvOptions.SeasonZeroFolderName,view.querySelector("#txtWatchFolder").value=tvOptions.WatchLocations[0]||"",view.querySelector("#txtEpisodePattern").value=tvOptions.EpisodeNamePattern,view.querySelector("#txtMultiEpisodePattern").value=tvOptions.MultiEpisodeNamePattern,view.querySelector("#txtDeleteLeftOverFiles").value=tvOptions.LeftOverFileExtensionsToDelete.join(";"),view.querySelector("#copyOrMoveFile").value=tvOptions.CopyOriginalFile.toString()}function onSubmit(view){return ApiClient.getNamedConfiguration("autoorganize").then(function(config){var tvOptions=config.TvOptions;tvOptions.IsEnabled=view.querySelector("#chkEnableTvSorting").checked,tvOptions.OverwriteExistingEpisodes=view.querySelector("#chkOverwriteExistingEpisodes").checked,tvOptions.DeleteEmptyFolders=view.querySelector("#chkDeleteEmptyFolders").checked,tvOptions.MinFileSizeMb=view.querySelector("#txtMinFileSize").value,tvOptions.SeasonFolderPattern=view.querySelector("#txtSeasonFolderPattern").value,tvOptions.SeasonZeroFolderName=view.querySelector("#txtSeasonZeroName").value,tvOptions.EpisodeNamePattern=view.querySelector("#txtEpisodePattern").value,tvOptions.MultiEpisodeNamePattern=view.querySelector("#txtMultiEpisodePattern").value,tvOptions.LeftOverFileExtensionsToDelete=view.querySelector("#txtDeleteLeftOverFiles").value.split(";");var watchLocation=view.querySelector("#txtWatchFolder").value;tvOptions.WatchLocations=watchLocation?[watchLocation]:[],tvOptions.CopyOriginalFile=view.querySelector("#copyOrMoveFile").value,ApiClient.updateNamedConfiguration("autoorganize",config).then(Dashboard.processServerConfigurationUpdateResult,Dashboard.processErrorResponse)}),!1}function getTabs(){return[{href:"autoorganizelog.html",name:Globalize.translate("TabActivityLog")},{href:"autoorganizetv.html",name:Globalize.translate("TabTV")},{href:"autoorganizesmart.html",name:Globalize.translate("TabSmartMatches")}]}return function(view,params){function updateSeasonPatternHelp(){var value=view.querySelector("#txtSeasonFolderPattern").value;value=value.replace("%s","1").replace("%0s","01").replace("%00s","001");var replacementHtmlResult=Globalize.translate("OrganizePatternResult").replace("{0}",value);view.querySelector(".seasonFolderFieldDescription").innerHTML=replacementHtmlResult}function updateEpisodePatternHelp(){var value=view.querySelector("#txtEpisodePattern").value,fileName=getEpisodeFileName(value,!1),replacementHtmlResult=Globalize.translate("OrganizePatternResult").replace("{0}",fileName);view.querySelector(".episodePatternDescription").innerHTML=replacementHtmlResult}function updateMultiEpisodePatternHelp(){var value=view.querySelector("#txtMultiEpisodePattern").value,fileName=getEpisodeFileName(value,!0),replacementHtmlResult=Globalize.translate("OrganizePatternResult").replace("{0}",fileName);view.querySelector(".multiEpisodePatternDescription").innerHTML=replacementHtmlResult}function selectWatchFolder(e){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&(view.querySelector("#txtWatchFolder").value=path),picker.close()},header:Globalize.translate("HeaderSelectWatchFolder"),instruction:Globalize.translate("HeaderSelectWatchFolderHelp")})})}view.querySelector("#txtSeasonFolderPattern").addEventListener("change",updateSeasonPatternHelp),view.querySelector("#txtSeasonFolderPattern").addEventListener("keyup",updateSeasonPatternHelp),view.querySelector("#txtEpisodePattern").addEventListener("change",updateEpisodePatternHelp),view.querySelector("#txtEpisodePattern").addEventListener("keyup",updateEpisodePatternHelp),view.querySelector("#txtMultiEpisodePattern").addEventListener("change",updateMultiEpisodePatternHelp),view.querySelector("#txtMultiEpisodePattern").addEventListener("keyup",updateMultiEpisodePatternHelp),view.querySelector("#btnSelectWatchFolder").addEventListener("click",selectWatchFolder),view.querySelector(".libraryFileOrganizerForm").addEventListener("submit",function(e){return e.preventDefault(),onSubmit(view),!1}),view.addEventListener("viewshow",function(e){LibraryMenu.setTabs("autoorganize",1,getTabs),ApiClient.getNamedConfiguration("autoorganize").then(function(config){loadPage(view,config),updateSeasonPatternHelp(),updateEpisodePatternHelp(),updateMultiEpisodePatternHelp()})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/cinemamodeconfiguration.js b/dashboard-ui/dashboard/cinemamodeconfiguration.js index af7db3f802..ccdf9ac533 100644 --- a/dashboard-ui/dashboard/cinemamodeconfiguration.js +++ b/dashboard-ui/dashboard/cinemamodeconfiguration.js @@ -1,144 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function loadPage(page, config) { - - $('.chkMovies', page).checked(config.EnableIntrosForMovies); - $('.chkEpisodes', page).checked(config.EnableIntrosForEpisodes); - - $('.chkMyMovieTrailers', page).checked(config.EnableIntrosFromMoviesInLibrary); - - $('.chkUpcomingTheaterTrailers', page).checked(config.EnableIntrosFromUpcomingTrailers); - $('.chkUpcomingDvdTrailers', page).checked(config.EnableIntrosFromUpcomingDvdMovies); - $('.chkUpcomingStreamingTrailers', page).checked(config.EnableIntrosFromUpcomingStreamingMovies); - $('.chkOtherTrailers', page).checked(config.EnableIntrosFromSimilarMovies); - - $('.chkUnwatchedOnly', page).checked(!config.EnableIntrosForWatchedContent); - $('.chkEnableParentalControl', page).checked(config.EnableIntrosParentalControl); - - $('#txtCustomIntrosPath', page).val(config.CustomIntroPath || ''); - $('#txtCodecIntrosPath', page).val(config.MediaInfoIntroPath || ''); - $('#txtNumTrailers', page).val(config.TrailerLimit); - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - var page = $(form).parents('.page'); - - ApiClient.getNamedConfiguration("cinemamode").then(function (config) { - - config.CustomIntroPath = $('#txtCustomIntrosPath', page).val(); - config.MediaInfoIntroPath = $('#txtCodecIntrosPath', page).val(); - config.TrailerLimit = $('#txtNumTrailers', page).val(); - - config.EnableIntrosForMovies = $('.chkMovies', page).checked(); - config.EnableIntrosForEpisodes = $('.chkEpisodes', page).checked(); - config.EnableIntrosFromMoviesInLibrary = $('.chkMyMovieTrailers', page).checked(); - config.EnableIntrosForWatchedContent = !$('.chkUnwatchedOnly', page).checked(); - config.EnableIntrosParentalControl = $('.chkEnableParentalControl', page).checked(); - - config.EnableIntrosFromUpcomingTrailers = $('.chkUpcomingTheaterTrailers', page).checked(); - config.EnableIntrosFromUpcomingDvdMovies = $('.chkUpcomingDvdTrailers', page).checked(); - config.EnableIntrosFromUpcomingStreamingMovies = $('.chkUpcomingStreamingTrailers', page).checked(); - config.EnableIntrosFromSimilarMovies = $('.chkOtherTrailers', page).checked(); - - ApiClient.updateNamedConfiguration("cinemamode", config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'cinemamodeconfiguration.html', - name: Globalize.translate('TabCinemaMode') - }, - { - href: 'playbackconfiguration.html', - name: Globalize.translate('TabResumeSettings') - }, - { - href: 'streamingsettings.html', - name: Globalize.translate('TabStreaming') - }]; - } - - $(document).on('pageinit', "#cinemaModeConfigurationPage", function () { - - var page = this; - - $('#btnSelectCustomIntrosPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - $('#txtCustomIntrosPath', page).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectCustomIntrosPath') - }); - }); - }); - - $('#btnSelectCodecIntrosPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - $('#txtCodecIntrosPath', page).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectCodecIntrosPath') - }); - }); - }); - - $('.cinemaModeConfigurationForm').off('submit', onSubmit).on('submit', onSubmit); - - if (!AppInfo.enableSupporterMembership) { - page.querySelector('.lnkSupporterLearnMore').href = '#'; - page.querySelector('.lnkSupporterLearnMore').addEventListener('click', function (e) { - e.preventDefault(); - return false; - }); - } - - }).on('pageshow', "#cinemaModeConfigurationPage", function () { - - LibraryMenu.setTabs('playback', 0, getTabs); - - Dashboard.showLoadingMsg(); - - var page = this; - - ApiClient.getNamedConfiguration("cinemamode").then(function (config) { - - loadPage(page, config); - - }); - }); - -}); +define(["jQuery","fnchecked"],function($){"use strict";function loadPage(page,config){$(".chkMovies",page).checked(config.EnableIntrosForMovies),$(".chkEpisodes",page).checked(config.EnableIntrosForEpisodes),$(".chkMyMovieTrailers",page).checked(config.EnableIntrosFromMoviesInLibrary),$(".chkUpcomingTheaterTrailers",page).checked(config.EnableIntrosFromUpcomingTrailers),$(".chkUpcomingDvdTrailers",page).checked(config.EnableIntrosFromUpcomingDvdMovies),$(".chkUpcomingStreamingTrailers",page).checked(config.EnableIntrosFromUpcomingStreamingMovies),$(".chkOtherTrailers",page).checked(config.EnableIntrosFromSimilarMovies),$(".chkUnwatchedOnly",page).checked(!config.EnableIntrosForWatchedContent),$(".chkEnableParentalControl",page).checked(config.EnableIntrosParentalControl),$("#txtCustomIntrosPath",page).val(config.CustomIntroPath||""),$("#txtCodecIntrosPath",page).val(config.MediaInfoIntroPath||""),$("#txtNumTrailers",page).val(config.TrailerLimit),Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this,page=$(form).parents(".page");return ApiClient.getNamedConfiguration("cinemamode").then(function(config){config.CustomIntroPath=$("#txtCustomIntrosPath",page).val(),config.MediaInfoIntroPath=$("#txtCodecIntrosPath",page).val(),config.TrailerLimit=$("#txtNumTrailers",page).val(),config.EnableIntrosForMovies=$(".chkMovies",page).checked(),config.EnableIntrosForEpisodes=$(".chkEpisodes",page).checked(),config.EnableIntrosFromMoviesInLibrary=$(".chkMyMovieTrailers",page).checked(),config.EnableIntrosForWatchedContent=!$(".chkUnwatchedOnly",page).checked(),config.EnableIntrosParentalControl=$(".chkEnableParentalControl",page).checked(),config.EnableIntrosFromUpcomingTrailers=$(".chkUpcomingTheaterTrailers",page).checked(),config.EnableIntrosFromUpcomingDvdMovies=$(".chkUpcomingDvdTrailers",page).checked(),config.EnableIntrosFromUpcomingStreamingMovies=$(".chkUpcomingStreamingTrailers",page).checked(),config.EnableIntrosFromSimilarMovies=$(".chkOtherTrailers",page).checked(),ApiClient.updateNamedConfiguration("cinemamode",config).then(Dashboard.processServerConfigurationUpdateResult)}),!1}function getTabs(){return[{href:"cinemamodeconfiguration.html",name:Globalize.translate("TabCinemaMode")},{href:"playbackconfiguration.html",name:Globalize.translate("TabResumeSettings")},{href:"streamingsettings.html",name:Globalize.translate("TabStreaming")}]}$(document).on("pageinit","#cinemaModeConfigurationPage",function(){var page=this;$("#btnSelectCustomIntrosPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtCustomIntrosPath",page).val(path),picker.close()},header:Globalize.translate("HeaderSelectCustomIntrosPath")})})}),$("#btnSelectCodecIntrosPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtCodecIntrosPath",page).val(path),picker.close()},header:Globalize.translate("HeaderSelectCodecIntrosPath")})})}),$(".cinemaModeConfigurationForm").off("submit",onSubmit).on("submit",onSubmit),AppInfo.enableSupporterMembership||(page.querySelector(".lnkSupporterLearnMore").href="#",page.querySelector(".lnkSupporterLearnMore").addEventListener("click",function(e){return e.preventDefault(),!1}))}).on("pageshow","#cinemaModeConfigurationPage",function(){LibraryMenu.setTabs("playback",0,getTabs),Dashboard.showLoadingMsg();var page=this;ApiClient.getNamedConfiguration("cinemamode").then(function(config){loadPage(page,config)})})}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/dashboardgeneral.js b/dashboard-ui/dashboard/dashboardgeneral.js index c3e6c26407..cbfede87bd 100644 --- a/dashboard-ui/dashboard/dashboardgeneral.js +++ b/dashboard-ui/dashboard/dashboardgeneral.js @@ -1,158 +1 @@ -define(['jQuery', 'fnchecked', 'emby-checkbox', 'emby-collapse', 'emby-textarea', 'emby-input', 'emby-select'], function ($) { - 'use strict'; - - var brandingConfigKey = "branding"; - var currentBrandingOptions; - - var currentLanguage; - - function loadPage(page, config, languageOptions, systemInfo) { - - var os = systemInfo.OperatingSystem.toLowerCase(); - - if (os.indexOf('windows') != -1) { - $('#windowsStartupDescription', page).show(); - } else { - $('#windowsStartupDescription', page).hide(); - } - - if (systemInfo.SupportsAutoRunAtStartup) { - $('#fldRunAtStartup', page).show(); - } else { - $('#fldRunAtStartup', page).hide(); - } - - page.querySelector('#txtCachePath').value = config.CachePath || ''; - - $('#selectLocalizationLanguage', page).html(languageOptions.map(function (l) { - - return ''; - - })).val(config.UICulture); - - currentLanguage = config.UICulture; - $('#chkUsageData', page).checked(config.EnableAnonymousUsageReporting); - $('#chkRunAtStartup', page).checked(config.RunAtStartup); - - if (systemInfo.CanSelfUpdate) { - $('.fldAutomaticUpdates', page).show(); - } else { - $('.fldAutomaticUpdates', page).hide(); - } - - $('#chkEnableAutomaticServerUpdates', page).checked(config.EnableAutoUpdate); - $('#chkEnableAutomaticRestart', page).checked(config.EnableAutomaticRestart); - - if (systemInfo.CanSelfRestart) { - $('#fldEnableAutomaticRestart', page).show(); - } else { - $('#fldEnableAutomaticRestart', page).hide(); - } - - if (systemInfo.CanSelfRestart || systemInfo.CanSelfUpdate) { - $('.autoUpdatesContainer', page).removeClass('hide'); - } else { - $('.autoUpdatesContainer', page).addClass('hide'); - } - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - var page = $(form).parents('.page'); - - ApiClient.getServerConfiguration().then(function (config) { - - config.UICulture = $('#selectLocalizationLanguage', form).val(); - - config.CachePath = form.querySelector('#txtCachePath').value; - - var requiresReload = false; - - if (config.UICulture != currentLanguage) { - requiresReload = true; - } - - config.EnableAnonymousUsageReporting = $('#chkUsageData', form).checked(); - config.RunAtStartup = $('#chkRunAtStartup', form).checked(); - - config.EnableAutomaticRestart = $('#chkEnableAutomaticRestart', form).checked(); - config.EnableAutoUpdate = $('#chkEnableAutomaticServerUpdates', form).checked(); - - ApiClient.updateServerConfiguration(config).then(function () { - - ApiClient.getNamedConfiguration(brandingConfigKey).then(function (brandingConfig) { - - brandingConfig.LoginDisclaimer = form.querySelector('#txtLoginDisclaimer').value; - brandingConfig.CustomCss = form.querySelector('#txtCustomCss').value; - - if (currentBrandingOptions && brandingConfig.CustomCss != currentBrandingOptions.CustomCss) { - requiresReload = true; - } - - ApiClient.updateNamedConfiguration(brandingConfigKey, brandingConfig).then(Dashboard.processServerConfigurationUpdateResult); - - if (requiresReload && !AppInfo.isNativeApp) { - window.location.reload(true); - } - }); - - }); - }); - - // Disable default form submission - return false; - } - - return function (view, params) { - - $('#btnSelectCachePath', view).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - view.querySelector('#txtCachePath').value = path; - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectServerCachePath'), - - instruction: Globalize.translate('HeaderSelectServerCachePathHelp') - }); - }); - }); - - $('.dashboardGeneralForm', view).off('submit', onSubmit).on('submit', onSubmit); - - view.addEventListener('viewshow', function () { - - var promise1 = ApiClient.getServerConfiguration(); - var promise2 = ApiClient.getJSON(ApiClient.getUrl("Localization/Options")); - var promise3 = ApiClient.getSystemInfo(); - - Promise.all([promise1, promise2, promise3]).then(function (responses) { - - loadPage(view, responses[0], responses[1], responses[2]); - - }); - - ApiClient.getNamedConfiguration(brandingConfigKey).then(function (config) { - - currentBrandingOptions = config; - - view.querySelector('#txtLoginDisclaimer').value = config.LoginDisclaimer || ''; - view.querySelector('#txtCustomCss').value = config.CustomCss || ''; - }); - }); - }; -}); +define(["jQuery","fnchecked","emby-checkbox","emby-collapse","emby-textarea","emby-input","emby-select"],function($){"use strict";function loadPage(page,config,languageOptions,systemInfo){var os=systemInfo.OperatingSystem.toLowerCase();os.indexOf("windows")!=-1?$("#windowsStartupDescription",page).show():$("#windowsStartupDescription",page).hide(),systemInfo.SupportsAutoRunAtStartup?$("#fldRunAtStartup",page).show():$("#fldRunAtStartup",page).hide(),page.querySelector("#txtCachePath").value=config.CachePath||"",$("#selectLocalizationLanguage",page).html(languageOptions.map(function(l){return'"})).val(config.UICulture),currentLanguage=config.UICulture,$("#chkUsageData",page).checked(config.EnableAnonymousUsageReporting),$("#chkRunAtStartup",page).checked(config.RunAtStartup),systemInfo.CanSelfUpdate?$(".fldAutomaticUpdates",page).show():$(".fldAutomaticUpdates",page).hide(),$("#chkEnableAutomaticServerUpdates",page).checked(config.EnableAutoUpdate),$("#chkEnableAutomaticRestart",page).checked(config.EnableAutomaticRestart),systemInfo.CanSelfRestart?$("#fldEnableAutomaticRestart",page).show():$("#fldEnableAutomaticRestart",page).hide(),systemInfo.CanSelfRestart||systemInfo.CanSelfUpdate?$(".autoUpdatesContainer",page).removeClass("hide"):$(".autoUpdatesContainer",page).addClass("hide"),Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this;$(form).parents(".page");return ApiClient.getServerConfiguration().then(function(config){config.UICulture=$("#selectLocalizationLanguage",form).val(),config.CachePath=form.querySelector("#txtCachePath").value;var requiresReload=!1;config.UICulture!=currentLanguage&&(requiresReload=!0),config.EnableAnonymousUsageReporting=$("#chkUsageData",form).checked(),config.RunAtStartup=$("#chkRunAtStartup",form).checked(),config.EnableAutomaticRestart=$("#chkEnableAutomaticRestart",form).checked(),config.EnableAutoUpdate=$("#chkEnableAutomaticServerUpdates",form).checked(),ApiClient.updateServerConfiguration(config).then(function(){ApiClient.getNamedConfiguration(brandingConfigKey).then(function(brandingConfig){brandingConfig.LoginDisclaimer=form.querySelector("#txtLoginDisclaimer").value,brandingConfig.CustomCss=form.querySelector("#txtCustomCss").value,currentBrandingOptions&&brandingConfig.CustomCss!=currentBrandingOptions.CustomCss&&(requiresReload=!0),ApiClient.updateNamedConfiguration(brandingConfigKey,brandingConfig).then(Dashboard.processServerConfigurationUpdateResult),requiresReload&&!AppInfo.isNativeApp&&window.location.reload(!0)})})}),!1}var currentBrandingOptions,currentLanguage,brandingConfigKey="branding";return function(view,params){$("#btnSelectCachePath",view).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&(view.querySelector("#txtCachePath").value=path),picker.close()},header:Globalize.translate("HeaderSelectServerCachePath"),instruction:Globalize.translate("HeaderSelectServerCachePathHelp")})})}),$(".dashboardGeneralForm",view).off("submit",onSubmit).on("submit",onSubmit),view.addEventListener("viewshow",function(){var promise1=ApiClient.getServerConfiguration(),promise2=ApiClient.getJSON(ApiClient.getUrl("Localization/Options")),promise3=ApiClient.getSystemInfo();Promise.all([promise1,promise2,promise3]).then(function(responses){loadPage(view,responses[0],responses[1],responses[2])}),ApiClient.getNamedConfiguration(brandingConfigKey).then(function(config){currentBrandingOptions=config,view.querySelector("#txtLoginDisclaimer").value=config.LoginDisclaimer||"",view.querySelector("#txtCustomCss").value=config.CustomCss||""})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/dashboardhosting.js b/dashboard-ui/dashboard/dashboardhosting.js index cebbc67eae..dbce604b08 100644 --- a/dashboard-ui/dashboard/dashboardhosting.js +++ b/dashboard-ui/dashboard/dashboardhosting.js @@ -1,139 +1 @@ -define(['jQuery', 'fnchecked', 'emby-checkbox'], function ($) { - 'use strict'; - - function onSubmit() { - var form = this; - var localAddress = form.querySelector('#txtLocalAddress').value; - var enableUpnp = $('#chkEnableUpnp', form).checked(); - - confirmSelections(localAddress, enableUpnp, function () { - - Dashboard.showLoadingMsg(); - - ApiClient.getServerConfiguration().then(function (config) { - - config.HttpServerPortNumber = $('#txtPortNumber', form).val(); - config.PublicPort = $('#txtPublicPort', form).val(); - config.PublicHttpsPort = $('#txtPublicHttpsPort', form).val(); - config.EnableHttps = $('#chkEnableHttps', form).checked(); - config.HttpsPortNumber = $('#txtHttpsPort', form).val(); - config.EnableUPnP = enableUpnp; - config.WanDdns = $('#txtDdns', form).val(); - config.CertificatePath = $('#txtCertificatePath', form).val(); - - config.LocalNetworkAddresses = localAddress ? [localAddress] : []; - - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult, Dashboard.processErrorResponse); - }); - }); - - // Disable default form submission - return false; - } - - function confirmSelections(localAddress, enableUpnp, callback) { - - if (localAddress || !enableUpnp) { - - require(['alert'], function (alert) { - alert({ - title: Globalize.translate('TitleHostingSettings'), - text: Globalize.translate('SettingsWarning') - }).then(callback); - }); - - } else { - callback(); - } - } - - function getTabs() { - return [ - { - href: 'dashboardhosting.html', - name: Globalize.translate('TabHosting') - }, - { - href: 'serversecurity.html', - name: Globalize.translate('TabSecurity') - }]; - } - - return function (view, params) { - - var self = this; - - function loadPage(page, config) { - - $('#txtPortNumber', page).val(config.HttpServerPortNumber); - $('#txtPublicPort', page).val(config.PublicPort); - $('#txtPublicHttpsPort', page).val(config.PublicHttpsPort); - - page.querySelector('#txtLocalAddress').value = config.LocalNetworkAddresses[0] || ''; - - var chkEnableHttps = page.querySelector('#chkEnableHttps'); - chkEnableHttps.checked = config.EnableHttps; - - $('#txtHttpsPort', page).val(config.HttpsPortNumber); - - $('#txtDdns', page).val(config.WanDdns || ''); - - var txtCertificatePath = page.querySelector('#txtCertificatePath'); - txtCertificatePath.value = config.CertificatePath || ''; - - $('#chkEnableUpnp', page).checked(config.EnableUPnP); - - onCertPathChange.call(txtCertificatePath); - - Dashboard.hideLoadingMsg(); - } - - function onCertPathChange() { - - if (this.value) { - view.querySelector('#txtDdns').setAttribute('required', 'required'); - } else { - view.querySelector('#txtDdns').removeAttribute('required'); - } - } - - $('#btnSelectCertPath', view).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - includeFiles: true, - includeDirectories: true, - - callback: function (path) { - - if (path) { - $('#txtCertificatePath', view).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectCertificatePath') - }); - }); - }); - - $('.dashboardHostingForm').off('submit', onSubmit).on('submit', onSubmit); - - view.querySelector('#txtCertificatePath').addEventListener('change', onCertPathChange); - - view.addEventListener('viewshow', function (e) { - LibraryMenu.setTabs('adminadvanced', 0, getTabs); - Dashboard.showLoadingMsg(); - - ApiClient.getServerConfiguration().then(function (config) { - - loadPage(view, config); - - }); - }); - }; -}); +define(["jQuery","fnchecked","emby-checkbox"],function($){"use strict";function onSubmit(){var form=this,localAddress=form.querySelector("#txtLocalAddress").value,enableUpnp=$("#chkEnableUpnp",form).checked();return confirmSelections(localAddress,enableUpnp,function(){Dashboard.showLoadingMsg(),ApiClient.getServerConfiguration().then(function(config){config.HttpServerPortNumber=$("#txtPortNumber",form).val(),config.PublicPort=$("#txtPublicPort",form).val(),config.PublicHttpsPort=$("#txtPublicHttpsPort",form).val(),config.EnableHttps=$("#chkEnableHttps",form).checked(),config.HttpsPortNumber=$("#txtHttpsPort",form).val(),config.EnableUPnP=enableUpnp,config.WanDdns=$("#txtDdns",form).val(),config.CertificatePath=$("#txtCertificatePath",form).val(),config.LocalNetworkAddresses=localAddress?[localAddress]:[],ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult,Dashboard.processErrorResponse)})}),!1}function confirmSelections(localAddress,enableUpnp,callback){localAddress||!enableUpnp?require(["alert"],function(alert){alert({title:Globalize.translate("TitleHostingSettings"),text:Globalize.translate("SettingsWarning")}).then(callback)}):callback()}function getTabs(){return[{href:"dashboardhosting.html",name:Globalize.translate("TabHosting")},{href:"serversecurity.html",name:Globalize.translate("TabSecurity")}]}return function(view,params){function loadPage(page,config){$("#txtPortNumber",page).val(config.HttpServerPortNumber),$("#txtPublicPort",page).val(config.PublicPort),$("#txtPublicHttpsPort",page).val(config.PublicHttpsPort),page.querySelector("#txtLocalAddress").value=config.LocalNetworkAddresses[0]||"";var chkEnableHttps=page.querySelector("#chkEnableHttps");chkEnableHttps.checked=config.EnableHttps,$("#txtHttpsPort",page).val(config.HttpsPortNumber),$("#txtDdns",page).val(config.WanDdns||"");var txtCertificatePath=page.querySelector("#txtCertificatePath");txtCertificatePath.value=config.CertificatePath||"",$("#chkEnableUpnp",page).checked(config.EnableUPnP),onCertPathChange.call(txtCertificatePath),Dashboard.hideLoadingMsg()}function onCertPathChange(){this.value?view.querySelector("#txtDdns").setAttribute("required","required"):view.querySelector("#txtDdns").removeAttribute("required")}$("#btnSelectCertPath",view).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({includeFiles:!0,includeDirectories:!0,callback:function(path){path&&$("#txtCertificatePath",view).val(path),picker.close()},header:Globalize.translate("HeaderSelectCertificatePath")})})}),$(".dashboardHostingForm").off("submit",onSubmit).on("submit",onSubmit),view.querySelector("#txtCertificatePath").addEventListener("change",onCertPathChange),view.addEventListener("viewshow",function(e){LibraryMenu.setTabs("adminadvanced",0,getTabs),Dashboard.showLoadingMsg(),ApiClient.getServerConfiguration().then(function(config){loadPage(view,config)})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/devicesupload.js b/dashboard-ui/dashboard/devicesupload.js index 281582dd05..4980fc3b50 100644 --- a/dashboard-ui/dashboard/devicesupload.js +++ b/dashboard-ui/dashboard/devicesupload.js @@ -1,101 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function load(page, config) { - - $('#txtUploadPath', page).val(config.CameraUploadPath || ''); - - $('#chkSubfolder', page).checked(config.EnableCameraUploadSubfolders); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getNamedConfiguration("devices").then(function (config) { - load(page, config); - - Dashboard.hideLoadingMsg(); - }); - } - - function save(page) { - - ApiClient.getNamedConfiguration("devices").then(function (config) { - - config.CameraUploadPath = $('#txtUploadPath', page).val(); - - config.EnableCameraUploadSubfolders = $('#chkSubfolder', page).checked(); - - ApiClient.updateNamedConfiguration("devices", config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - } - - function onSubmit() { - var form = this; - var page = $(form).parents('.page'); - - save(page); - - return false; - } - - function getTabs() { - return [ - { - href: 'syncactivity.html', - name: Globalize.translate('TabSyncJobs') - }, - { - href: 'devicesupload.html', - name: Globalize.translate('TabCameraUpload') - }, - { - href: 'appservices.html?context=sync', - name: Globalize.translate('TabServices') - }, - { - href: 'syncsettings.html', - name: Globalize.translate('TabSettings') - }]; - } - - $(document).on('pageinit', "#devicesUploadPage", function () { - - var page = this; - - $('#btnSelectUploadPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - $('#txtUploadPath', page).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectUploadPath') - }); - }); - }); - - $('.devicesUploadForm').off('submit', onSubmit).on('submit', onSubmit); - - - }).on('pageshow', "#devicesUploadPage", function () { - - LibraryMenu.setTabs('syncadmin', 1, getTabs); - var page = this; - - loadData(page); - - }); - -}); \ No newline at end of file +define(["jQuery","fnchecked"],function($){"use strict";function load(page,config){$("#txtUploadPath",page).val(config.CameraUploadPath||""),$("#chkSubfolder",page).checked(config.EnableCameraUploadSubfolders)}function loadData(page){Dashboard.showLoadingMsg(),ApiClient.getNamedConfiguration("devices").then(function(config){load(page,config),Dashboard.hideLoadingMsg()})}function save(page){ApiClient.getNamedConfiguration("devices").then(function(config){config.CameraUploadPath=$("#txtUploadPath",page).val(),config.EnableCameraUploadSubfolders=$("#chkSubfolder",page).checked(),ApiClient.updateNamedConfiguration("devices",config).then(Dashboard.processServerConfigurationUpdateResult)})}function onSubmit(){var form=this,page=$(form).parents(".page");return save(page),!1}function getTabs(){return[{href:"syncactivity.html",name:Globalize.translate("TabSyncJobs")},{href:"devicesupload.html",name:Globalize.translate("TabCameraUpload")},{href:"appservices.html?context=sync",name:Globalize.translate("TabServices")},{href:"syncsettings.html",name:Globalize.translate("TabSettings")}]}$(document).on("pageinit","#devicesUploadPage",function(){var page=this;$("#btnSelectUploadPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtUploadPath",page).val(path),picker.close()},header:Globalize.translate("HeaderSelectUploadPath")})})}),$(".devicesUploadForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#devicesUploadPage",function(){LibraryMenu.setTabs("syncadmin",1,getTabs);var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/librarydisplay.js b/dashboard-ui/dashboard/librarydisplay.js index f1672d2c8f..8a5482b966 100644 --- a/dashboard-ui/dashboard/librarydisplay.js +++ b/dashboard-ui/dashboard/librarydisplay.js @@ -1,70 +1 @@ -define(['globalize', 'emby-checkbox', 'emby-button'], function (globalize) { - 'use strict'; - - function getTabs() { - return [ - { - href: 'library.html', - name: Globalize.translate('HeaderLibraries') - }, - { - href: 'librarydisplay.html', - name: Globalize.translate('TabDisplay') - }, - { - href: 'metadataimages.html', - name: Globalize.translate('TabMetadata') - }, - { - href: 'metadatanfo.html', - name: Globalize.translate('TabNfoSettings') - }, - { - href: 'librarysettings.html', - name: Globalize.translate('TabAdvanced') - }]; - } - - return function (view, params) { - - var self = this; - - view.querySelector('form').addEventListener('submit', function (e) { - - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getServerConfiguration().then(function (config) { - - config.EnableFolderView = form.querySelector('.chkFolderView').checked; - config.EnableGroupingIntoCollections = form.querySelector('.chkGroupMoviesIntoCollections').checked; - config.DisplaySpecialsWithinSeasons = form.querySelector('.chkDisplaySpecialsWithinSeasons').checked; - config.DisplayCollectionsView = form.querySelector('.chkDisplayCollectionView').checked; - config.EnableChannelView = !form.querySelector('.chkDisplayChannelsInline').checked; - config.EnableExternalContentInSuggestions = form.querySelector('.chkExternalContentInSuggestions').checked; - - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - e.preventDefault(); - return false; - }); - - function loadData() { - ApiClient.getServerConfiguration().then(function (config) { - view.querySelector('.chkFolderView').checked = config.EnableFolderView; - view.querySelector('.chkGroupMoviesIntoCollections').checked = config.EnableGroupingIntoCollections; - view.querySelector('.chkDisplaySpecialsWithinSeasons').checked = config.DisplaySpecialsWithinSeasons; - view.querySelector('.chkDisplayCollectionView').checked = config.DisplayCollectionsView; - view.querySelector('.chkDisplayChannelsInline').checked = !(config.EnableChannelView || false); - view.querySelector('.chkExternalContentInSuggestions').checked = config.EnableExternalContentInSuggestions; - }); - } - - view.addEventListener('viewshow', function () { - LibraryMenu.setTabs('librarysetup', 1, getTabs); - loadData(); - }); - }; -}); \ No newline at end of file +define(["globalize","emby-checkbox","emby-button"],function(globalize){"use strict";function getTabs(){return[{href:"library.html",name:Globalize.translate("HeaderLibraries")},{href:"librarydisplay.html",name:Globalize.translate("TabDisplay")},{href:"metadataimages.html",name:Globalize.translate("TabMetadata")},{href:"metadatanfo.html",name:Globalize.translate("TabNfoSettings")},{href:"librarysettings.html",name:Globalize.translate("TabAdvanced")}]}return function(view,params){function loadData(){ApiClient.getServerConfiguration().then(function(config){view.querySelector(".chkFolderView").checked=config.EnableFolderView,view.querySelector(".chkGroupMoviesIntoCollections").checked=config.EnableGroupingIntoCollections,view.querySelector(".chkDisplaySpecialsWithinSeasons").checked=config.DisplaySpecialsWithinSeasons,view.querySelector(".chkDisplayCollectionView").checked=config.DisplayCollectionsView,view.querySelector(".chkDisplayChannelsInline").checked=!config.EnableChannelView,view.querySelector(".chkExternalContentInSuggestions").checked=config.EnableExternalContentInSuggestions})}view.querySelector("form").addEventListener("submit",function(e){Dashboard.showLoadingMsg();var form=this;return ApiClient.getServerConfiguration().then(function(config){config.EnableFolderView=form.querySelector(".chkFolderView").checked,config.EnableGroupingIntoCollections=form.querySelector(".chkGroupMoviesIntoCollections").checked,config.DisplaySpecialsWithinSeasons=form.querySelector(".chkDisplaySpecialsWithinSeasons").checked,config.DisplayCollectionsView=form.querySelector(".chkDisplayCollectionView").checked,config.EnableChannelView=!form.querySelector(".chkDisplayChannelsInline").checked,config.EnableExternalContentInSuggestions=form.querySelector(".chkExternalContentInSuggestions").checked,ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult)}),e.preventDefault(),!1}),view.addEventListener("viewshow",function(){LibraryMenu.setTabs("librarysetup",1,getTabs),loadData()})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/librarysettings.js b/dashboard-ui/dashboard/librarysettings.js index 39719fb834..434ec8bd4f 100644 --- a/dashboard-ui/dashboard/librarysettings.js +++ b/dashboard-ui/dashboard/librarysettings.js @@ -1,161 +1 @@ -define(['jQuery', 'fnchecked', 'emby-checkbox'], function ($) { - 'use strict'; - - function loadPage(page, config) { - - if (config.MergeMetadataAndImagesByName) { - $('.fldImagesByName', page).hide(); - } else { - $('.fldImagesByName', page).show(); - } - - $('#txtSeasonZeroName', page).val(config.SeasonZeroDisplayName); - - $('#chkSaveMetadataHidden', page).checked(config.SaveMetadataHidden); - - $('#txtMetadataPath', page).val(config.MetadataPath || ''); - $('#txtMetadataNetworkPath', page).val(config.MetadataNetworkPath || ''); - - Dashboard.hideLoadingMsg(); - } - - function loadMetadataConfig(page, config) { - - $('#selectDateAdded', page).val((config.UseFileCreationTimeForDateAdded ? '1' : '0')); - } - - function loadFanartConfig(page, config) { - - $('#txtFanartApiKey', page).val(config.UserApiKey || ''); - } - - function saveFanart(form) { - - ApiClient.getNamedConfiguration("fanart").then(function (config) { - - config.UserApiKey = $('#txtFanartApiKey', form).val(); - - ApiClient.updateNamedConfiguration("fanart", config); - }); - } - - function saveMetadata(form) { - - ApiClient.getNamedConfiguration("metadata").then(function (config) { - - config.UseFileCreationTimeForDateAdded = $('#selectDateAdded', form).val() == '1'; - - ApiClient.updateNamedConfiguration("metadata", config); - }); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getServerConfiguration().then(function (config) { - - config.SeasonZeroDisplayName = $('#txtSeasonZeroName', form).val(); - - config.SaveMetadataHidden = $('#chkSaveMetadataHidden', form).checked(); - - config.EnableTvDbUpdates = $('#chkEnableTvdbUpdates', form).checked(); - config.EnableTmdbUpdates = $('#chkEnableTmdbUpdates', form).checked(); - config.EnableFanArtUpdates = $('#chkEnableFanartUpdates', form).checked(); - config.MetadataPath = $('#txtMetadataPath', form).val(); - config.MetadataNetworkPath = $('#txtMetadataNetworkPath', form).val(); - config.FanartApiKey = $('#txtFanartApiKey', form).val(); - - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - saveMetadata(form); - saveFanart(form); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'library.html', - name: Globalize.translate('HeaderLibraries') - }, - { - href: 'librarydisplay.html', - name: Globalize.translate('TabDisplay') - }, - { - href: 'metadataimages.html', - name: Globalize.translate('TabMetadata') - }, - { - href: 'metadatanfo.html', - name: Globalize.translate('TabNfoSettings') - }, - { - href: 'librarysettings.html', - name: Globalize.translate('TabAdvanced') - }]; - } - - return function (view, params) { - - var self = this; - - $('#btnSelectMetadataPath', view).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - path: $('#txtMetadataPath', view).val(), - networkSharePath: $('#txtMetadataNetworkPath', view).val(), - callback: function (path, networkPath) { - if (path) { - $('#txtMetadataPath', view).val(path); - $('#txtMetadataNetworkPath', view).val(networkPath); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectMetadataPath'), - - instruction: Globalize.translate('HeaderSelectMetadataPathHelp'), - - enableNetworkSharePath: true - }); - }); - - }); - - $('.librarySettingsForm').off('submit', onSubmit).on('submit', onSubmit); - - view.addEventListener('viewshow', function () { - LibraryMenu.setTabs('librarysetup', 4, getTabs); - Dashboard.showLoadingMsg(); - - var page = this; - - ApiClient.getServerConfiguration().then(function (config) { - - loadPage(page, config); - }); - - ApiClient.getNamedConfiguration("metadata").then(function (metadata) { - - loadMetadataConfig(page, metadata); - }); - - ApiClient.getNamedConfiguration("fanart").then(function (metadata) { - - loadFanartConfig(page, metadata); - }); - }); - }; - -}); +define(["jQuery","fnchecked","emby-checkbox"],function($){"use strict";function loadPage(page,config){config.MergeMetadataAndImagesByName?$(".fldImagesByName",page).hide():$(".fldImagesByName",page).show(),$("#txtSeasonZeroName",page).val(config.SeasonZeroDisplayName),$("#chkSaveMetadataHidden",page).checked(config.SaveMetadataHidden),$("#txtMetadataPath",page).val(config.MetadataPath||""),$("#txtMetadataNetworkPath",page).val(config.MetadataNetworkPath||""),Dashboard.hideLoadingMsg()}function loadMetadataConfig(page,config){$("#selectDateAdded",page).val(config.UseFileCreationTimeForDateAdded?"1":"0")}function loadFanartConfig(page,config){$("#txtFanartApiKey",page).val(config.UserApiKey||"")}function saveFanart(form){ApiClient.getNamedConfiguration("fanart").then(function(config){config.UserApiKey=$("#txtFanartApiKey",form).val(),ApiClient.updateNamedConfiguration("fanart",config)})}function saveMetadata(form){ApiClient.getNamedConfiguration("metadata").then(function(config){config.UseFileCreationTimeForDateAdded="1"==$("#selectDateAdded",form).val(),ApiClient.updateNamedConfiguration("metadata",config)})}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getServerConfiguration().then(function(config){config.SeasonZeroDisplayName=$("#txtSeasonZeroName",form).val(),config.SaveMetadataHidden=$("#chkSaveMetadataHidden",form).checked(),config.EnableTvDbUpdates=$("#chkEnableTvdbUpdates",form).checked(),config.EnableTmdbUpdates=$("#chkEnableTmdbUpdates",form).checked(),config.EnableFanArtUpdates=$("#chkEnableFanartUpdates",form).checked(),config.MetadataPath=$("#txtMetadataPath",form).val(),config.MetadataNetworkPath=$("#txtMetadataNetworkPath",form).val(),config.FanartApiKey=$("#txtFanartApiKey",form).val(),ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult)}),saveMetadata(form),saveFanart(form),!1}function getTabs(){return[{href:"library.html",name:Globalize.translate("HeaderLibraries")},{href:"librarydisplay.html",name:Globalize.translate("TabDisplay")},{href:"metadataimages.html",name:Globalize.translate("TabMetadata")},{href:"metadatanfo.html",name:Globalize.translate("TabNfoSettings")},{href:"librarysettings.html",name:Globalize.translate("TabAdvanced")}]}return function(view,params){$("#btnSelectMetadataPath",view).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({path:$("#txtMetadataPath",view).val(),networkSharePath:$("#txtMetadataNetworkPath",view).val(),callback:function(path,networkPath){path&&($("#txtMetadataPath",view).val(path),$("#txtMetadataNetworkPath",view).val(networkPath)),picker.close()},header:Globalize.translate("HeaderSelectMetadataPath"),instruction:Globalize.translate("HeaderSelectMetadataPathHelp"),enableNetworkSharePath:!0})})}),$(".librarySettingsForm").off("submit",onSubmit).on("submit",onSubmit),view.addEventListener("viewshow",function(){LibraryMenu.setTabs("librarysetup",4,getTabs),Dashboard.showLoadingMsg();var page=this;ApiClient.getServerConfiguration().then(function(config){loadPage(page,config)}),ApiClient.getNamedConfiguration("metadata").then(function(metadata){loadMetadataConfig(page,metadata)}),ApiClient.getNamedConfiguration("fanart").then(function(metadata){loadFanartConfig(page,metadata)})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/livetvtunerprovider-satip.js b/dashboard-ui/dashboard/livetvtunerprovider-satip.js index 3897eeb024..5550b6c181 100644 --- a/dashboard-ui/dashboard/livetvtunerprovider-satip.js +++ b/dashboard-ui/dashboard/livetvtunerprovider-satip.js @@ -1,136 +1 @@ -define(['emby-checkbox'], function () { - 'use strict'; - - function reload(page, providerId) { - - page.querySelector('.txtDevicePath').value = ''; - - if (providerId) { - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - var info = config.TunerHosts.filter(function (i) { - return i.Id == providerId; - })[0]; - - page.querySelector('.txtDevicePath').value = info.Url || ''; - page.querySelector('.txtM3uUrl').value = info.M3UUrl || ''; - page.querySelector('.chkEnabled').checked = info.IsEnabled; - }); - } - } - - function fillInfoFromPage(page, info) { - info.Url = page.querySelector('.txtDevicePath').value; - info.M3UUrl = page.querySelector('.txtM3uUrl').value; - info.IsEnabled = page.querySelector('.chkEnabled').checked; - info.DiseqC = page.querySelector('.selectDiseqC').value; - info.SourceA = page.querySelector('.selectSourceA').value; - info.SourceB = page.querySelector('.selectSourceB').value; - info.SourceC = page.querySelector('.selectSourceC').value; - info.SourceD = page.querySelector('.selectSourceD').value; - } - - function submitTunerInfo(page, info) { - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('LiveTv/TunerHosts'), - data: JSON.stringify(info), - contentType: "application/json" - - }).then(function () { - - Dashboard.processServerConfigurationUpdateResult(); - Dashboard.navigate('livetvstatus.html'); - - }, function () { - Dashboard.hideLoadingMsg(); - Dashboard.alert({ - message: Globalize.translate('ErrorSavingTvProvider') - }); - }); - } - - function populateMappings(view) { - - ApiClient.getJSON(ApiClient.getUrl('LiveTv/TunerHosts/Satip/IniMappings')).then(function (mappings) { - - var optionsHtml = mappings.map(function (m) { - return ''; - }).join(''); - - optionsHtml = '' + optionsHtml; - - view.querySelector('.selectSourceA').innerHTML = optionsHtml; - view.querySelector('.selectSourceB').innerHTML = optionsHtml; - view.querySelector('.selectSourceC').innerHTML = optionsHtml; - view.querySelector('.selectSourceD').innerHTML = optionsHtml; - }); - } - - return function (view, params) { - - function submitForm() { - - Dashboard.showLoadingMsg(); - - var id = params.id; - - if (id) { - - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - var info = config.TunerHosts.filter(function (i) { - return i.Id == id; - })[0]; - - fillInfoFromPage(view, info); - submitTunerInfo(view, info); - }); - - } else { - var info = { - Type: 'satip' - }; - - fillInfoFromPage(view, info); - submitTunerInfo(view, info); - } - } - - function onSelectDiseqCChange(e) { - - var select = e.target; - var value = select.value; - - if (value) { - view.querySelector('.fldSourceB').classList.remove('hide'); - } else { - view.querySelector('.fldSourceB').classList.add('hide'); - } - - if (value == 'diseqc1') { - - view.querySelector('.fldSourceC').classList.remove('hide'); - view.querySelector('.fldSourceD').classList.remove('hide'); - } else { - view.querySelector('.fldSourceC').classList.add('hide'); - view.querySelector('.fldSourceD').classList.add('hide'); - } - } - - view.querySelector('form').addEventListener('submit', function (e) { - submitForm(); - e.preventDefault(); - return false; - }); - - view.querySelector('.selectDiseqC').addEventListener('change', onSelectDiseqCChange); - - populateMappings(view); - - view.addEventListener('viewshow', function (e) { - var providerId = params.id; - reload(view, providerId); - }); - } -}); \ No newline at end of file +define(["emby-checkbox"],function(){"use strict";function reload(page,providerId){page.querySelector(".txtDevicePath").value="",providerId&&ApiClient.getNamedConfiguration("livetv").then(function(config){var info=config.TunerHosts.filter(function(i){return i.Id==providerId})[0];page.querySelector(".txtDevicePath").value=info.Url||"",page.querySelector(".txtM3uUrl").value=info.M3UUrl||"",page.querySelector(".chkEnabled").checked=info.IsEnabled})}function fillInfoFromPage(page,info){info.Url=page.querySelector(".txtDevicePath").value,info.M3UUrl=page.querySelector(".txtM3uUrl").value,info.IsEnabled=page.querySelector(".chkEnabled").checked,info.DiseqC=page.querySelector(".selectDiseqC").value,info.SourceA=page.querySelector(".selectSourceA").value,info.SourceB=page.querySelector(".selectSourceB").value,info.SourceC=page.querySelector(".selectSourceC").value,info.SourceD=page.querySelector(".selectSourceD").value}function submitTunerInfo(page,info){ApiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/TunerHosts"),data:JSON.stringify(info),contentType:"application/json"}).then(function(){Dashboard.processServerConfigurationUpdateResult(),Dashboard.navigate("livetvstatus.html")},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("ErrorSavingTvProvider")})})}function populateMappings(view){ApiClient.getJSON(ApiClient.getUrl("LiveTv/TunerHosts/Satip/IniMappings")).then(function(mappings){var optionsHtml=mappings.map(function(m){return'"}).join("");optionsHtml='"+optionsHtml,view.querySelector(".selectSourceA").innerHTML=optionsHtml,view.querySelector(".selectSourceB").innerHTML=optionsHtml,view.querySelector(".selectSourceC").innerHTML=optionsHtml,view.querySelector(".selectSourceD").innerHTML=optionsHtml})}return function(view,params){function submitForm(){Dashboard.showLoadingMsg();var id=params.id;if(id)ApiClient.getNamedConfiguration("livetv").then(function(config){var info=config.TunerHosts.filter(function(i){return i.Id==id})[0];fillInfoFromPage(view,info),submitTunerInfo(view,info)});else{var info={Type:"satip"};fillInfoFromPage(view,info),submitTunerInfo(view,info)}}function onSelectDiseqCChange(e){var select=e.target,value=select.value;value?view.querySelector(".fldSourceB").classList.remove("hide"):view.querySelector(".fldSourceB").classList.add("hide"),"diseqc1"==value?(view.querySelector(".fldSourceC").classList.remove("hide"),view.querySelector(".fldSourceD").classList.remove("hide")):(view.querySelector(".fldSourceC").classList.add("hide"),view.querySelector(".fldSourceD").classList.add("hide"))}view.querySelector("form").addEventListener("submit",function(e){return submitForm(),e.preventDefault(),!1}),view.querySelector(".selectDiseqC").addEventListener("change",onSelectDiseqCChange),populateMappings(view),view.addEventListener("viewshow",function(e){var providerId=params.id;reload(view,providerId)})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/logpage.js b/dashboard-ui/dashboard/logpage.js index f6c454547c..048bd1e31f 100644 --- a/dashboard-ui/dashboard/logpage.js +++ b/dashboard-ui/dashboard/logpage.js @@ -1,79 +1 @@ -define(['datetime', 'listViewStyle'], function (datetime) { - 'use strict'; - - return function (view, params) { - - view.querySelector('#chkDebugLog').addEventListener('change', function () { - - ApiClient.getServerConfiguration().then(function (config) { - - config.EnableDebugLevelLogging = view.querySelector('#chkDebugLog').checked; - - ApiClient.updateServerConfiguration(config); - }); - }); - - view.addEventListener('viewbeforeshow', function () { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - apiClient.getJSON(apiClient.getUrl('System/Logs')).then(function (logs) { - - var html = ''; - - html += '
'; - - html += logs.map(function (log) { - - var logUrl = apiClient.getUrl('System/Logs/Log', { - name: log.Name - }); - - logUrl += "&api_key=" + apiClient.accessToken(); - - var logHtml = ''; - logHtml += ''; - - return logHtml; - - }) - .join(''); - - html += '
'; - - view.querySelector('.serverLogs').innerHTML = html; - Dashboard.hideLoadingMsg(); - }); - - apiClient.getServerConfiguration().then(function (config) { - - view.querySelector('#chkDebugLog').checked = config.EnableDebugLevelLogging; - }); - }); - - }; -}); \ No newline at end of file +define(["datetime","listViewStyle"],function(datetime){"use strict";return function(view,params){view.querySelector("#chkDebugLog").addEventListener("change",function(){ApiClient.getServerConfiguration().then(function(config){config.EnableDebugLevelLogging=view.querySelector("#chkDebugLog").checked,ApiClient.updateServerConfiguration(config)})}),view.addEventListener("viewbeforeshow",function(){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("System/Logs")).then(function(logs){var html="";html+='
',html+=logs.map(function(log){var logUrl=apiClient.getUrl("System/Logs/Log",{name:log.Name});logUrl+="&api_key="+apiClient.accessToken();var logHtml="";logHtml+='"}).join(""),html+="
",view.querySelector(".serverLogs").innerHTML=html,Dashboard.hideLoadingMsg()}),apiClient.getServerConfiguration().then(function(config){view.querySelector("#chkDebugLog").checked=config.EnableDebugLevelLogging})})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/wizardcomponents.js b/dashboard-ui/dashboard/wizardcomponents.js index fe69bdae58..8707aec0d5 100644 --- a/dashboard-ui/dashboard/wizardcomponents.js +++ b/dashboard-ui/dashboard/wizardcomponents.js @@ -1,145 +1 @@ -define([], function () { - 'use strict'; - - function goNext() { - Dashboard.navigate('wizardagreement.html'); - } - - function loadDownloadInfo(view) { - - var instructions = ''; - - ApiClient.getSystemInfo().then(function (systemInfo) { - - var operatingSystem = systemInfo.OperatingSystem.toLowerCase(); - - if (operatingSystem == 'windows') { - view.querySelector('.fldSelectEncoderPathType').classList.add('hide'); - view.querySelector('.markExec').classList.add('hide'); - } else { - view.querySelector('.fldSelectEncoderPathType').classList.remove('hide'); - view.querySelector('.markExec').classList.remove('hide'); - } - - if (operatingSystem == 'windows' && systemInfo.SystemArchitecture != 'Arm') { - - view.querySelector('.suggestedLocation').innerHTML = Globalize.translate('FFmpegSuggestedDownload', 'https://ffmpeg.zeranoe.com'); - - if (systemInfo.SystemArchitecture == 'X86') { - instructions = 'Download FFmpeg 32-Bit Static'; - } - else if (systemInfo.SystemArchitecture == 'X64') { - instructions = 'Download FFmpeg 64-Bit Static'; - } - - } else if (operatingSystem == 'linux') { - - view.querySelector('.suggestedLocation').innerHTML = Globalize.translate('FFmpegSuggestedDownload', 'http://johnvansickle.com/ffmpeg'); - - if (systemInfo.SystemArchitecture == 'X86') { - instructions = 'Download x86 build'; - } - else if (systemInfo.SystemArchitecture == 'X64') { - instructions = 'Download x86_64 build'; - } - - } else if (operatingSystem == 'osx' && systemInfo.SystemArchitecture == 'X64') { - - view.querySelector('.suggestedLocation').innerHTML = Globalize.translate('FFmpegSuggestedDownload', 'http://evermeet.cx/ffmpeg'); - instructions = 'Download both ffmpeg and ffprobe, and extract them to the same folder.'; - - } else { - view.querySelector('.suggestedLocation').innerHTML = Globalize.translate('FFmpegSuggestedDownload', 'https://ffmpeg.org/download.html'); - } - - view.querySelector('.downloadInstructions').innerHTML = instructions; - - var selectEncoderPath = view.querySelector('#selectEncoderPath'); - selectEncoderPath.value = 'Custom'; - onSelectEncoderPathChange.call(selectEncoderPath); - }); - } - - function onSaveEncodingPathFailure(response) { - - var msg = ''; - - // This is a fallback that handles both 404 and 400 (no path entered) - msg = Globalize.translate('FFmpegSavePathNotFound'); - - require(['alert'], function (alert) { - alert(msg); - }); - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function onSelectEncoderPathChange(e) { - - var page = parentWithClass(this, 'page'); - - if (this.value == 'Custom') { - page.querySelector('.fldEncoderPath').classList.remove('hide'); - } else { - page.querySelector('.fldEncoderPath').classList.add('hide'); - } - } - - return function (view, params) { - - view.querySelector('#btnSelectEncoderPath').addEventListener("click", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - includeFiles: true, - callback: function (path) { - - if (path) { - view.querySelector('.txtEncoderPath').value = path; - } - picker.close(); - } - }); - }); - }); - - view.querySelector('form').addEventListener('submit', function (e) { - - var form = this; - - ApiClient.ajax({ - url: ApiClient.getUrl('System/MediaEncoder/Path'), - type: 'POST', - data: { - Path: form.querySelector('.txtEncoderPath').value, - PathType: 'Custom' - } - }).then(goNext, onSaveEncodingPathFailure); - - e.preventDefault(); - return false; - }); - - view.querySelector('#selectEncoderPath').addEventListener('change', onSelectEncoderPathChange); - - view.addEventListener('viewbeforeshow', function (e) { - - loadDownloadInfo(view); - }); - }; -}); \ No newline at end of file +define([],function(){"use strict";function goNext(){Dashboard.navigate("wizardagreement.html")}function loadDownloadInfo(view){var instructions="";ApiClient.getSystemInfo().then(function(systemInfo){var operatingSystem=systemInfo.OperatingSystem.toLowerCase();"windows"==operatingSystem?(view.querySelector(".fldSelectEncoderPathType").classList.add("hide"),view.querySelector(".markExec").classList.add("hide")):(view.querySelector(".fldSelectEncoderPathType").classList.remove("hide"),view.querySelector(".markExec").classList.remove("hide")),"windows"==operatingSystem&&"Arm"!=systemInfo.SystemArchitecture?(view.querySelector(".suggestedLocation").innerHTML=Globalize.translate("FFmpegSuggestedDownload",'https://ffmpeg.zeranoe.com'),"X86"==systemInfo.SystemArchitecture?instructions="Download FFmpeg 32-Bit Static":"X64"==systemInfo.SystemArchitecture&&(instructions="Download FFmpeg 64-Bit Static")):"linux"==operatingSystem?(view.querySelector(".suggestedLocation").innerHTML=Globalize.translate("FFmpegSuggestedDownload",'http://johnvansickle.com/ffmpeg'),"X86"==systemInfo.SystemArchitecture?instructions="Download x86 build":"X64"==systemInfo.SystemArchitecture&&(instructions="Download x86_64 build")):"osx"==operatingSystem&&"X64"==systemInfo.SystemArchitecture?(view.querySelector(".suggestedLocation").innerHTML=Globalize.translate("FFmpegSuggestedDownload",'http://evermeet.cx/ffmpeg'),instructions="Download both ffmpeg and ffprobe, and extract them to the same folder."):view.querySelector(".suggestedLocation").innerHTML=Globalize.translate("FFmpegSuggestedDownload",'https://ffmpeg.org/download.html'),view.querySelector(".downloadInstructions").innerHTML=instructions;var selectEncoderPath=view.querySelector("#selectEncoderPath");selectEncoderPath.value="Custom",onSelectEncoderPathChange.call(selectEncoderPath)})}function onSaveEncodingPathFailure(response){var msg="";msg=Globalize.translate("FFmpegSavePathNotFound"),require(["alert"],function(alert){alert(msg)})}function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onSelectEncoderPathChange(e){var page=parentWithClass(this,"page");"Custom"==this.value?page.querySelector(".fldEncoderPath").classList.remove("hide"):page.querySelector(".fldEncoderPath").classList.add("hide")}return function(view,params){view.querySelector("#btnSelectEncoderPath").addEventListener("click",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({includeFiles:!0,callback:function(path){path&&(view.querySelector(".txtEncoderPath").value=path),picker.close()}})})}),view.querySelector("form").addEventListener("submit",function(e){var form=this;return ApiClient.ajax({url:ApiClient.getUrl("System/MediaEncoder/Path"),type:"POST",data:{Path:form.querySelector(".txtEncoderPath").value,PathType:"Custom"}}).then(goNext,onSaveEncodingPathFailure),e.preventDefault(),!1}),view.querySelector("#selectEncoderPath").addEventListener("change",onSelectEncoderPathChange),view.addEventListener("viewbeforeshow",function(e){loadDownloadInfo(view)})}}); \ No newline at end of file diff --git a/dashboard-ui/dashboard/wizardfinishpage.js b/dashboard-ui/dashboard/wizardfinishpage.js index a147255c0c..3b5de30ee9 100644 --- a/dashboard-ui/dashboard/wizardfinishpage.js +++ b/dashboard-ui/dashboard/wizardfinishpage.js @@ -1,27 +1 @@ -define(['loading'], function (loading) { - 'use strict'; - - function onFinish() { - - loading.show(); - - ApiClient.ajax({ - - url: ApiClient.getUrl('Startup/Complete'), - type: 'POST' - - }).then(function () { - - Dashboard.navigate('dashboard.html'); - loading.hide(); - }); - } - - return function (view, params) { - - var self = this; - - view.querySelector('.btnWizardNext').addEventListener('click', onFinish); - }; - -}); \ No newline at end of file +define(["loading"],function(loading){"use strict";function onFinish(){loading.show(),ApiClient.ajax({url:ApiClient.getUrl("Startup/Complete"),type:"POST"}).then(function(){Dashboard.navigate("dashboard.html"),loading.hide()})}return function(view,params){view.querySelector(".btnWizardNext").addEventListener("click",onFinish)}}); \ No newline at end of file diff --git a/dashboard-ui/devices/android/android.css b/dashboard-ui/devices/android/android.css index 0e84f3622b..c2a38617c6 100644 --- a/dashboard-ui/devices/android/android.css +++ b/dashboard-ui/devices/android/android.css @@ -1,15 +1 @@ -.libraryMenuButtonText { - font-weight: 500 !important; -} - -@media all and (min-width: 300px) { - - .libraryViewNav, .emby-tabs-slider { - display: flex; - flex-grow: 1; - } - - .emby-tab-button { - flex-grow: 1; - } -} +.libraryMenuButtonText{font-weight:500!important}@media all and (min-width:300px){.emby-tabs-slider,.libraryViewNav{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1}.emby-tab-button{-webkit-box-flex:1;-webkit-flex-grow:1;flex-grow:1}} \ No newline at end of file diff --git a/dashboard-ui/devices/ios/ios.css b/dashboard-ui/devices/ios/ios.css index cebe066a73..35c59fdcca 100644 --- a/dashboard-ui/devices/ios/ios.css +++ b/dashboard-ui/devices/ios/ios.css @@ -1,95 +1 @@ -body:not(.dashboardDocument) .mainDrawerButton { - display: none !important; -} - -.pageWithAbsoluteTabs:not(.noSecondaryNavPage) { - padding-top: 88px !important; -} - -.libraryPage:not(.noSecondaryNavPage) { - padding-top: 85px !important; -} - -.backdropContainer { - /* This isn't implemented right and ends up looking terrible */ - background-attachment: initial; -} - -.viewMenuBar { - /* It needs this in order to retain height since we're positioning the contents absolutely */ - height: 50px; -} - -.ui-body-b .libraryViewNav { - box-shadow: none; -} - -/*.viewMenuBar, .ui-body-b .libraryViewNav { - background: rgba(34,35,38,.90); - -webkit-backdrop-filter: blur(5px); - backdrop-filter: blur(5px); -} - - .viewMenuBar.semiTransparent { - background-color: rgba(15, 15, 15, .3); - }*/ - -.emby-tab-button { - font-weight: 400; - text-transform: none !important; - border-color: transparent !important; - border-width: 0 !important; -} - -.criticReviewPaperList { - background-color: #262626; -} - -.settingsMenuHeader { - display: none; -} - -.libraryMenuButtonText { - font-weight: 500 !important; -} - -.btnNotificationsInner { - font-weight: 400; -} - -.cardImageContainer { - border-radius: 4px; -} - -.sidebarLinkText { - font-weight: 400 !important; -} - -.videoSubtitles { - font-size: 200% !important; -} - -.txtSearch { - padding-bottom: .5em !important; - text-indent: 0 !important; -} - -.searchInputContainer { - margin-left: 5%; - margin-right: 5%; -} - -.categorySyncButton, .btnSync { - display: none !important; -} - -.dialog.background-theme-b { - background: rgba(28,28,28,.84); - -webkit-backdrop-filter: blur(5px); - backdrop-filter: blur(5px); -} - -.cardOverlayButton { - -webkit-backdrop-filter: blur(5px); - backdrop-filter: blur(5px); -} +body:not(.dashboardDocument) .mainDrawerButton{display:none!important}.pageWithAbsoluteTabs:not(.noSecondaryNavPage){padding-top:88px!important}.libraryPage:not(.noSecondaryNavPage){padding-top:85px!important}.backdropContainer{background-attachment:initial}.viewMenuBar{height:50px}.ui-body-b .libraryViewNav{-webkit-box-shadow:none;box-shadow:none}.emby-tab-button{font-weight:400;text-transform:none!important;border-color:transparent!important;border-width:0!important}.criticReviewPaperList{background-color:#262626}.settingsMenuHeader{display:none}.libraryMenuButtonText{font-weight:500!important}.btnNotificationsInner{font-weight:400}.cardImageContainer{-webkit-border-radius:4px;border-radius:4px}.sidebarLinkText{font-weight:400!important}.videoSubtitles{font-size:200%!important}.txtSearch{padding-bottom:.5em!important;text-indent:0!important}.searchInputContainer{margin-left:5%;margin-right:5%}.btnSync,.categorySyncButton{display:none!important}.dialog.background-theme-b{background:rgba(28,28,28,.84);-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)}.cardOverlayButton{-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)} \ No newline at end of file diff --git a/dashboard-ui/legacy/buttonenabled.js b/dashboard-ui/legacy/buttonenabled.js index bd18e22b43..aea7ab8ff8 100644 --- a/dashboard-ui/legacy/buttonenabled.js +++ b/dashboard-ui/legacy/buttonenabled.js @@ -1,8 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - $.fn.buttonEnabled = function (enabled) { - - return enabled ? this.attr('disabled', '').removeAttr('disabled') : this.attr('disabled', 'disabled'); - }; -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";$.fn.buttonEnabled=function(enabled){return enabled?this.attr("disabled","").removeAttr("disabled"):this.attr("disabled","disabled")}}); \ No newline at end of file diff --git a/dashboard-ui/legacy/dashboard.js b/dashboard-ui/legacy/dashboard.js index 399d2f15e1..390f1ae7df 100644 --- a/dashboard-ui/legacy/dashboard.js +++ b/dashboard-ui/legacy/dashboard.js @@ -1,12 +1 @@ -Dashboard.confirm = function (message, title, callback) { - 'use strict'; - - require(['confirm'], function (confirm) { - - confirm(message, title).then(function () { - callback(true); - }, function () { - callback(false); - }); - }); -}; \ No newline at end of file +Dashboard.confirm=function(message,title,callback){"use strict";require(["confirm"],function(confirm){confirm(message,title).then(function(){callback(!0)},function(){callback(!1)})})}; \ No newline at end of file diff --git a/dashboard-ui/legacy/fnchecked.js b/dashboard-ui/legacy/fnchecked.js index db7eb810ee..4417f523e5 100644 --- a/dashboard-ui/legacy/fnchecked.js +++ b/dashboard-ui/legacy/fnchecked.js @@ -1,20 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - // TODO: This needs to be deprecated, but it's used heavily - $.fn.checked = function (value) { - if (value === true || value === false) { - // Set the value of the checkbox - return $(this).each(function () { - this.checked = value; - }); - } else { - // Return check state - return this.length && this[0].checked; - } - }; - - $.fn.checkboxradio = function () { - return this; - }; -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";$.fn.checked=function(value){return value===!0||value===!1?$(this).each(function(){this.checked=value}):this.length&&this[0].checked},$.fn.checkboxradio=function(){return this}}); \ No newline at end of file diff --git a/dashboard-ui/legacy/selectmenu.js b/dashboard-ui/legacy/selectmenu.js index a867fb3793..952941d9c7 100644 --- a/dashboard-ui/legacy/selectmenu.js +++ b/dashboard-ui/legacy/selectmenu.js @@ -1,9 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - // TODO: This needs to be deprecated, but it's used heavily by plugins - $.fn.selectmenu = function () { - // No-op. This implementation only exists to prevent script errors - return this; - }; -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";$.fn.selectmenu=function(){return this}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/addpluginpage.js b/dashboard-ui/scripts/addpluginpage.js index bdd591ee20..536d8cf2bc 100644 --- a/dashboard-ui/scripts/addpluginpage.js +++ b/dashboard-ui/scripts/addpluginpage.js @@ -1,357 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function populateHistory(packageInfo, page) { - - var html = ''; - - for (var i = 0, length = Math.min(packageInfo.versions.length, 10) ; i < length; i++) { - - var version = packageInfo.versions[i]; - - html += '

' + version.versionStr + ' (' + version.classification + ')

'; - - html += '
' + version.description + '
'; - } - - $('#revisionHistory', page).html(html); - } - - function populateVersions(packageInfo, page, installedPlugin) { - - var html = ''; - - for (var i = 0, length = packageInfo.versions.length; i < length; i++) { - - var version = packageInfo.versions[i]; - - html += ''; - - } - - var selectmenu = $('#selectVersion', page).html(html); - - if (!installedPlugin) { - - $('#pCurrentVersion', page).hide().html(""); - } - - var packageVersion = packageInfo.versions.filter(function (current) { - - return current.classification == "Release"; - })[0]; - - // If we still don't have a package version to select, pick the first Beta build - if (!packageVersion) { - - packageVersion = packageInfo.versions.filter(function (current) { - - return current.classification == "Beta"; - })[0]; - } - - if (packageVersion) { - var val = packageVersion.versionStr + '|' + packageVersion.classification; - - selectmenu.val(val); - } - } - - function renderPluginInfo(page, pkg, pluginSecurityInfo) { - - if (AppInfo.isNativeApp) { - return; - } - - if (pkg.isPremium) { - $('.premiumPackage', page).show(); - - // Fill in registration info - var regStatus = ""; - if (pkg.isRegistered) { - - regStatus += "

"; - - regStatus += Globalize.translate('MessageFeatureIncludedWithSupporter'); - - } else { - - var expDateTime = new Date(pkg.expDate).getTime(); - var nowTime = new Date().getTime(); - - if (expDateTime <= nowTime) { - regStatus += "

"; - regStatus += Globalize.translate('MessageTrialExpired'); - } else if (expDateTime > new Date(1970, 1, 1).getTime()) { - - regStatus += "

"; - regStatus += Globalize.translate('MessageTrialWillExpireIn').replace('{0}', Math.round(expDateTime - nowTime) / (86400000)); - } - } - - regStatus += "

"; - $('#regStatus', page).html(regStatus); - - if (pluginSecurityInfo.IsMBSupporter) { - $('#regInfo', page).html(pkg.regInfo || ""); - - $('.premiumDescription', page).hide(); - $('.supporterDescription', page).hide(); - - if (pkg.price > 0) { - - $('.premiumHasPrice', page).show(); - $('#featureId', page).val(pkg.featureId); - $('#featureName', page).val(pkg.name); - $('#amount', page).val(pkg.price); - - $('#regPrice', page).html("

" + Globalize.translate('ValuePriceUSD').replace('{0}', "$" + pkg.price.toFixed(2)) + "

"); - $('#ppButton', page).hide(); - - var url = "https://mb3admin.com/admin/service/user/getPayPalEmail?id=" + pkg.owner; - - fetch(url).then(function (response) { - - return response.json(); - - }).then(function (dev) { - - if (dev.payPalEmail) { - $('#payPalEmail', page).val(dev.payPalEmail); - $('#ppButton', page).show(); - - } - }); - - } else { - // Supporter-only feature - $('.premiumHasPrice', page).hide(); - } - } else { - - if (pkg.price) { - $('.premiumDescription', page).show(); - $('.supporterDescription', page).hide(); - $('#regInfo', page).html(""); - - } else { - $('.premiumDescription', page).hide(); - $('.supporterDescription', page).show(); - $('#regInfo', page).html(""); - } - - $('#ppButton', page).hide(); - } - - } else { - $('.premiumPackage', page).hide(); - } - } - - function renderPackage(pkg, installedPlugins, pluginSecurityInfo, page) { - - var installedPlugin = installedPlugins.filter(function (ip) { - return ip.Name == pkg.name; - })[0]; - - populateVersions(pkg, page, installedPlugin); - populateHistory(pkg, page); - - $('.pluginName', page).html(pkg.name); - - if (pkg.targetSystem == 'Server') { - $("#btnInstallDiv", page).removeClass('hide'); - $("#nonServerMsg", page).hide(); - $("#pSelectVersion", page).removeClass('hide'); - } else { - $("#btnInstallDiv", page).addClass('hide'); - $("#pSelectVersion", page).addClass('hide'); - - var msg = Globalize.translate('MessageInstallPluginFromApp'); - $("#nonServerMsg", page).html(msg).show(); - } - - if (pkg.shortDescription) { - $('#tagline', page).show().html(pkg.shortDescription); - } else { - $('#tagline', page).hide(); - } - - $('#overview', page).html(pkg.overview || ""); - - - $('#developer', page).html(pkg.owner); - - renderPluginInfo(page, pkg, pluginSecurityInfo); - - if (pkg.richDescUrl) { - $('#pViewWebsite', page).show(); - $('#pViewWebsite a', page).attr('href', pkg.richDescUrl); - } else { - $('#pViewWebsite', page).hide(); - } - - if (pkg.previewImage || pkg.thumbImage) { - - var color = pkg.tileColor || "#38c"; - var img = pkg.previewImage ? pkg.previewImage : pkg.thumbImage; - $('#pPreviewImage', page).show().html(""); - } else { - $('#pPreviewImage', page).hide().html(""); - } - - if (installedPlugin) { - - var currentVersionText = Globalize.translate('MessageYouHaveVersionInstalled').replace('{0}', '' + installedPlugin.Version + ''); - $('#pCurrentVersion', page).show().html(currentVersionText); - - } else { - $('#pCurrentVersion', page).hide().html(""); - } - - Dashboard.hideLoadingMsg(); - } - - function performInstallation(page, packageName, guid, updateClass, version) { - - var developer = $('#developer', page).html().toLowerCase(); - - var alertCallback = function (confirmed) { - - if (confirmed) { - - Dashboard.showLoadingMsg(); - - page.querySelector('#btnInstall').disabled = true; - - ApiClient.installPlugin(packageName, guid, updateClass, version).then(function () { - - Dashboard.hideLoadingMsg(); - }); - } - }; - - if (developer != 'luke' && developer != 'ebr') { - - Dashboard.hideLoadingMsg(); - - var msg = Globalize.translate('MessagePluginInstallDisclaimer'); - msg += '
'; - msg += '
'; - msg += Globalize.translate('PleaseConfirmPluginInstallation'); - - require(['confirm'], function (confirm) { - - confirm(msg, Globalize.translate('HeaderConfirmPluginInstallation')).then(function () { - - alertCallback(true); - }, function () { - - alertCallback(false); - }); - - }); - - } else { - alertCallback(true); - } - } - - function updateHelpUrl(page, params) { - - var context = params.context; - - $('.notificationsTabs', page).hide(); - - if (context == 'sync') { - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Sync'); - LibraryMenu.setTitle(Globalize.translate('TitleSync')); - } - else if (context == 'livetv') { - - LibraryMenu.setTitle(Globalize.translate('TitleLiveTV')); - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Live%20TV'); - } - else if (context == 'notifications') { - - $('.notificationsTabs', page).show(); - - LibraryMenu.setTitle(Globalize.translate('TitleNotifications')); - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Notifications'); - } - else { - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Plugins'); - LibraryMenu.setTitle(Globalize.translate('TitlePlugins')); - } - } - - return function (view, params) { - - var onSubmit = function () { - - Dashboard.showLoadingMsg(); - - var page = $(this).parents('#addPluginPage')[0]; - - var name = params.name; - var guid = params.guid; - - ApiClient.getInstalledPlugins().then(function (plugins) { - - var installedPlugin = plugins.filter(function (ip) { - return ip.Name == name; - })[0]; - - var vals = $('#selectVersion', page).val().split('|'); - - var version = vals[0]; - - if (installedPlugin && installedPlugin.Version == version) { - - Dashboard.hideLoadingMsg(); - - Dashboard.alert({ - message: Globalize.translate('MessageAlreadyInstalled'), - title: Globalize.translate('HeaderPluginInstallation') - }); - } else { - performInstallation(page, name, guid, vals[1], version); - } - }); - - return false; - }; - - $('.addPluginForm', view).on('submit', onSubmit); - - updateHelpUrl(view, params); - - view.addEventListener('viewbeforeshow', function () { - - var page = this; - - updateHelpUrl(page, params); - }); - - view.addEventListener('viewshow', function () { - - var page = this; - - Dashboard.showLoadingMsg(); - - var name = params.name; - var guid = params.guid; - - var promise1 = ApiClient.getPackageInfo(name, guid); - var promise2 = ApiClient.getInstalledPlugins(); - var promise3 = ApiClient.getPluginSecurityInfo(); - - Promise.all([promise1, promise2, promise3]).then(function (responses) { - - renderPackage(responses[0], responses[1], responses[2], page); - }); - - updateHelpUrl(page, params); - }); - }; -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function populateHistory(packageInfo,page){for(var html="",i=0,length=Math.min(packageInfo.versions.length,10);i'+version.versionStr+" ("+version.classification+")",html+='
'+version.description+"
"}$("#revisionHistory",page).html(html)}function populateVersions(packageInfo,page,installedPlugin){for(var html="",i=0,length=packageInfo.versions.length;i'+version.versionStr+" ("+version.classification+")"}var selectmenu=$("#selectVersion",page).html(html);installedPlugin||$("#pCurrentVersion",page).hide().html("");var packageVersion=packageInfo.versions.filter(function(current){return"Release"==current.classification})[0];if(packageVersion||(packageVersion=packageInfo.versions.filter(function(current){return"Beta"==current.classification})[0]),packageVersion){var val=packageVersion.versionStr+"|"+packageVersion.classification;selectmenu.val(val)}}function renderPluginInfo(page,pkg,pluginSecurityInfo){if(!AppInfo.isNativeApp)if(pkg.isPremium){$(".premiumPackage",page).show();var regStatus="";if(pkg.isRegistered)regStatus+="

",regStatus+=Globalize.translate("MessageFeatureIncludedWithSupporter");else{var expDateTime=new Date(pkg.expDate).getTime(),nowTime=(new Date).getTime();expDateTime<=nowTime?(regStatus+="

",regStatus+=Globalize.translate("MessageTrialExpired")):expDateTime>new Date(1970,1,1).getTime()&&(regStatus+="

",regStatus+=Globalize.translate("MessageTrialWillExpireIn").replace("{0}",Math.round(expDateTime-nowTime)/864e5))}if(regStatus+="

",$("#regStatus",page).html(regStatus),pluginSecurityInfo.IsMBSupporter)if($("#regInfo",page).html(pkg.regInfo||""),$(".premiumDescription",page).hide(),$(".supporterDescription",page).hide(),pkg.price>0){$(".premiumHasPrice",page).show(),$("#featureId",page).val(pkg.featureId),$("#featureName",page).val(pkg.name),$("#amount",page).val(pkg.price),$("#regPrice",page).html("

"+Globalize.translate("ValuePriceUSD").replace("{0}","$"+pkg.price.toFixed(2))+"

"),$("#ppButton",page).hide();var url="https://mb3admin.com/admin/service/user/getPayPalEmail?id="+pkg.owner;fetch(url).then(function(response){return response.json()}).then(function(dev){dev.payPalEmail&&($("#payPalEmail",page).val(dev.payPalEmail),$("#ppButton",page).show())})}else $(".premiumHasPrice",page).hide();else pkg.price?($(".premiumDescription",page).show(),$(".supporterDescription",page).hide(),$("#regInfo",page).html("")):($(".premiumDescription",page).hide(),$(".supporterDescription",page).show(),$("#regInfo",page).html("")),$("#ppButton",page).hide()}else $(".premiumPackage",page).hide()}function renderPackage(pkg,installedPlugins,pluginSecurityInfo,page){var installedPlugin=installedPlugins.filter(function(ip){return ip.Name==pkg.name})[0];if(populateVersions(pkg,page,installedPlugin),populateHistory(pkg,page),$(".pluginName",page).html(pkg.name),"Server"==pkg.targetSystem)$("#btnInstallDiv",page).removeClass("hide"),$("#nonServerMsg",page).hide(),$("#pSelectVersion",page).removeClass("hide");else{$("#btnInstallDiv",page).addClass("hide"),$("#pSelectVersion",page).addClass("hide");var msg=Globalize.translate("MessageInstallPluginFromApp");$("#nonServerMsg",page).html(msg).show()}if(pkg.shortDescription?$("#tagline",page).show().html(pkg.shortDescription):$("#tagline",page).hide(),$("#overview",page).html(pkg.overview||""),$("#developer",page).html(pkg.owner),renderPluginInfo(page,pkg,pluginSecurityInfo),pkg.richDescUrl?($("#pViewWebsite",page).show(),$("#pViewWebsite a",page).attr("href",pkg.richDescUrl)):$("#pViewWebsite",page).hide(),pkg.previewImage||pkg.thumbImage){var color=pkg.tileColor||"#38c",img=pkg.previewImage?pkg.previewImage:pkg.thumbImage;$("#pPreviewImage",page).show().html("")}else $("#pPreviewImage",page).hide().html("");if(installedPlugin){var currentVersionText=Globalize.translate("MessageYouHaveVersionInstalled").replace("{0}",""+installedPlugin.Version+"");$("#pCurrentVersion",page).show().html(currentVersionText)}else $("#pCurrentVersion",page).hide().html("");Dashboard.hideLoadingMsg()}function performInstallation(page,packageName,guid,updateClass,version){var developer=$("#developer",page).html().toLowerCase(),alertCallback=function(confirmed){confirmed&&(Dashboard.showLoadingMsg(),page.querySelector("#btnInstall").disabled=!0,ApiClient.installPlugin(packageName,guid,updateClass,version).then(function(){Dashboard.hideLoadingMsg()}))};if("luke"!=developer&&"ebr"!=developer){Dashboard.hideLoadingMsg();var msg=Globalize.translate("MessagePluginInstallDisclaimer");msg+="
",msg+="
",msg+=Globalize.translate("PleaseConfirmPluginInstallation"),require(["confirm"],function(confirm){confirm(msg,Globalize.translate("HeaderConfirmPluginInstallation")).then(function(){alertCallback(!0)},function(){alertCallback(!1)})})}else alertCallback(!0)}function updateHelpUrl(page,params){var context=params.context;$(".notificationsTabs",page).hide(),"sync"==context?(page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Sync"),LibraryMenu.setTitle(Globalize.translate("TitleSync"))):"livetv"==context?(LibraryMenu.setTitle(Globalize.translate("TitleLiveTV")),page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Live%20TV")):"notifications"==context?($(".notificationsTabs",page).show(),LibraryMenu.setTitle(Globalize.translate("TitleNotifications")),page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Notifications")):(page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Plugins"),LibraryMenu.setTitle(Globalize.translate("TitlePlugins")))}return function(view,params){var onSubmit=function(){Dashboard.showLoadingMsg();var page=$(this).parents("#addPluginPage")[0],name=params.name,guid=params.guid;return ApiClient.getInstalledPlugins().then(function(plugins){var installedPlugin=plugins.filter(function(ip){return ip.Name==name})[0],vals=$("#selectVersion",page).val().split("|"),version=vals[0];installedPlugin&&installedPlugin.Version==version?(Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("MessageAlreadyInstalled"),title:Globalize.translate("HeaderPluginInstallation")})):performInstallation(page,name,guid,vals[1],version)}),!1};$(".addPluginForm",view).on("submit",onSubmit),updateHelpUrl(view,params),view.addEventListener("viewbeforeshow",function(){var page=this;updateHelpUrl(page,params)}),view.addEventListener("viewshow",function(){var page=this;Dashboard.showLoadingMsg();var name=params.name,guid=params.guid,promise1=ApiClient.getPackageInfo(name,guid),promise2=ApiClient.getInstalledPlugins(),promise3=ApiClient.getPluginSecurityInfo();Promise.all([promise1,promise2,promise3]).then(function(responses){renderPackage(responses[0],responses[1],responses[2],page)}),updateHelpUrl(page,params)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/appservices.js b/dashboard-ui/scripts/appservices.js index 137a17e039..dd751b7449 100644 --- a/dashboard-ui/scripts/appservices.js +++ b/dashboard-ui/scripts/appservices.js @@ -1,106 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function reloadList(page) { - - Dashboard.showLoadingMsg(); - - var promise1 = ApiClient.getAvailablePlugins({ - TargetSystems: 'Server' - }); - - var promise2 = ApiClient.getInstalledPlugins(); - - Promise.all([promise1, promise2]).then(function (responses) { - renderInstalled(page, responses[0], responses[1]); - renderCatalog(page, responses[0], responses[1]); - }); - } - - function getCategories() { - - var context = getParameterByName('context'); - - var categories = []; - - if (context == 'sync') { - categories.push('Sync'); - } - else if (context == 'livetv') { - categories.push('Live TV'); - } - else if (context == 'notifications') { - categories.push('Notifications'); - } - - return categories; - } - - function renderInstalled(page, availablePlugins, installedPlugins) { - - requirejs(['scripts/pluginspage'], function() { - var category = getCategories()[0]; - - installedPlugins = installedPlugins.filter(function (i) { - - var catalogEntry = availablePlugins.filter(function (a) { - return (a.guid || '').toLowerCase() == (i.Id || '').toLowerCase(); - })[0]; - - if (catalogEntry) { - return catalogEntry.category == category; - } - return false; - }); - - PluginsPage.renderPlugins(page, installedPlugins); - }); - } - - function renderCatalog(page, availablePlugins, installedPlugins) { - - requirejs(['scripts/plugincatalogpage'], function () { - var categories = getCategories(); - - PluginCatalog.renderCatalog({ - - catalogElement: $('.catalog', page), - availablePlugins: availablePlugins, - installedPlugins: installedPlugins, - categories: categories, - showCategory: false, - context: getParameterByName('context'), - targetSystem: 'Server' - }); - }); - } - - $(document).on('pagebeforeshow pageshow', "#appServicesPage", function () { - - // This needs both events for the helpurl to get done at the right time - - var page = this; - - var context = getParameterByName('context'); - - if (context == 'sync') { - LibraryMenu.setTitle(Globalize.translate('TitleSync')); - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Sync'); - } - else if (context == 'livetv') { - LibraryMenu.setTitle(Globalize.translate('TitleLiveTV')); - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Live%20TV'); - } - else if (context == 'notifications') { - LibraryMenu.setTitle(Globalize.translate('TitleNotifications')); - page.setAttribute('data-helpurl', 'https://github.com/MediaBrowser/Wiki/wiki/Notifications'); - } - - }).on('pageshow', "#appServicesPage", function () { - - var page = this; - - reloadList(page); - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function reloadList(page){Dashboard.showLoadingMsg();var promise1=ApiClient.getAvailablePlugins({TargetSystems:"Server"}),promise2=ApiClient.getInstalledPlugins();Promise.all([promise1,promise2]).then(function(responses){renderInstalled(page,responses[0],responses[1]),renderCatalog(page,responses[0],responses[1])})}function getCategories(){var context=getParameterByName("context"),categories=[];return"sync"==context?categories.push("Sync"):"livetv"==context?categories.push("Live TV"):"notifications"==context&&categories.push("Notifications"),categories}function renderInstalled(page,availablePlugins,installedPlugins){requirejs(["scripts/pluginspage"],function(){var category=getCategories()[0];installedPlugins=installedPlugins.filter(function(i){var catalogEntry=availablePlugins.filter(function(a){return(a.guid||"").toLowerCase()==(i.Id||"").toLowerCase()})[0];return!!catalogEntry&&catalogEntry.category==category}),PluginsPage.renderPlugins(page,installedPlugins)})}function renderCatalog(page,availablePlugins,installedPlugins){requirejs(["scripts/plugincatalogpage"],function(){var categories=getCategories();PluginCatalog.renderCatalog({catalogElement:$(".catalog",page),availablePlugins:availablePlugins,installedPlugins:installedPlugins,categories:categories,showCategory:!1,context:getParameterByName("context"),targetSystem:"Server"})})}$(document).on("pagebeforeshow pageshow","#appServicesPage",function(){var page=this,context=getParameterByName("context");"sync"==context?(LibraryMenu.setTitle(Globalize.translate("TitleSync")),page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Sync")):"livetv"==context?(LibraryMenu.setTitle(Globalize.translate("TitleLiveTV")),page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Live%20TV")):"notifications"==context&&(LibraryMenu.setTitle(Globalize.translate("TitleNotifications")),page.setAttribute("data-helpurl","https://github.com/MediaBrowser/Wiki/wiki/Notifications"))}).on("pageshow","#appServicesPage",function(){var page=this;reloadList(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/autobackdrops.js b/dashboard-ui/scripts/autobackdrops.js index bd43edd650..04a608fd55 100644 --- a/dashboard-ui/scripts/autobackdrops.js +++ b/dashboard-ui/scripts/autobackdrops.js @@ -1,112 +1 @@ -define(['backdrop', 'appStorage'], function (backdrop, appStorage) { - 'use strict'; - - function enabled() { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return false; - } - - var userId = apiClient.getCurrentUserId(); - - var val = appStorage.getItem('enableBackdrops-' + userId); - - // For bandwidth - return val == '1'; - } - - var cache = {}; - - function getBackdropItemIds(apiClient, userId, types, parentId) { - - var key = 'backdrops2_' + userId + (types || '') + (parentId || ''); - - var data = cache[key]; - - if (data) { - - console.log('Found backdrop id list in cache. Key: ' + key); - data = JSON.parse(data); - return Promise.resolve(data); - } else { - - var options = { - - SortBy: "IsFavoriteOrLiked,Random", - Limit: 20, - Recursive: true, - IncludeItemTypes: types, - ImageTypes: "Backdrop", - //Ids: "8114409aa00a2722456c08e298f90bed", - ParentId: parentId - }; - - return apiClient.getItems(apiClient.getCurrentUserId(), options).then(function (result) { - - var images = result.Items.map(function (i) { - return { - Id: i.Id, - tag: i.BackdropImageTags[0], - ServerId: i.ServerId - }; - }); - - cache[key] = JSON.stringify(images); - return images; - }); - } - } - - function showBackdrop(type, parentId) { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return; - } - - getBackdropItemIds(apiClient, apiClient.getCurrentUserId(), type, parentId).then(function (images) { - - if (images.length) { - - backdrop.setBackdrops(images.map(function (i) { - i.BackdropImageTags = [i.tag]; - return i; - })); - - } else { - - backdrop.clear(); - } - }); - } - - pageClassOn('pagebeforeshow', "page", function () { - - var page = this; - - // These pages self-manage their backdrops - if (page.classList.contains('selfBackdropPage')) { - return; - } - - if (page.classList.contains('backdropPage')) { - - if (enabled()) { - var type = page.getAttribute('data-backdroptype'); - - var parentId = page.classList.contains('globalBackdropPage') ? '' : LibraryMenu.getTopParentId(); - showBackdrop(type, parentId); - - } else { - page.classList.remove('backdropPage'); - backdrop.clear(); - } - } else { - backdrop.clear(); - } - - }); -}); \ No newline at end of file +define(["backdrop","appStorage"],function(backdrop,appStorage){"use strict";function enabled(){var apiClient=window.ApiClient;if(!apiClient)return!1;var userId=apiClient.getCurrentUserId(),val=appStorage.getItem("enableBackdrops-"+userId);return"1"==val}function getBackdropItemIds(apiClient,userId,types,parentId){var key="backdrops2_"+userId+(types||"")+(parentId||""),data=cache[key];if(data)return console.log("Found backdrop id list in cache. Key: "+key),data=JSON.parse(data),Promise.resolve(data);var options={SortBy:"IsFavoriteOrLiked,Random",Limit:20,Recursive:!0,IncludeItemTypes:types,ImageTypes:"Backdrop",ParentId:parentId};return apiClient.getItems(apiClient.getCurrentUserId(),options).then(function(result){var images=result.Items.map(function(i){return{Id:i.Id,tag:i.BackdropImageTags[0],ServerId:i.ServerId}});return cache[key]=JSON.stringify(images),images})}function showBackdrop(type,parentId){var apiClient=window.ApiClient;apiClient&&getBackdropItemIds(apiClient,apiClient.getCurrentUserId(),type,parentId).then(function(images){images.length?backdrop.setBackdrops(images.map(function(i){return i.BackdropImageTags=[i.tag],i})):backdrop.clear()})}var cache={};pageClassOn("pagebeforeshow","page",function(){var page=this;if(!page.classList.contains("selfBackdropPage"))if(page.classList.contains("backdropPage"))if(enabled()){var type=page.getAttribute("data-backdroptype"),parentId=page.classList.contains("globalBackdropPage")?"":LibraryMenu.getTopParentId();showBackdrop(type,parentId)}else page.classList.remove("backdropPage"),backdrop.clear();else backdrop.clear()})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/camerauploadsettings.js b/dashboard-ui/scripts/camerauploadsettings.js index b877a5bfce..faf110a50e 100644 --- a/dashboard-ui/scripts/camerauploadsettings.js +++ b/dashboard-ui/scripts/camerauploadsettings.js @@ -1,73 +1 @@ -define(['appSettings', 'emby-checkbox'], function (appSettings) { - 'use strict'; - - function loadForm(page, user) { - - var uploadServers = appSettings.cameraUploadServers(); - - page.querySelector('.uploadServerList').innerHTML = ConnectionManager.getSavedServers().map(function (s) { - - var checkedHtml = uploadServers.indexOf(s.Id) == -1 ? '' : ' checked'; - var html = ''; - - return html; - - }).join(''); - - Dashboard.hideLoadingMsg(); - } - - function saveUser(page) { - - var chkUploadServer = page.querySelectorAll('.chkUploadServer'); - var cameraUploadServers = []; - - for (var i = 0, length = chkUploadServer.length; i < length; i++) { - if (chkUploadServer[i].checked) { - cameraUploadServers.push(chkUploadServer[i].getAttribute('data-id')); - } - } - - appSettings.cameraUploadServers(cameraUploadServers); - - if (window.MainActivity) { - // TODO: isolate into android app - MainActivity.authorizeStorage(); - } - - Dashboard.hideLoadingMsg(); - } - - return function (view, params) { - - view.querySelector('form').addEventListener('submit', function (e) { - - Dashboard.showLoadingMsg(); - - saveUser(view); - - // Disable default form submission - e.preventDefault(); - return false; - }); - - view.addEventListener('viewshow', function () { - var page = this; - - Dashboard.showLoadingMsg(); - - var userId = params.userId || Dashboard.getCurrentUserId(); - - ApiClient.getUser(userId).then(function (user) { - - loadForm(page, user); - }); - }); - - view.addEventListener('viewbeforehide', function () { - - saveUser(this); - }); - }; - -}); \ No newline at end of file +define(["appSettings","emby-checkbox"],function(appSettings){"use strict";function loadForm(page,user){var uploadServers=appSettings.cameraUploadServers();page.querySelector(".uploadServerList").innerHTML=ConnectionManager.getSavedServers().map(function(s){var checkedHtml=uploadServers.indexOf(s.Id)==-1?"":" checked",html='";return html}).join(""),Dashboard.hideLoadingMsg()}function saveUser(page){for(var chkUploadServer=page.querySelectorAll(".chkUploadServer"),cameraUploadServers=[],i=0,length=chkUploadServer.length;ihttps://emby.media') - }); - } - break; - case MediaBrowser.ConnectionState.Unavailable: - { - Dashboard.alert({ - message: Globalize.translate("MessageUnableToConnectToServer"), - title: Globalize.translate("HeaderConnectionFailure") - }); - } - break; - default: - break; - } - } - - function loadAppConnection(page) { - - Dashboard.showLoadingMsg(); - - ConnectionManager.connect({ - - enableAutoLogin: appSettings.enableAutoLogin() - - }).then(function (result) { - - handleConnectionResult(page, result); - - }); - } - - function loadPage(page, params) { - - var mode = params.mode || 'auto'; - - if (mode == 'auto') { - - if (AppInfo.isNativeApp) { - loadAppConnection(page); - return; - } - mode = 'connect'; - } - - loadMode(page, mode); - } - function loadMode(page, mode) { - - if (mode == 'welcome') { - - page.querySelector('.connectLoginForm').classList.add('hide'); - page.querySelector('.welcomeContainer').classList.remove('hide'); - page.querySelector('.manualServerForm').classList.add('hide'); - page.querySelector('.signupForm').classList.add('hide'); - } - else if (mode == 'connect') { - page.querySelector('.connectLoginForm').classList.remove('hide'); - page.querySelector('.welcomeContainer').classList.add('hide'); - page.querySelector('.manualServerForm').classList.add('hide'); - page.querySelector('.signupForm').classList.add('hide'); - } - else if (mode == 'manualserver') { - page.querySelector('.manualServerForm').classList.remove('hide'); - page.querySelector('.connectLoginForm').classList.add('hide'); - page.querySelector('.welcomeContainer').classList.add('hide'); - page.querySelector('.signupForm').classList.add('hide'); - } - else if (mode == 'signup') { - page.querySelector('.manualServerForm').classList.add('hide'); - page.querySelector('.connectLoginForm').classList.add('hide'); - page.querySelector('.welcomeContainer').classList.add('hide'); - page.querySelector('.signupForm').classList.remove('hide'); - initSignup(page); - } - } - - function skip() { - - Dashboard.navigate('selectserver.html'); - } - - function requireCaptcha() { - return !AppInfo.isNativeApp && window.location.href.toLowerCase().indexOf('https') == 0; - } - - function supportInAppSignup() { - return AppInfo.isNativeApp || window.location.href.toLowerCase().indexOf('https') == 0; - } - - var greWidgetId; - function initSignup(page) { - - if (!supportInAppSignup()) { - return; - } - - if (!requireCaptcha()) { - return; - } - - require(['https://www.google.com/recaptcha/api.js?render=explicit'], function () { - - setTimeout(function () { - var recaptchaContainer = page.querySelector('.recaptchaContainer'); - - greWidgetId = grecaptcha.render(recaptchaContainer, { - 'sitekey': '6Le2LAgTAAAAAK06Wvttt_yUnbISTy6q3Azqp9po', - 'theme': 'dark' - }); - }, 100); - }); - } - - function submitManualServer(page) { - - var host = page.querySelector('#txtServerHost').value; - var port = page.querySelector('#txtServerPort').value; - - if (port) { - host += ':' + port; - } - - Dashboard.showLoadingMsg(); - - ConnectionManager.connectToAddress(host, { - - enableAutoLogin: appSettings.enableAutoLogin() - - }).then(function (result) { - - handleConnectionResult(page, result); - - }, function () { - handleConnectionResult(page, { - State: MediaBrowser.ConnectionState.Unavailable - }); - - }); - } - - function submit(page) { - - var user = page.querySelector('#txtManualName').value; - var password = page.querySelector('#txtManualPassword').value; - - login(page, user, password); - } - - return function (view, params) { - - function onSubmit(e) { - submit(view); - - e.preventDefault(); - return false; - } - - function onManualServerSubmit(e) { - submitManualServer(view); - - e.preventDefault(); - return false; - } - - function onSignupFormSubmit(e) { - - if (!supportInAppSignup()) { - e.preventDefault(); - return false; - } - - var page = view; - - var greResponse = greWidgetId ? grecaptcha.getResponse(greWidgetId) : null; - - ConnectionManager.signupForConnect({ - - email: page.querySelector('#txtSignupEmail', page).value, - username: page.querySelector('#txtSignupUsername', page).value, - password: page.querySelector('#txtSignupPassword', page).value, - passwordConfirm: page.querySelector('#txtSignupPasswordConfirm', page).value, - grecaptcha: greResponse - - }).then(function (result) { - - var msg = result.Validated ? - Globalize.translate('MessageThankYouForConnectSignUpNoValidation') : - Globalize.translate('MessageThankYouForConnectSignUp'); - - Dashboard.alert({ - message: msg, - callback: function () { - Dashboard.navigate('connectlogin.html?mode=welcome'); - } - }); - - }, function (result) { - - if (result.errorCode == 'passwordmatch') { - Dashboard.alert({ - message: Globalize.translate('ErrorMessagePasswordNotMatchConfirm') - }); - } - else if (result.errorCode == 'USERNAME_IN_USE') { - Dashboard.alert({ - message: Globalize.translate('ErrorMessageUsernameInUse') - }); - } - else if (result.errorCode == 'EMAIL_IN_USE') { - Dashboard.alert({ - message: Globalize.translate('ErrorMessageEmailInUse') - }); - } else { - Dashboard.alert({ - message: Globalize.translate('DefaultErrorMessage') - }); - } - - }); - - e.preventDefault(); - return false; - } - - view.querySelector('.btnSkipConnect').addEventListener('click', skip); - - view.querySelector('.connectLoginForm').addEventListener('submit', onSubmit); - view.querySelector('.manualServerForm').addEventListener('submit', onManualServerSubmit); - view.querySelector('.signupForm').addEventListener('submit', onSignupFormSubmit); - - view.querySelector('.btnSignupForConnect').addEventListener('click', function (e) { - if (supportInAppSignup()) { - e.preventDefault(); - e.stopPropagation(); - Dashboard.navigate('connectlogin.html?mode=signup'); - return false; - } - }); - - function goBack() { - require(['embyRouter'], function (embyRouter) { - embyRouter.back(); - }); - } - - view.querySelector('.btnCancelSignup').addEventListener('click', goBack); - view.querySelector('.btnCancelManualServer').addEventListener('click', goBack); - - view.querySelector('.btnWelcomeNext').addEventListener('click', function () { - Dashboard.navigate('connectlogin.html?mode=connect'); - }); - - var terms = view.querySelector('.terms'); - terms.innerHTML = Globalize.translate('LoginDisclaimer') + ""; - - if (AppInfo.isNativeApp) { - terms.classList.add('hide'); - view.querySelector('.tvAppInfo').classList.add('hide'); - } else { - terms.classList.remove('hide'); - view.querySelector('.tvAppInfo').classList.remove('hide'); - } - - view.addEventListener('viewbeforeshow', function () { - - var page = this; - - page.querySelector('#txtSignupEmail').value = ''; - page.querySelector('#txtSignupUsername').value = ''; - page.querySelector('#txtSignupPassword').value = ''; - page.querySelector('#txtSignupPasswordConfirm').value = ''; - - if (browserInfo.safari && AppInfo.isNativeApp) { - // With apple we can't even have a link to the site - page.querySelector('.embyIntroDownloadMessage').innerHTML = Globalize.translate('EmbyIntroDownloadMessageWithoutLink'); - } else { - var link = 'http://emby.media'; - page.querySelector('.embyIntroDownloadMessage').innerHTML = Globalize.translate('EmbyIntroDownloadMessage', link); - } - }); - - view.addEventListener('viewshow', function () { - loadPage(view, params); - }); - }; -}); \ No newline at end of file +define(["appSettings"],function(appSettings){"use strict";function login(page,username,password){Dashboard.showLoadingMsg(),appSettings.enableAutoLogin(!0),ConnectionManager.loginToConnect(username,password).then(function(){Dashboard.hideLoadingMsg(),Dashboard.navigate("selectserver.html")},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("MessageInvalidUser"),title:Globalize.translate("HeaderLoginFailure")}),page.querySelector("#txtManualPassword").value=""})}function handleConnectionResult(page,result){switch(Dashboard.hideLoadingMsg(),result.State){case MediaBrowser.ConnectionState.SignedIn:var apiClient=result.ApiClient;Dashboard.onServerChanged(apiClient.getCurrentUserId(),apiClient.accessToken(),apiClient),Dashboard.navigate("home.html");break;case MediaBrowser.ConnectionState.ServerSignIn:Dashboard.navigate("login.html?serverid="+result.Servers[0].Id,!1,"none");break;case MediaBrowser.ConnectionState.ServerSelection:Dashboard.navigate("selectserver.html",!1,"none");break;case MediaBrowser.ConnectionState.ConnectSignIn:loadMode(page,"welcome");break;case MediaBrowser.ConnectionState.ServerUpdateNeeded:Dashboard.alert({message:Globalize.translate("ServerUpdateNeeded",'https://emby.media')});break;case MediaBrowser.ConnectionState.Unavailable:Dashboard.alert({message:Globalize.translate("MessageUnableToConnectToServer"),title:Globalize.translate("HeaderConnectionFailure")})}}function loadAppConnection(page){Dashboard.showLoadingMsg(),ConnectionManager.connect({enableAutoLogin:appSettings.enableAutoLogin()}).then(function(result){handleConnectionResult(page,result)})}function loadPage(page,params){var mode=params.mode||"auto";if("auto"==mode){if(AppInfo.isNativeApp)return void loadAppConnection(page);mode="connect"}loadMode(page,mode)}function loadMode(page,mode){"welcome"==mode?(page.querySelector(".connectLoginForm").classList.add("hide"),page.querySelector(".welcomeContainer").classList.remove("hide"),page.querySelector(".manualServerForm").classList.add("hide"),page.querySelector(".signupForm").classList.add("hide")):"connect"==mode?(page.querySelector(".connectLoginForm").classList.remove("hide"),page.querySelector(".welcomeContainer").classList.add("hide"),page.querySelector(".manualServerForm").classList.add("hide"),page.querySelector(".signupForm").classList.add("hide")):"manualserver"==mode?(page.querySelector(".manualServerForm").classList.remove("hide"),page.querySelector(".connectLoginForm").classList.add("hide"),page.querySelector(".welcomeContainer").classList.add("hide"),page.querySelector(".signupForm").classList.add("hide")):"signup"==mode&&(page.querySelector(".manualServerForm").classList.add("hide"),page.querySelector(".connectLoginForm").classList.add("hide"),page.querySelector(".welcomeContainer").classList.add("hide"),page.querySelector(".signupForm").classList.remove("hide"),initSignup(page))}function skip(){Dashboard.navigate("selectserver.html")}function requireCaptcha(){return!AppInfo.isNativeApp&&0==window.location.href.toLowerCase().indexOf("https")}function supportInAppSignup(){return AppInfo.isNativeApp||0==window.location.href.toLowerCase().indexOf("https")}function initSignup(page){supportInAppSignup()&&requireCaptcha()&&require(["https://www.google.com/recaptcha/api.js?render=explicit"],function(){setTimeout(function(){var recaptchaContainer=page.querySelector(".recaptchaContainer");greWidgetId=grecaptcha.render(recaptchaContainer,{sitekey:"6Le2LAgTAAAAAK06Wvttt_yUnbISTy6q3Azqp9po",theme:"dark"})},100)})}function submitManualServer(page){var host=page.querySelector("#txtServerHost").value,port=page.querySelector("#txtServerPort").value;port&&(host+=":"+port),Dashboard.showLoadingMsg(),ConnectionManager.connectToAddress(host,{enableAutoLogin:appSettings.enableAutoLogin()}).then(function(result){handleConnectionResult(page,result)},function(){handleConnectionResult(page,{State:MediaBrowser.ConnectionState.Unavailable})})}function submit(page){var user=page.querySelector("#txtManualName").value,password=page.querySelector("#txtManualPassword").value;login(page,user,password)}var greWidgetId;return function(view,params){function onSubmit(e){return submit(view),e.preventDefault(),!1}function onManualServerSubmit(e){return submitManualServer(view),e.preventDefault(),!1}function onSignupFormSubmit(e){if(!supportInAppSignup())return e.preventDefault(),!1;var page=view,greResponse=greWidgetId?grecaptcha.getResponse(greWidgetId):null;return ConnectionManager.signupForConnect({email:page.querySelector("#txtSignupEmail",page).value,username:page.querySelector("#txtSignupUsername",page).value,password:page.querySelector("#txtSignupPassword",page).value,passwordConfirm:page.querySelector("#txtSignupPasswordConfirm",page).value,grecaptcha:greResponse}).then(function(result){var msg=result.Validated?Globalize.translate("MessageThankYouForConnectSignUpNoValidation"):Globalize.translate("MessageThankYouForConnectSignUp");Dashboard.alert({message:msg,callback:function(){Dashboard.navigate("connectlogin.html?mode=welcome")}})},function(result){"passwordmatch"==result.errorCode?Dashboard.alert({message:Globalize.translate("ErrorMessagePasswordNotMatchConfirm")}):"USERNAME_IN_USE"==result.errorCode?Dashboard.alert({message:Globalize.translate("ErrorMessageUsernameInUse")}):"EMAIL_IN_USE"==result.errorCode?Dashboard.alert({message:Globalize.translate("ErrorMessageEmailInUse")}):Dashboard.alert({message:Globalize.translate("DefaultErrorMessage")})}),e.preventDefault(),!1}function goBack(){require(["embyRouter"],function(embyRouter){embyRouter.back()})}view.querySelector(".btnSkipConnect").addEventListener("click",skip),view.querySelector(".connectLoginForm").addEventListener("submit",onSubmit),view.querySelector(".manualServerForm").addEventListener("submit",onManualServerSubmit),view.querySelector(".signupForm").addEventListener("submit",onSignupFormSubmit),view.querySelector(".btnSignupForConnect").addEventListener("click",function(e){if(supportInAppSignup())return e.preventDefault(),e.stopPropagation(),Dashboard.navigate("connectlogin.html?mode=signup"),!1}),view.querySelector(".btnCancelSignup").addEventListener("click",goBack),view.querySelector(".btnCancelManualServer").addEventListener("click",goBack),view.querySelector(".btnWelcomeNext").addEventListener("click",function(){Dashboard.navigate("connectlogin.html?mode=connect")});var terms=view.querySelector(".terms");terms.innerHTML=Globalize.translate("LoginDisclaimer")+"",AppInfo.isNativeApp?(terms.classList.add("hide"),view.querySelector(".tvAppInfo").classList.add("hide")):(terms.classList.remove("hide"),view.querySelector(".tvAppInfo").classList.remove("hide")),view.addEventListener("viewbeforeshow",function(){var page=this;if(page.querySelector("#txtSignupEmail").value="",page.querySelector("#txtSignupUsername").value="",page.querySelector("#txtSignupPassword").value="",page.querySelector("#txtSignupPasswordConfirm").value="",browserInfo.safari&&AppInfo.isNativeApp)page.querySelector(".embyIntroDownloadMessage").innerHTML=Globalize.translate("EmbyIntroDownloadMessageWithoutLink");else{var link='http://emby.media';page.querySelector(".embyIntroDownloadMessage").innerHTML=Globalize.translate("EmbyIntroDownloadMessage",link)}}),view.addEventListener("viewshow",function(){loadPage(view,params)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/dashboardpage.js b/dashboard-ui/scripts/dashboardpage.js index b1c2190b5c..7a956feee0 100644 --- a/dashboard-ui/scripts/dashboardpage.js +++ b/dashboard-ui/scripts/dashboardpage.js @@ -1,1414 +1 @@ -define(['datetime', 'jQuery', 'dom', 'humanedate', 'cardStyle', 'listViewStyle'], function (datetime, $, dom) { - 'use strict'; - - function renderNoHealthAlertsMessage(page) { - - var html = '

'; - - html += ''; - - html += Globalize.translate('HealthMonitorNoAlerts') + '

'; - - page.querySelector('.healthMonitor').innerHTML = html; - } - - function refreshHealthMonitor(page) { - - renderNoHealthAlertsMessage(page); - } - - function onConnectionHelpClick(e) { - - e.preventDefault(); - return false; - } - - function onEditServerNameClick(e) { - - var page = dom.parentWithClass(this, 'page'); - - require(['prompt'], function (prompt) { - - prompt({ - label: Globalize.translate('LabelFriendlyServerName'), - description: Globalize.translate('LabelFriendlyServerNameHelp'), - value: page.querySelector('.serverNameHeader').innerHTML, - confirmText: Globalize.translate('ButtonSave') - - }).then(function (value) { - - Dashboard.showLoadingMsg(); - - ApiClient.getServerConfiguration().then(function (config) { - - config.ServerName = value; - - ApiClient.updateServerConfiguration(config).then(function () { - page.querySelector('.serverNameHeader').innerHTML = value; - Dashboard.hideLoadingMsg(); - }); - }); - }); - }); - - e.preventDefault(); - return false; - } - - window.DashboardPage = { - - newsStartIndex: 0, - - onPageInit: function () { - - var page = this; - - page.querySelector('.btnConnectionHelp').addEventListener('click', onConnectionHelpClick); - page.querySelector('.btnEditServerName').addEventListener('click', onEditServerNameClick); - }, - - onPageShow: function () { - - var page = this; - - var apiClient = ApiClient; - - if (!apiClient) { - return; - } - - DashboardPage.newsStartIndex = 0; - - Dashboard.showLoadingMsg(); - DashboardPage.pollForInfo(page); - DashboardPage.startInterval(apiClient); - - Events.on(apiClient, 'websocketmessage', DashboardPage.onWebSocketMessage); - Events.on(apiClient, 'websocketopen', DashboardPage.onWebSocketOpen); - - DashboardPage.lastAppUpdateCheck = null; - DashboardPage.lastPluginUpdateCheck = null; - - Dashboard.getPluginSecurityInfo().then(function (pluginSecurityInfo) { - - DashboardPage.renderSupporterIcon(page, pluginSecurityInfo); - }); - - DashboardPage.reloadSystemInfo(page); - DashboardPage.reloadNews(page); - DashboardPage.sessionUpdateTimer = setInterval(DashboardPage.refreshSessionsLocally, 60000); - - $('.activityItems', page).activityLogList(); - - $('.swaggerLink', page).attr('href', apiClient.getUrl('swagger-ui/index.html', { - api_key: ApiClient.accessToken() - })); - - refreshHealthMonitor(page); - }, - - onPageHide: function () { - - var page = this; - - $('.activityItems', page).activityLogList('destroy'); - - var apiClient = ApiClient; - - if (apiClient) { - Events.off(apiClient, 'websocketmessage', DashboardPage.onWebSocketMessage); - Events.off(apiClient, 'websocketopen', DashboardPage.onWebSocketOpen); - DashboardPage.stopInterval(apiClient); - } - - if (DashboardPage.sessionUpdateTimer) { - clearInterval(DashboardPage.sessionUpdateTimer); - } - }, - - renderPaths: function (page, systemInfo) { - - $('#cachePath', page).html(systemInfo.CachePath); - $('#logPath', page).html(systemInfo.LogPath); - $('#transcodingTemporaryPath', page).html(systemInfo.TranscodingTempPath); - $('#metadataPath', page).html(systemInfo.InternalMetadataPath); - }, - - refreshSessionsLocally: function () { - - var list = DashboardPage.sessionsList; - - if (list) { - DashboardPage.renderActiveConnections($.mobile.activePage, list); - } - }, - - reloadSystemInfo: function (page) { - - ApiClient.getSystemInfo().then(function (systemInfo) { - - page.querySelector('.serverNameHeader').innerHTML = systemInfo.ServerName; - - var localizedVersion = Globalize.translate('LabelVersionNumber', systemInfo.Version); - if (systemInfo.SystemUpdateLevel && systemInfo.SystemUpdateLevel != 'Release') { - localizedVersion += " " + Globalize.translate('Option' + systemInfo.SystemUpdateLevel).toLowerCase(); - } - - $('#appVersionNumber', page).html(localizedVersion); - - if (systemInfo.SupportsHttps) { - $('#ports', page).html(Globalize.translate('LabelRunningOnPorts', systemInfo.HttpServerPortNumber, systemInfo.HttpsPortNumber)); - } else { - $('#ports', page).html(Globalize.translate('LabelRunningOnPort', systemInfo.HttpServerPortNumber)); - } - - if (systemInfo.CanSelfRestart) { - $('.btnRestartContainer', page).removeClass('hide'); - } else { - $('.btnRestartContainer', page).addClass('hide'); - } - - DashboardPage.renderUrls(page, systemInfo); - DashboardPage.renderPendingInstallations(page, systemInfo); - - if (systemInfo.CanSelfUpdate) { - $('#btnUpdateApplicationContainer', page).show(); - $('#btnManualUpdateContainer', page).hide(); - } else { - $('#btnUpdateApplicationContainer', page).hide(); - $('#btnManualUpdateContainer', page).show(); - } - - if (systemInfo.PackageName == 'synology') { - $('#btnManualUpdateContainer').html(Globalize.translate('SynologyUpdateInstructions')); - } else { - $('#btnManualUpdateContainer').html('' + Globalize.translate('PleaseUpdateManually') + ''); - } - - DashboardPage.renderPaths(page, systemInfo); - DashboardPage.renderHasPendingRestart(page, systemInfo.HasPendingRestart); - }); - }, - - reloadNews: function (page) { - - var query = { - StartIndex: DashboardPage.newsStartIndex, - Limit: 7 - }; - - ApiClient.getProductNews(query).then(function (result) { - - var html = result.Items.map(function (item) { - - var itemHtml = ''; - - itemHtml += ''; - itemHtml += '
'; - - itemHtml += 'dvr'; - - itemHtml += '
'; - - itemHtml += '
'; - itemHtml += item.Title; - itemHtml += '
'; - - itemHtml += '
'; - var date = datetime.parseISO8601Date(item.Date, true); - itemHtml += datetime.toLocaleDateString(date); - itemHtml += '
'; - - //itemHtml += '
'; - //itemHtml += item.Description; - //itemHtml += '
'; - - itemHtml += '
'; - - itemHtml += '
'; - itemHtml += '
'; - - return itemHtml; - }); - - var pagingHtml = ''; - pagingHtml += '
'; - pagingHtml += LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false - }); - pagingHtml += '
'; - - html = html.join('') + pagingHtml; - - var elem = $('.latestNewsItems', page).html(html); - - $('.btnNextPage', elem).on('click', function () { - DashboardPage.newsStartIndex += query.Limit; - DashboardPage.reloadNews(page); - }); - - $('.btnPreviousPage', elem).on('click', function () { - DashboardPage.newsStartIndex -= query.Limit; - DashboardPage.reloadNews(page); - }); - }); - - }, - - startInterval: function (apiClient) { - - if (apiClient.isWebSocketOpen()) { - apiClient.sendWebSocketMessage("SessionsStart", "0,1500"); - apiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "0,1000"); - } - }, - - stopInterval: function (apiClient) { - - if (apiClient.isWebSocketOpen()) { - apiClient.sendWebSocketMessage("SessionsStop"); - apiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); - } - }, - - onWebSocketMessage: function (e, msg) { - - var page = $.mobile.activePage; - - if (msg.MessageType == "Sessions") { - DashboardPage.renderInfo(page, msg.Data); - } - else if (msg.MessageType == "RestartRequired") { - DashboardPage.renderHasPendingRestart(page, true); - } - else if (msg.MessageType == "ServerShuttingDown") { - DashboardPage.renderHasPendingRestart(page, true); - } - else if (msg.MessageType == "ServerRestarting") { - DashboardPage.renderHasPendingRestart(page, true); - } - else if (msg.MessageType == "ScheduledTasksInfo") { - - var tasks = msg.Data; - - DashboardPage.renderRunningTasks(page, tasks); - } - else if (msg.MessageType == "PackageInstalling" || msg.MessageType == "PackageInstallationCompleted") { - - DashboardPage.pollForInfo(page, true); - DashboardPage.reloadSystemInfo(page); - } - }, - - onWebSocketOpen: function () { - - var apiClient = this; - - DashboardPage.startInterval(apiClient); - }, - - pollForInfo: function (page, forceUpdate) { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return; - } - - apiClient.getSessions().then(function (sessions) { - - DashboardPage.renderInfo(page, sessions, forceUpdate); - }); - apiClient.getScheduledTasks().then(function (tasks) { - - DashboardPage.renderRunningTasks(page, tasks); - }); - }, - - renderInfo: function (page, sessions, forceUpdate) { - - DashboardPage.renderActiveConnections(page, sessions); - DashboardPage.renderPluginUpdateInfo(page, forceUpdate); - - Dashboard.hideLoadingMsg(); - }, - - renderActiveConnections: function (page, sessions) { - - var html = ''; - - DashboardPage.sessionsList = sessions; - - var parentElement = $('.activeDevices', page); - - $('.card', parentElement).addClass('deadSession'); - - for (var i = 0, length = sessions.length; i < length; i++) { - - var session = sessions[i]; - - var rowId = 'session' + session.Id; - - var elem = $('#' + rowId, page); - - if (elem.length) { - DashboardPage.updateSession(elem, session); - continue; - } - - var nowPlayingItem = session.NowPlayingItem; - - var className = nowPlayingItem ? 'scalableCard card activeSession backdropCard backdropCard-scalable' : 'scalableCard card activeSession backdropCard backdropCard-scalable'; - - if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { - className += ' transcodingSession'; - } - - html += '
'; - - html += '
'; - html += '
'; - - html += '
'; - html += '
'; - - html += '
'; - html += '
' + DashboardPage.getAppSecondaryText(session) + '
'; - html += '
'; - - html += '
'; - - html += '
' + DashboardPage.getSessionNowPlayingTime(session) + '
'; - - //if (session.TranscodingInfo && session.TranscodingInfo.Framerate) { - - // html += '
' + session.TranscodingInfo.Framerate + ' fps
'; - //} else { - // html += '
'; - //} - - var nowPlayingName = DashboardPage.getNowPlayingName(session); - - html += '
'; - html += nowPlayingName.html; - html += '
'; - - if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { - - var position = session.PlayState.PositionTicks || 0; - var value = (100 * position) / nowPlayingItem.RunTimeTicks; - - html += ''; - } else { - html += ''; - } - - if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { - - html += ''; - } else { - html += ''; - } - - html += '
'; - - html += '
'; - - // cardScalable - html += '
'; - - html += '
'; - - html += '
'; - html += DashboardPage.getSessionNowPlayingStreamInfo(session); - html += '
'; - - html += '
'; - var userImage = DashboardPage.getUserImage(session); - if (userImage) { - html += ''; - } else { - html += '
'; - } - - html += '
'; - html += DashboardPage.getUsersHtml(session) || ' '; - html += '
'; - html += '
'; - html += '
'; - - // cardBox - html += ''; - - // card - html += ''; - } - - parentElement.append(html); - - $('.deadSession', parentElement).remove(); - }, - - getSessionNowPlayingStreamInfo: function (session) { - - var html = ''; - - //html += '
'; - var showTranscodingInfo = false; - - if (session.TranscodingInfo && session.TranscodingInfo.IsAudioDirect && session.TranscodingInfo.IsVideoDirect) { - html += Globalize.translate('LabelPlayMethodDirectStream'); - } - else if (session.TranscodingInfo && session.TranscodingInfo.IsVideoDirect) { - html += Globalize.translate('LabelPlayMethodDirectStream'); - } - else if (session.PlayState.PlayMethod == 'Transcode') { - html += Globalize.translate('LabelPlayMethodTranscoding'); - - if (session.TranscodingInfo && session.TranscodingInfo.Framerate) { - - html += ' (' + session.TranscodingInfo.Framerate + ' fps' + ')'; - } - showTranscodingInfo = true; - } - else if (session.PlayState.PlayMethod == 'DirectStream') { - html += Globalize.translate('LabelPlayMethodDirectPlay'); - } - else if (session.PlayState.PlayMethod == 'DirectPlay') { - html += Globalize.translate('LabelPlayMethodDirectPlay'); - } - - //html += '
'; - - if (showTranscodingInfo) { - - var line = []; - - if (session.TranscodingInfo) { - if (session.TranscodingInfo.Bitrate) { - - if (session.TranscodingInfo.Bitrate > 1000000) { - line.push((session.TranscodingInfo.Bitrate / 1000000).toFixed(1) + ' Mbps'); - } else { - line.push(Math.floor(session.TranscodingInfo.Bitrate / 1000) + ' kbps'); - } - } - if (session.TranscodingInfo.Container) { - - line.push(session.TranscodingInfo.Container); - } - - if (session.TranscodingInfo.VideoCodec) { - - //line.push(Globalize.translate('LabelVideoCodec').replace('{0}', session.TranscodingInfo.VideoCodec)); - line.push(session.TranscodingInfo.VideoCodec); - } - if (session.TranscodingInfo.AudioCodec && session.TranscodingInfo.AudioCodec != session.TranscodingInfo.Container) { - - //line.push(Globalize.translate('LabelAudioCodec').replace('{0}', session.TranscodingInfo.AudioCodec)); - line.push(session.TranscodingInfo.AudioCodec); - } - } - - if (line.length) { - - html += ' - ' + line.join(' '); - } - - } - - return html || ' '; - }, - - getSessionNowPlayingTime: function (session) { - - var html = ''; - - if (session.PlayState.PositionTicks) { - html += datetime.getDisplayRunningTime(session.PlayState.PositionTicks); - } else { - html += '--:--:--'; - } - - html += ' / '; - - var nowPlayingItem = session.NowPlayingItem; - - if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { - html += datetime.getDisplayRunningTime(nowPlayingItem.RunTimeTicks); - } else { - html += '--:--:--'; - } - - return html; - }, - - getAppSecondaryText: function (session) { - - return session.ApplicationVersion; - }, - - getNowPlayingName: function (session) { - - var imgUrl = ''; - - var nowPlayingItem = session.NowPlayingItem; - - if (!nowPlayingItem) { - - return { - html: 'Last seen ' + humane_date(session.LastActivityDate), - image: imgUrl - }; - } - - var topText = nowPlayingItem.Name; - - var bottomText = ''; - - if (nowPlayingItem.Artists && nowPlayingItem.Artists.length) { - bottomText = topText; - topText = nowPlayingItem.Artists[0]; - } - else if (nowPlayingItem.SeriesName || nowPlayingItem.Album) { - bottomText = topText; - topText = nowPlayingItem.SeriesName || nowPlayingItem.Album; - } - else if (nowPlayingItem.ProductionYear) { - bottomText = nowPlayingItem.ProductionYear; - } - - if (nowPlayingItem.LogoItemId) { - - imgUrl = ApiClient.getScaledImageUrl(nowPlayingItem.LogoItemId, { - - tag: session.LogoImageTag, - maxHeight: 24, - maxWidth: 130, - type: 'Logo' - - }); - - topText = ''; - } - - var text = bottomText ? topText + '
' + bottomText : topText; - - return { - html: text, - image: imgUrl - }; - }, - - getUsersHtml: function (session) { - - var html = []; - - if (session.UserId) { - html.push(session.UserName); - } - - for (var i = 0, length = session.AdditionalUsers.length; i < length; i++) { - - html.push(session.AdditionalUsers[i].UserName); - } - - return html.join(', '); - }, - - getUserImage: function (session) { - - if (session.UserId && session.UserPrimaryImageTag) { - return ApiClient.getUserImageUrl(session.UserId, { - - tag: session.UserPrimaryImageTag, - height: 24, - type: 'Primary' - - }); - } - - return null; - }, - - updateSession: function (row, session) { - - row.removeClass('deadSession'); - - var nowPlayingItem = session.NowPlayingItem; - - if (nowPlayingItem) { - row.addClass('playingSession'); - } else { - row.removeClass('playingSession'); - } - - $('.sessionNowPlayingStreamInfo', row).html(DashboardPage.getSessionNowPlayingStreamInfo(session)); - $('.sessionNowPlayingTime', row).html(DashboardPage.getSessionNowPlayingTime(session)); - - $('.sessionUserName', row).html(DashboardPage.getUsersHtml(session) || ' '); - - $('.sessionAppSecondaryText', row).html(DashboardPage.getAppSecondaryText(session)); - - $('.sessionTranscodingFramerate', row).html((session.TranscodingInfo && session.TranscodingInfo.Framerate) ? session.TranscodingInfo.Framerate + ' fps' : ''); - - var nowPlayingName = DashboardPage.getNowPlayingName(session); - var nowPlayingInfoElem = $('.sessionNowPlayingInfo', row); - - if (!nowPlayingName.image || nowPlayingName.image != nowPlayingInfoElem.attr('data-imgsrc')) { - nowPlayingInfoElem.html(nowPlayingName.html); - nowPlayingInfoElem.attr('data-imgsrc', nowPlayingName.image || ''); - } - - if (nowPlayingItem && nowPlayingItem.RunTimeTicks) { - - var position = session.PlayState.PositionTicks || 0; - var value = (100 * position) / nowPlayingItem.RunTimeTicks; - - $('.playbackProgress', row).show().val(value); - } else { - $('.playbackProgress', row).hide(); - } - - if (session.TranscodingInfo && session.TranscodingInfo.CompletionPercentage) { - - row.addClass('transcodingSession'); - $('.transcodingProgress', row).show().val(session.TranscodingInfo.CompletionPercentage); - } else { - $('.transcodingProgress', row).hide(); - row.removeClass('transcodingSession'); - } - - var imgUrl = DashboardPage.getNowPlayingImageUrl(nowPlayingItem) || ''; - var imgElem = $('.sessionNowPlayingContent', row)[0]; - - if (imgUrl != imgElem.getAttribute('data-src')) { - imgElem.style.backgroundImage = imgUrl ? 'url(\'' + imgUrl + '\')' : ''; - imgElem.setAttribute('data-src', imgUrl); - } - }, - - getClientImage: function (connection) { - - var clientLowered = connection.Client.toLowerCase(); - var device = connection.DeviceName.toLowerCase(); - - if (connection.AppIconUrl) { - return ""; - } - - if (clientLowered == "dashboard" || clientLowered == "emby web client") { - - var imgUrl; - - if (device.indexOf('chrome') != -1) { - imgUrl = 'css/images/clients/chrome.png'; - } - else { - imgUrl = 'css/images/clients/html5.png'; - } - - return "Emby Web Client"; - } - if (clientLowered.indexOf('android') != -1) { - return ""; - } - if (clientLowered.indexOf('ios') != -1) { - return ""; - } - if (clientLowered == "mb-classic") { - - return ""; - } - if (clientLowered == "roku") { - - return ""; - } - if (clientLowered == "dlna") { - - return ""; - } - if (clientLowered == "kodi" || clientLowered == "xbmc") { - return ""; - } - if (clientLowered == "chromecast") { - - return ""; - } - - return null; - }, - - getNowPlayingImageUrl: function (item) { - - if (item && item.BackdropImageTag) { - - return ApiClient.getScaledImageUrl(item.BackdropItemId, { - type: "Backdrop", - width: 275, - tag: item.BackdropImageTag - }); - } - - if (item && item.ThumbImageTag) { - - return ApiClient.getScaledImageUrl(item.ThumbItemId, { - type: "Thumb", - width: 275, - tag: item.ThumbImageTag - }); - } - - if (item && item.PrimaryImageTag) { - - return ApiClient.getScaledImageUrl(item.PrimaryImageItemId, { - type: "Primary", - width: 275, - tag: item.PrimaryImageTag - }); - } - - return null; - }, - - systemUpdateTaskKey: "SystemUpdateTask", - - renderRunningTasks: function (page, tasks) { - - var html = ''; - - tasks = tasks.filter(function (t) { - return t.State != 'Idle' && !t.IsHidden; - }); - - if (tasks.filter(function (t) { - - return t.Key == DashboardPage.systemUpdateTaskKey; - - }).length) { - - $('#btnUpdateApplication', page).buttonEnabled(false); - } else { - $('#btnUpdateApplication', page).buttonEnabled(true); - } - - if (!tasks.length) { - $('#runningTasksCollapsible', page).hide(); - } else { - $('#runningTasksCollapsible', page).show(); - } - - for (var i = 0, length = tasks.length; i < length; i++) { - - var task = tasks[i]; - - html += '

'; - - html += task.Name + "
"; - - if (task.State == "Running") { - var progress = (task.CurrentProgressPercentage || 0).toFixed(1); - - html += ''; - html += '' + progress + '%'; - html += ''; - - html += "" + progress + "%"; - - html += ''; - } - else if (task.State == "Cancelling") { - html += '' + Globalize.translate('LabelStopping') + ''; - } - - html += '

'; - } - - - $('#divRunningTasks', page).html(html); - }, - - renderUrls: function (page, systemInfo) { - - var helpButton = '' + Globalize.translate('ButtonHelp') + ''; - - if (systemInfo.LocalAddress) { - - var localAccessHtml = Globalize.translate('LabelLocalAccessUrl', '' + systemInfo.LocalAddress + ''); - - $('.localUrl', page).html(localAccessHtml + helpButton).show().trigger('create'); - } else { - $('.externalUrl', page).hide(); - } - - if (systemInfo.WanAddress) { - - var externalUrl = systemInfo.WanAddress; - - var remoteAccessHtml = Globalize.translate('LabelRemoteAccessUrl', '' + externalUrl + ''); - - $('.externalUrl', page).html(remoteAccessHtml + helpButton).show().trigger('create'); - } else { - $('.externalUrl', page).hide(); - } - }, - - renderSupporterIcon: function (page, pluginSecurityInfo) { - - var imgUrl, text; - - var supporterIconContainer = page.querySelector('.supporterIconContainer'); - - if (!AppInfo.enableSupporterMembership) { - supporterIconContainer.classList.add('hide'); - } - else if (pluginSecurityInfo.IsMBSupporter) { - - supporterIconContainer.classList.remove('hide'); - - imgUrl = "css/images/supporter/supporterbadge.png"; - text = Globalize.translate('MessageThankYouForSupporting'); - - supporterIconContainer.innerHTML = '' + text + ''; - } else { - - supporterIconContainer.classList.add('hide'); - } - }, - - renderHasPendingRestart: function (page, hasPendingRestart) { - - if (!hasPendingRestart) { - - // Only check once every 30 mins - if (DashboardPage.lastAppUpdateCheck && (new Date().getTime() - DashboardPage.lastAppUpdateCheck) < 1800000) { - return; - } - - DashboardPage.lastAppUpdateCheck = new Date().getTime(); - - ApiClient.getAvailableApplicationUpdate().then(function (packageInfo) { - - var version = packageInfo[0]; - - if (!version) { - page.querySelector('#pUpToDate').classList.remove('hide'); - $('#pUpdateNow', page).hide(); - } else { - page.querySelector('#pUpToDate').classList.add('hide'); - - $('#pUpdateNow', page).show(); - - $('#newVersionNumber', page).html(Globalize.translate('VersionXIsAvailableForDownload').replace('{0}', version.versionStr)); - } - - }); - - } else { - - page.querySelector('#pUpToDate').classList.add('hide'); - - $('#pUpdateNow', page).hide(); - } - }, - - renderPendingInstallations: function (page, systemInfo) { - - if (systemInfo.CompletedInstallations.length) { - - $('#collapsiblePendingInstallations', page).show(); - - } else { - $('#collapsiblePendingInstallations', page).hide(); - - return; - } - - var html = ''; - - for (var i = 0, length = systemInfo.CompletedInstallations.length; i < length; i++) { - - var update = systemInfo.CompletedInstallations[i]; - - html += '
' + update.Name + ' (' + update.Version + ')
'; - } - - $('#pendingInstallations', page).html(html); - }, - - renderPluginUpdateInfo: function (page, forceUpdate) { - - // Only check once every 30 mins - if (!forceUpdate && DashboardPage.lastPluginUpdateCheck && (new Date().getTime() - DashboardPage.lastPluginUpdateCheck) < 1800000) { - return; - } - - DashboardPage.lastPluginUpdateCheck = new Date().getTime(); - - ApiClient.getAvailablePluginUpdates().then(function (updates) { - - var elem = $('#pPluginUpdates', page); - - if (updates.length) { - - elem.show(); - - } else { - elem.hide(); - - return; - } - var html = ''; - - for (var i = 0, length = updates.length; i < length; i++) { - - var update = updates[i]; - - html += '

' + Globalize.translate('NewVersionOfSomethingAvailable').replace('{0}', update.name) + '

'; - - html += ''; - } - - elem.html(html); - - }); - }, - - installPluginUpdate: function (button) { - - $(button).buttonEnabled(false); - - var name = button.getAttribute('data-name'); - var guid = button.getAttribute('data-guid'); - var version = button.getAttribute('data-version'); - var classification = button.getAttribute('data-classification'); - - Dashboard.showLoadingMsg(); - - ApiClient.installPlugin(name, guid, classification, version).then(function () { - - Dashboard.hideLoadingMsg(); - }); - }, - - updateApplication: function () { - - var page = $.mobile.activePage; - $('#btnUpdateApplication', page).buttonEnabled(false); - - Dashboard.showLoadingMsg(); - - ApiClient.getScheduledTasks().then(function (tasks) { - - var task = tasks.filter(function (t) { - - return t.Key == DashboardPage.systemUpdateTaskKey; - })[0]; - - ApiClient.startScheduledTask(task.Id).then(function () { - - DashboardPage.pollForInfo(page); - - Dashboard.hideLoadingMsg(); - }); - }); - }, - - stopTask: function (id) { - - var page = $.mobile.activePage; - - ApiClient.stopScheduledTask(id).then(function () { - - DashboardPage.pollForInfo(page); - }); - - }, - - restart: function () { - - require(['confirm'], function (confirm) { - - confirm({ - - title: Globalize.translate('HeaderRestart'), - text: Globalize.translate('MessageConfirmRestart'), - confirmText: Globalize.translate('ButtonRestart'), - primary: 'cancel' - - }).then(function () { - - $('#btnRestartServer').buttonEnabled(false); - $('#btnShutdown').buttonEnabled(false); - Dashboard.restartServer(); - }); - }); - }, - - shutdown: function () { - - require(['confirm'], function (confirm) { - - confirm({ - - title: Globalize.translate('HeaderShutdown'), - text: Globalize.translate('MessageConfirmShutdown'), - confirmText: Globalize.translate('ButtonShutdown'), - primary: 'cancel' - - }).then(function () { - - $('#btnRestartServer').buttonEnabled(false); - $('#btnShutdown').buttonEnabled(false); - ApiClient.shutdownServer(); - }); - }); - } - }; - - $(document).on('pageinit', "#dashboardPage", DashboardPage.onPageInit).on('pageshow', "#dashboardPage", DashboardPage.onPageShow).on('pagebeforehide', "#dashboardPage", DashboardPage.onPageHide); - - (function ($, document, window) { - - function getEntryHtml(entry) { - - var html = ''; - - html += '
'; - - var color = entry.Severity == 'Error' || entry.Severity == 'Fatal' || entry.Severity == 'Warn' ? '#cc0000' : '#52B54B'; - - if (entry.UserId && entry.UserPrimaryImageTag) { - - var userImgUrl = ApiClient.getUserImageUrl(entry.UserId, { - type: 'Primary', - tag: entry.UserPrimaryImageTag, - height: 40 - }); - - html += 'dvr'; - } - else { - html += 'dvr'; - } - - html += '
'; - - html += '
'; - html += entry.Name; - html += '
'; - - html += '
'; - var date = datetime.parseISO8601Date(entry.Date, true); - html += datetime.toLocaleString(date).toLowerCase(); - html += '
'; - - html += '
'; - html += entry.ShortOverview || ''; - html += '
'; - - html += '
'; - - html += '
'; - - return html; - } - - function renderList(elem, result, startIndex, limit) { - - var html = result.Items.map(getEntryHtml).join(''); - - if (result.TotalRecordCount > limit) { - - var query = { StartIndex: startIndex, Limit: limit }; - - html += LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false - }); - } - - $(elem).html(html); - - $('.btnNextPage', elem).on('click', function () { - reloadData(elem, startIndex + limit, limit); - }); - - $('.btnPreviousPage', elem).on('click', function () { - reloadData(elem, startIndex - limit, limit); - }); - - $('.btnShowOverview', elem).on('click', function () { - - var item = $(this).parents('.newsItem'); - var overview = $('.newsItemLongDescription', item).html(); - var name = $('.notificationName', item).html(); - - Dashboard.alert({ - message: '
' + overview + '
', - title: name - }); - }); - } - - function reloadData(elem, startIndex, limit) { - - if (startIndex == null) { - startIndex = parseInt(elem.getAttribute('data-activitystartindex') || '0'); - } - - limit = limit || parseInt(elem.getAttribute('data-activitylimit') || '7'); - - // Show last 24 hours - var minDate = new Date(); - minDate.setTime(minDate.getTime() - 86400000); - - ApiClient.getJSON(ApiClient.getUrl('System/ActivityLog/Entries', { - - startIndex: startIndex, - limit: limit, - minDate: minDate.toISOString() - - })).then(function (result) { - - elem.setAttribute('data-activitystartindex', startIndex); - elem.setAttribute('data-activitylimit', limit); - - renderList(elem, result, startIndex, limit); - }); - } - - function createList(elem) { - - elem.each(function () { - - reloadData(this); - - }).addClass('activityLogListWidget'); - - var apiClient = ApiClient; - - if (!apiClient) { - return; - } - - Events.on(apiClient, 'websocketopen', onSocketOpen); - Events.on(apiClient, 'websocketmessage', onSocketMessage); - } - - function startListening(apiClient) { - - if (apiClient.isWebSocketOpen()) { - apiClient.sendWebSocketMessage("ActivityLogEntryStart", "0,1500"); - } - - } - - function stopListening(apiClient) { - - if (apiClient.isWebSocketOpen()) { - apiClient.sendWebSocketMessage("ActivityLogEntryStop", "0,1500"); - } - - } - - function onSocketOpen() { - - var apiClient = ApiClient; - if (apiClient) { - startListening(apiClient); - } - } - - function onSocketMessage(e, data) { - - var msg = data; - - if (msg.MessageType === "ActivityLogEntry") { - $('.activityLogListWidget').each(function () { - - reloadData(this); - }); - } - } - - function destroyList(elem) { - - var apiClient = ApiClient; - - if (apiClient) { - Events.off(apiClient, 'websocketopen', onSocketOpen); - Events.off(apiClient, 'websocketmessage', onSocketMessage); - - stopListening(apiClient); - } - } - - $.fn.activityLogList = function (action) { - - if (action == 'destroy') { - this.removeClass('activityLogListWidget'); - destroyList(this); - } else { - createList(this); - } - - var apiClient = ApiClient; - - if (apiClient) { - startListening(apiClient); - } - - return this; - }; - - })(jQuery, document, window); - - (function ($, document, window) { - - var welcomeDismissValue = '12'; - var welcomeTourKey = 'welcomeTour'; - - function dismissWelcome(page, userId) { - - ApiClient.getDisplayPreferences('dashboard', userId, 'dashboard').then(function (result) { - - result.CustomPrefs[welcomeTourKey] = welcomeDismissValue; - ApiClient.updateDisplayPreferences('dashboard', result, userId, 'dashboard'); - - $(page).off('pageshow', onPageShowCheckTour); - }); - } - - function showWelcomeIfNeeded(page, apiClient) { - - var userId = Dashboard.getCurrentUserId(); - - apiClient.getDisplayPreferences('dashboard', userId, 'dashboard').then(function (result) { - - if (result.CustomPrefs[welcomeTourKey] == welcomeDismissValue) { - $('.welcomeMessage', page).hide(); - } else { - - var elem = $('.welcomeMessage', page).show(); - - if (result.CustomPrefs[welcomeTourKey]) { - - $('.tourHeader', elem).html(Globalize.translate('HeaderWelcomeBack')); - $('.tourButtonText', elem).html(Globalize.translate('ButtonTakeTheTourToSeeWhatsNew')); - - } else { - - $('.tourHeader', elem).html(Globalize.translate('HeaderWelcomeToProjectServerDashboard')); - $('.tourButtonText', elem).html(Globalize.translate('ButtonTakeTheTour')); - } - } - }); - } - - function takeTour(page, userId) { - - require(['slideshow'], function () { - - var slides = [ - { imageUrl: 'css/images/tour/admin/dashboard.png', title: Globalize.translate('DashboardTourDashboard') }, - { imageUrl: 'css/images/tour/admin/help.png', title: Globalize.translate('DashboardTourHelp') }, - { imageUrl: 'css/images/tour/admin/users.png', title: Globalize.translate('DashboardTourUsers') }, - { imageUrl: 'css/images/tour/admin/sync.png', title: Globalize.translate('DashboardTourSync') }, - { imageUrl: 'css/images/tour/admin/cinemamode.png', title: Globalize.translate('DashboardTourCinemaMode') }, - { imageUrl: 'css/images/tour/admin/chapters.png', title: Globalize.translate('DashboardTourChapters') }, - { imageUrl: 'css/images/tour/admin/subtitles.png', title: Globalize.translate('DashboardTourSubtitles') }, - { imageUrl: 'css/images/tour/admin/plugins.png', title: Globalize.translate('DashboardTourPlugins') }, - { imageUrl: 'css/images/tour/admin/notifications.png', title: Globalize.translate('DashboardTourNotifications') }, - { imageUrl: 'css/images/tour/admin/scheduledtasks.png', title: Globalize.translate('DashboardTourScheduledTasks') }, - { imageUrl: 'css/images/tour/admin/mobile.png', title: Globalize.translate('DashboardTourMobile') }, - { imageUrl: 'css/images/tour/enjoy.jpg', title: Globalize.translate('MessageEnjoyYourStay') } - ]; - - require(['slideshow'], function (slideshow) { - - var newSlideShow = new slideshow({ - slides: slides, - interactive: true, - loop: false - }); - - newSlideShow.show(); - - dismissWelcome(page, userId); - $('.welcomeMessage', page).hide(); - }); - }); - } - - function onPageShowCheckTour() { - var page = this; - - var apiClient = ApiClient; - - if (apiClient && !AppInfo.isNativeApp) { - showWelcomeIfNeeded(page, apiClient); - } - } - - $(document).on('pageinit', "#dashboardPage", function () { - - var page = this; - - $('.btnTakeTour', page).on('click', function () { - takeTour(page, Dashboard.getCurrentUserId()); - }); - - }).on('pageshow', "#dashboardPage", onPageShowCheckTour); - - })(jQuery, document, window); - - pageClassOn('pageshow', "type-interior", function () { - - var page = this; - - Dashboard.getPluginSecurityInfo().then(function (pluginSecurityInfo) { - - if (!page.querySelector('.customSupporterPromotion')) { - - $('.supporterPromotion', page).remove(); - - if (!pluginSecurityInfo.IsMBSupporter && AppInfo.enableSupporterMembership) { - - var html = ''; - - page.querySelector('.content-primary').insertAdjacentHTML('afterbegin', html); - } - } - }); - - }); -}); \ No newline at end of file +define(["datetime","jQuery","dom","humanedate","cardStyle","listViewStyle"],function(datetime,$,dom){"use strict";function renderNoHealthAlertsMessage(page){var html='

';html+='',html+=Globalize.translate("HealthMonitorNoAlerts")+"

",page.querySelector(".healthMonitor").innerHTML=html}function refreshHealthMonitor(page){renderNoHealthAlertsMessage(page)}function onConnectionHelpClick(e){return e.preventDefault(),!1}function onEditServerNameClick(e){var page=dom.parentWithClass(this,"page");return require(["prompt"],function(prompt){prompt({label:Globalize.translate("LabelFriendlyServerName"),description:Globalize.translate("LabelFriendlyServerNameHelp"),value:page.querySelector(".serverNameHeader").innerHTML,confirmText:Globalize.translate("ButtonSave")}).then(function(value){Dashboard.showLoadingMsg(),ApiClient.getServerConfiguration().then(function(config){config.ServerName=value,ApiClient.updateServerConfiguration(config).then(function(){page.querySelector(".serverNameHeader").innerHTML=value,Dashboard.hideLoadingMsg()})})})}),e.preventDefault(),!1}window.DashboardPage={newsStartIndex:0,onPageInit:function(){var page=this;page.querySelector(".btnConnectionHelp").addEventListener("click",onConnectionHelpClick),page.querySelector(".btnEditServerName").addEventListener("click",onEditServerNameClick)},onPageShow:function(){var page=this,apiClient=ApiClient;apiClient&&(DashboardPage.newsStartIndex=0,Dashboard.showLoadingMsg(),DashboardPage.pollForInfo(page),DashboardPage.startInterval(apiClient),Events.on(apiClient,"websocketmessage",DashboardPage.onWebSocketMessage),Events.on(apiClient,"websocketopen",DashboardPage.onWebSocketOpen),DashboardPage.lastAppUpdateCheck=null,DashboardPage.lastPluginUpdateCheck=null,Dashboard.getPluginSecurityInfo().then(function(pluginSecurityInfo){DashboardPage.renderSupporterIcon(page,pluginSecurityInfo)}),DashboardPage.reloadSystemInfo(page),DashboardPage.reloadNews(page),DashboardPage.sessionUpdateTimer=setInterval(DashboardPage.refreshSessionsLocally,6e4),$(".activityItems",page).activityLogList(),$(".swaggerLink",page).attr("href",apiClient.getUrl("swagger-ui/index.html",{api_key:ApiClient.accessToken()})),refreshHealthMonitor(page))},onPageHide:function(){var page=this;$(".activityItems",page).activityLogList("destroy");var apiClient=ApiClient;apiClient&&(Events.off(apiClient,"websocketmessage",DashboardPage.onWebSocketMessage),Events.off(apiClient,"websocketopen",DashboardPage.onWebSocketOpen),DashboardPage.stopInterval(apiClient)),DashboardPage.sessionUpdateTimer&&clearInterval(DashboardPage.sessionUpdateTimer)},renderPaths:function(page,systemInfo){$("#cachePath",page).html(systemInfo.CachePath),$("#logPath",page).html(systemInfo.LogPath),$("#transcodingTemporaryPath",page).html(systemInfo.TranscodingTempPath),$("#metadataPath",page).html(systemInfo.InternalMetadataPath)},refreshSessionsLocally:function(){var list=DashboardPage.sessionsList;list&&DashboardPage.renderActiveConnections($.mobile.activePage,list)},reloadSystemInfo:function(page){ApiClient.getSystemInfo().then(function(systemInfo){page.querySelector(".serverNameHeader").innerHTML=systemInfo.ServerName;var localizedVersion=Globalize.translate("LabelVersionNumber",systemInfo.Version);systemInfo.SystemUpdateLevel&&"Release"!=systemInfo.SystemUpdateLevel&&(localizedVersion+=" "+Globalize.translate("Option"+systemInfo.SystemUpdateLevel).toLowerCase()),$("#appVersionNumber",page).html(localizedVersion),systemInfo.SupportsHttps?$("#ports",page).html(Globalize.translate("LabelRunningOnPorts",systemInfo.HttpServerPortNumber,systemInfo.HttpsPortNumber)):$("#ports",page).html(Globalize.translate("LabelRunningOnPort",systemInfo.HttpServerPortNumber)),systemInfo.CanSelfRestart?$(".btnRestartContainer",page).removeClass("hide"):$(".btnRestartContainer",page).addClass("hide"),DashboardPage.renderUrls(page,systemInfo),DashboardPage.renderPendingInstallations(page,systemInfo),systemInfo.CanSelfUpdate?($("#btnUpdateApplicationContainer",page).show(),$("#btnManualUpdateContainer",page).hide()):($("#btnUpdateApplicationContainer",page).hide(),$("#btnManualUpdateContainer",page).show()),"synology"==systemInfo.PackageName?$("#btnManualUpdateContainer").html(Globalize.translate("SynologyUpdateInstructions")):$("#btnManualUpdateContainer").html(''+Globalize.translate("PleaseUpdateManually")+""),DashboardPage.renderPaths(page,systemInfo),DashboardPage.renderHasPendingRestart(page,systemInfo.HasPendingRestart)})},reloadNews:function(page){var query={StartIndex:DashboardPage.newsStartIndex,Limit:7};ApiClient.getProductNews(query).then(function(result){var html=result.Items.map(function(item){var itemHtml="";itemHtml+='',itemHtml+='
',itemHtml+='dvr',itemHtml+='
',itemHtml+='
',itemHtml+=item.Title,itemHtml+="
",itemHtml+='
';var date=datetime.parseISO8601Date(item.Date,!0);return itemHtml+=datetime.toLocaleDateString(date),itemHtml+="
",itemHtml+="
",itemHtml+="
",itemHtml+="
"}),pagingHtml="";pagingHtml+="
",pagingHtml+=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1}),pagingHtml+="
",html=html.join("")+pagingHtml;var elem=$(".latestNewsItems",page).html(html);$(".btnNextPage",elem).on("click",function(){DashboardPage.newsStartIndex+=query.Limit,DashboardPage.reloadNews(page)}),$(".btnPreviousPage",elem).on("click",function(){DashboardPage.newsStartIndex-=query.Limit,DashboardPage.reloadNews(page)})})},startInterval:function(apiClient){apiClient.isWebSocketOpen()&&(apiClient.sendWebSocketMessage("SessionsStart","0,1500"),apiClient.sendWebSocketMessage("ScheduledTasksInfoStart","0,1000"))},stopInterval:function(apiClient){apiClient.isWebSocketOpen()&&(apiClient.sendWebSocketMessage("SessionsStop"),apiClient.sendWebSocketMessage("ScheduledTasksInfoStop"))},onWebSocketMessage:function(e,msg){var page=$.mobile.activePage;if("Sessions"==msg.MessageType)DashboardPage.renderInfo(page,msg.Data);else if("RestartRequired"==msg.MessageType)DashboardPage.renderHasPendingRestart(page,!0);else if("ServerShuttingDown"==msg.MessageType)DashboardPage.renderHasPendingRestart(page,!0);else if("ServerRestarting"==msg.MessageType)DashboardPage.renderHasPendingRestart(page,!0);else if("ScheduledTasksInfo"==msg.MessageType){var tasks=msg.Data;DashboardPage.renderRunningTasks(page,tasks)}else"PackageInstalling"!=msg.MessageType&&"PackageInstallationCompleted"!=msg.MessageType||(DashboardPage.pollForInfo(page,!0),DashboardPage.reloadSystemInfo(page))},onWebSocketOpen:function(){var apiClient=this;DashboardPage.startInterval(apiClient)},pollForInfo:function(page,forceUpdate){var apiClient=window.ApiClient;apiClient&&(apiClient.getSessions().then(function(sessions){DashboardPage.renderInfo(page,sessions,forceUpdate)}),apiClient.getScheduledTasks().then(function(tasks){DashboardPage.renderRunningTasks(page,tasks)}))},renderInfo:function(page,sessions,forceUpdate){DashboardPage.renderActiveConnections(page,sessions),DashboardPage.renderPluginUpdateInfo(page,forceUpdate),Dashboard.hideLoadingMsg()},renderActiveConnections:function(page,sessions){var html="";DashboardPage.sessionsList=sessions;var parentElement=$(".activeDevices",page);$(".card",parentElement).addClass("deadSession");for(var i=0,length=sessions.length;i',html+='
',html+='
',html+='
',html+='
',html+='
',html+='
'+session.DeviceName+"
",html+='
'+DashboardPage.getAppSecondaryText(session)+"
",html+="
",html+="
",html+='
'+DashboardPage.getSessionNowPlayingTime(session)+"
";var nowPlayingName=DashboardPage.getNowPlayingName(session);if(html+='
',html+=nowPlayingName.html,html+="
",nowPlayingItem&&nowPlayingItem.RunTimeTicks){var position=session.PlayState.PositionTicks||0,value=100*position/nowPlayingItem.RunTimeTicks;html+=''}else html+='';html+=session.TranscodingInfo&&session.TranscodingInfo.CompletionPercentage?'':'',html+="
",html+="
",html+="",html+='
',html+='
',html+=DashboardPage.getSessionNowPlayingStreamInfo(session),html+="
",html+='
';var userImage=DashboardPage.getUserImage(session);html+=userImage?'':'
',html+='
',html+=DashboardPage.getUsersHtml(session)||" ",html+="
",html+="
",html+="
",html+="",html+=""}}parentElement.append(html),$(".deadSession",parentElement).remove()},getSessionNowPlayingStreamInfo:function(session){var html="",showTranscodingInfo=!1;if(session.TranscodingInfo&&session.TranscodingInfo.IsAudioDirect&&session.TranscodingInfo.IsVideoDirect?html+=Globalize.translate("LabelPlayMethodDirectStream"):session.TranscodingInfo&&session.TranscodingInfo.IsVideoDirect?html+=Globalize.translate("LabelPlayMethodDirectStream"):"Transcode"==session.PlayState.PlayMethod?(html+=Globalize.translate("LabelPlayMethodTranscoding"),session.TranscodingInfo&&session.TranscodingInfo.Framerate&&(html+=" ("+session.TranscodingInfo.Framerate+" fps)"),showTranscodingInfo=!0):"DirectStream"==session.PlayState.PlayMethod?html+=Globalize.translate("LabelPlayMethodDirectPlay"):"DirectPlay"==session.PlayState.PlayMethod&&(html+=Globalize.translate("LabelPlayMethodDirectPlay")),showTranscodingInfo){var line=[];session.TranscodingInfo&&(session.TranscodingInfo.Bitrate&&(session.TranscodingInfo.Bitrate>1e6?line.push((session.TranscodingInfo.Bitrate/1e6).toFixed(1)+" Mbps"):line.push(Math.floor(session.TranscodingInfo.Bitrate/1e3)+" kbps")),session.TranscodingInfo.Container&&line.push(session.TranscodingInfo.Container),session.TranscodingInfo.VideoCodec&&line.push(session.TranscodingInfo.VideoCodec),session.TranscodingInfo.AudioCodec&&session.TranscodingInfo.AudioCodec!=session.TranscodingInfo.Container&&line.push(session.TranscodingInfo.AudioCodec)),line.length&&(html+=" - "+line.join(" "))}return html||" "},getSessionNowPlayingTime:function(session){var html="";html+=session.PlayState.PositionTicks?datetime.getDisplayRunningTime(session.PlayState.PositionTicks):"--:--:--",html+=" / ";var nowPlayingItem=session.NowPlayingItem;return html+=nowPlayingItem&&nowPlayingItem.RunTimeTicks?datetime.getDisplayRunningTime(nowPlayingItem.RunTimeTicks):"--:--:--"},getAppSecondaryText:function(session){return session.ApplicationVersion},getNowPlayingName:function(session){var imgUrl="",nowPlayingItem=session.NowPlayingItem;if(!nowPlayingItem)return{html:"Last seen "+humane_date(session.LastActivityDate),image:imgUrl};var topText=nowPlayingItem.Name,bottomText="";nowPlayingItem.Artists&&nowPlayingItem.Artists.length?(bottomText=topText,topText=nowPlayingItem.Artists[0]):nowPlayingItem.SeriesName||nowPlayingItem.Album?(bottomText=topText,topText=nowPlayingItem.SeriesName||nowPlayingItem.Album):nowPlayingItem.ProductionYear&&(bottomText=nowPlayingItem.ProductionYear),nowPlayingItem.LogoItemId&&(imgUrl=ApiClient.getScaledImageUrl(nowPlayingItem.LogoItemId,{tag:session.LogoImageTag,maxHeight:24,maxWidth:130,type:"Logo"}),topText='');var text=bottomText?topText+"
"+bottomText:topText;return{html:text,image:imgUrl}},getUsersHtml:function(session){var html=[];session.UserId&&html.push(session.UserName);for(var i=0,length=session.AdditionalUsers.length;i";if("dashboard"==clientLowered||"emby web client"==clientLowered){var imgUrl;return imgUrl=device.indexOf("chrome")!=-1?"css/images/clients/chrome.png":"css/images/clients/html5.png","Emby Web Client"}return clientLowered.indexOf("android")!=-1?"":clientLowered.indexOf("ios")!=-1?"":"mb-classic"==clientLowered?"":"roku"==clientLowered?"":"dlna"==clientLowered?"":"kodi"==clientLowered||"xbmc"==clientLowered?"":"chromecast"==clientLowered?"":null},getNowPlayingImageUrl:function(item){return item&&item.BackdropImageTag?ApiClient.getScaledImageUrl(item.BackdropItemId,{type:"Backdrop",width:275,tag:item.BackdropImageTag}):item&&item.ThumbImageTag?ApiClient.getScaledImageUrl(item.ThumbItemId,{type:"Thumb",width:275,tag:item.ThumbImageTag}):item&&item.PrimaryImageTag?ApiClient.getScaledImageUrl(item.PrimaryImageItemId,{type:"Primary",width:275,tag:item.PrimaryImageTag}):null},systemUpdateTaskKey:"SystemUpdateTask",renderRunningTasks:function(page,tasks){var html="";tasks=tasks.filter(function(t){return"Idle"!=t.State&&!t.IsHidden}),tasks.filter(function(t){return t.Key==DashboardPage.systemUpdateTaskKey}).length?$("#btnUpdateApplication",page).buttonEnabled(!1):$("#btnUpdateApplication",page).buttonEnabled(!0),tasks.length?$("#runningTasksCollapsible",page).show():$("#runningTasksCollapsible",page).hide();for(var i=0,length=tasks.length;i",html+=task.Name+"
","Running"==task.State){var progress=(task.CurrentProgressPercentage||0).toFixed(1);html+='',html+=""+progress+"%",html+="",html+=""+progress+"%",html+=''}else"Cancelling"==task.State&&(html+=''+Globalize.translate("LabelStopping")+"");html+="

"}$("#divRunningTasks",page).html(html)},renderUrls:function(page,systemInfo){var helpButton=''+Globalize.translate("ButtonHelp")+"";if(systemInfo.LocalAddress){var localAccessHtml=Globalize.translate("LabelLocalAccessUrl",''+systemInfo.LocalAddress+"");$(".localUrl",page).html(localAccessHtml+helpButton).show().trigger("create")}else $(".externalUrl",page).hide();if(systemInfo.WanAddress){var externalUrl=systemInfo.WanAddress,remoteAccessHtml=Globalize.translate("LabelRemoteAccessUrl",''+externalUrl+"");$(".externalUrl",page).html(remoteAccessHtml+helpButton).show().trigger("create")}else $(".externalUrl",page).hide()},renderSupporterIcon:function(page,pluginSecurityInfo){var imgUrl,text,supporterIconContainer=page.querySelector(".supporterIconContainer");AppInfo.enableSupporterMembership&&pluginSecurityInfo.IsMBSupporter?(supporterIconContainer.classList.remove("hide"),imgUrl="css/images/supporter/supporterbadge.png",text=Globalize.translate("MessageThankYouForSupporting"),supporterIconContainer.innerHTML=''+text+""):supporterIconContainer.classList.add("hide")},renderHasPendingRestart:function(page,hasPendingRestart){if(hasPendingRestart)page.querySelector("#pUpToDate").classList.add("hide"),$("#pUpdateNow",page).hide();else{if(DashboardPage.lastAppUpdateCheck&&(new Date).getTime()-DashboardPage.lastAppUpdateCheck<18e5)return;DashboardPage.lastAppUpdateCheck=(new Date).getTime(),ApiClient.getAvailableApplicationUpdate().then(function(packageInfo){var version=packageInfo[0];version?(page.querySelector("#pUpToDate").classList.add("hide"),$("#pUpdateNow",page).show(),$("#newVersionNumber",page).html(Globalize.translate("VersionXIsAvailableForDownload").replace("{0}",version.versionStr))):(page.querySelector("#pUpToDate").classList.remove("hide"),$("#pUpdateNow",page).hide())})}},renderPendingInstallations:function(page,systemInfo){if(!systemInfo.CompletedInstallations.length)return void $("#collapsiblePendingInstallations",page).hide();$("#collapsiblePendingInstallations",page).show();for(var html="",i=0,length=systemInfo.CompletedInstallations.length;i"+update.Name+" ("+update.Version+")"}$("#pendingInstallations",page).html(html)},renderPluginUpdateInfo:function(page,forceUpdate){!forceUpdate&&DashboardPage.lastPluginUpdateCheck&&(new Date).getTime()-DashboardPage.lastPluginUpdateCheck<18e5||(DashboardPage.lastPluginUpdateCheck=(new Date).getTime(),ApiClient.getAvailablePluginUpdates().then(function(updates){var elem=$("#pPluginUpdates",page);if(!updates.length)return void elem.hide();elem.show();for(var html="",i=0,length=updates.length;i"+Globalize.translate("NewVersionOfSomethingAvailable").replace("{0}",update.name)+"

",html+='"}elem.html(html)}))},installPluginUpdate:function(button){$(button).buttonEnabled(!1);var name=button.getAttribute("data-name"),guid=button.getAttribute("data-guid"),version=button.getAttribute("data-version"),classification=button.getAttribute("data-classification");Dashboard.showLoadingMsg(),ApiClient.installPlugin(name,guid,classification,version).then(function(){Dashboard.hideLoadingMsg()})},updateApplication:function(){var page=$.mobile.activePage;$("#btnUpdateApplication",page).buttonEnabled(!1),Dashboard.showLoadingMsg(),ApiClient.getScheduledTasks().then(function(tasks){var task=tasks.filter(function(t){return t.Key==DashboardPage.systemUpdateTaskKey})[0];ApiClient.startScheduledTask(task.Id).then(function(){DashboardPage.pollForInfo(page),Dashboard.hideLoadingMsg()})})},stopTask:function(id){var page=$.mobile.activePage;ApiClient.stopScheduledTask(id).then(function(){DashboardPage.pollForInfo(page)})},restart:function(){require(["confirm"],function(confirm){confirm({title:Globalize.translate("HeaderRestart"),text:Globalize.translate("MessageConfirmRestart"),confirmText:Globalize.translate("ButtonRestart"),primary:"cancel"}).then(function(){$("#btnRestartServer").buttonEnabled(!1),$("#btnShutdown").buttonEnabled(!1),Dashboard.restartServer()})})},shutdown:function(){require(["confirm"],function(confirm){confirm({title:Globalize.translate("HeaderShutdown"),text:Globalize.translate("MessageConfirmShutdown"),confirmText:Globalize.translate("ButtonShutdown"),primary:"cancel"}).then(function(){$("#btnRestartServer").buttonEnabled(!1),$("#btnShutdown").buttonEnabled(!1),ApiClient.shutdownServer()})})}},$(document).on("pageinit","#dashboardPage",DashboardPage.onPageInit).on("pageshow","#dashboardPage",DashboardPage.onPageShow).on("pagebeforehide","#dashboardPage",DashboardPage.onPageHide),function($,document,window){function getEntryHtml(entry){var html="";html+='
';var color="Error"==entry.Severity||"Fatal"==entry.Severity||"Warn"==entry.Severity?"#cc0000":"#52B54B";if(entry.UserId&&entry.UserPrimaryImageTag){var userImgUrl=ApiClient.getUserImageUrl(entry.UserId,{type:"Primary",tag:entry.UserPrimaryImageTag,height:40});html+='dvr"}else html+='dvr';html+='
',html+='
',html+=entry.Name,html+="
",html+='
';var date=datetime.parseISO8601Date(entry.Date,!0);return html+=datetime.toLocaleString(date).toLowerCase(),html+="
",html+='
',html+=entry.ShortOverview||"",html+="
",html+="
",html+="
"}function renderList(elem,result,startIndex,limit){var html=result.Items.map(getEntryHtml).join("");if(result.TotalRecordCount>limit){var query={StartIndex:startIndex,Limit:limit};html+=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1})}$(elem).html(html),$(".btnNextPage",elem).on("click",function(){reloadData(elem,startIndex+limit,limit)}),$(".btnPreviousPage",elem).on("click",function(){reloadData(elem,startIndex-limit,limit)}),$(".btnShowOverview",elem).on("click",function(){var item=$(this).parents(".newsItem"),overview=$(".newsItemLongDescription",item).html(),name=$(".notificationName",item).html();Dashboard.alert({message:'
'+overview+"
",title:name})})}function reloadData(elem,startIndex,limit){null==startIndex&&(startIndex=parseInt(elem.getAttribute("data-activitystartindex")||"0")),limit=limit||parseInt(elem.getAttribute("data-activitylimit")||"7");var minDate=new Date;minDate.setTime(minDate.getTime()-864e5),ApiClient.getJSON(ApiClient.getUrl("System/ActivityLog/Entries",{startIndex:startIndex,limit:limit,minDate:minDate.toISOString()})).then(function(result){elem.setAttribute("data-activitystartindex",startIndex),elem.setAttribute("data-activitylimit",limit),renderList(elem,result,startIndex,limit)})}function createList(elem){elem.each(function(){reloadData(this)}).addClass("activityLogListWidget");var apiClient=ApiClient;apiClient&&(Events.on(apiClient,"websocketopen",onSocketOpen),Events.on(apiClient,"websocketmessage",onSocketMessage))}function startListening(apiClient){apiClient.isWebSocketOpen()&&apiClient.sendWebSocketMessage("ActivityLogEntryStart","0,1500")}function stopListening(apiClient){apiClient.isWebSocketOpen()&&apiClient.sendWebSocketMessage("ActivityLogEntryStop","0,1500")}function onSocketOpen(){var apiClient=ApiClient;apiClient&&startListening(apiClient)}function onSocketMessage(e,data){var msg=data;"ActivityLogEntry"===msg.MessageType&&$(".activityLogListWidget").each(function(){reloadData(this)})}function destroyList(elem){var apiClient=ApiClient;apiClient&&(Events.off(apiClient,"websocketopen",onSocketOpen),Events.off(apiClient,"websocketmessage",onSocketMessage),stopListening(apiClient))}$.fn.activityLogList=function(action){"destroy"==action?(this.removeClass("activityLogListWidget"),destroyList(this)):createList(this);var apiClient=ApiClient;return apiClient&&startListening(apiClient),this}}(jQuery,document,window),function($,document,window){function dismissWelcome(page,userId){ApiClient.getDisplayPreferences("dashboard",userId,"dashboard").then(function(result){result.CustomPrefs[welcomeTourKey]=welcomeDismissValue,ApiClient.updateDisplayPreferences("dashboard",result,userId,"dashboard"),$(page).off("pageshow",onPageShowCheckTour)})}function showWelcomeIfNeeded(page,apiClient){var userId=Dashboard.getCurrentUserId();apiClient.getDisplayPreferences("dashboard",userId,"dashboard").then(function(result){if(result.CustomPrefs[welcomeTourKey]==welcomeDismissValue)$(".welcomeMessage",page).hide();else{var elem=$(".welcomeMessage",page).show();result.CustomPrefs[welcomeTourKey]?($(".tourHeader",elem).html(Globalize.translate("HeaderWelcomeBack")),$(".tourButtonText",elem).html(Globalize.translate("ButtonTakeTheTourToSeeWhatsNew"))):($(".tourHeader",elem).html(Globalize.translate("HeaderWelcomeToProjectServerDashboard")),$(".tourButtonText",elem).html(Globalize.translate("ButtonTakeTheTour")))}})}function takeTour(page,userId){require(["slideshow"],function(){var slides=[{imageUrl:"css/images/tour/admin/dashboard.png",title:Globalize.translate("DashboardTourDashboard")},{imageUrl:"css/images/tour/admin/help.png",title:Globalize.translate("DashboardTourHelp")},{imageUrl:"css/images/tour/admin/users.png",title:Globalize.translate("DashboardTourUsers")},{imageUrl:"css/images/tour/admin/sync.png",title:Globalize.translate("DashboardTourSync")},{imageUrl:"css/images/tour/admin/cinemamode.png",title:Globalize.translate("DashboardTourCinemaMode")},{imageUrl:"css/images/tour/admin/chapters.png",title:Globalize.translate("DashboardTourChapters")},{imageUrl:"css/images/tour/admin/subtitles.png",title:Globalize.translate("DashboardTourSubtitles")},{imageUrl:"css/images/tour/admin/plugins.png",title:Globalize.translate("DashboardTourPlugins")},{imageUrl:"css/images/tour/admin/notifications.png",title:Globalize.translate("DashboardTourNotifications")},{imageUrl:"css/images/tour/admin/scheduledtasks.png",title:Globalize.translate("DashboardTourScheduledTasks")},{imageUrl:"css/images/tour/admin/mobile.png",title:Globalize.translate("DashboardTourMobile")},{imageUrl:"css/images/tour/enjoy.jpg",title:Globalize.translate("MessageEnjoyYourStay")}];require(["slideshow"],function(slideshow){var newSlideShow=new slideshow({slides:slides,interactive:!0,loop:!1});newSlideShow.show(),dismissWelcome(page,userId),$(".welcomeMessage",page).hide()})})}function onPageShowCheckTour(){var page=this,apiClient=ApiClient;apiClient&&!AppInfo.isNativeApp&&showWelcomeIfNeeded(page,apiClient)}var welcomeDismissValue="12",welcomeTourKey="welcomeTour";$(document).on("pageinit","#dashboardPage",function(){var page=this;$(".btnTakeTour",page).on("click",function(){takeTour(page,Dashboard.getCurrentUserId())})}).on("pageshow","#dashboardPage",onPageShowCheckTour)}(jQuery,document,window),pageClassOn("pageshow","type-interior",function(){var page=this;Dashboard.getPluginSecurityInfo().then(function(pluginSecurityInfo){if(!page.querySelector(".customSupporterPromotion")&&($(".supporterPromotion",page).remove(),!pluginSecurityInfo.IsMBSupporter&&AppInfo.enableSupporterMembership)){var html='";page.querySelector(".content-primary").insertAdjacentHTML("afterbegin",html)}})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/device.js b/dashboard-ui/scripts/device.js index 5948801287..d53bb52291 100644 --- a/dashboard-ui/scripts/device.js +++ b/dashboard-ui/scripts/device.js @@ -1,96 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function load(page, device, capabilities) { - - if (capabilities.SupportsContentUploading) { - $('#fldCameraUploadPath', page).removeClass('hide'); - } else { - $('#fldCameraUploadPath', page).addClass('hide'); - } - - $('#txtCustomName', page).val(device.CustomName || ''); - $('#txtUploadPath', page).val(device.CameraUploadPath || ''); - $('.reportedName', page).html(device.ReportedName || ''); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - var id = getParameterByName('id'); - - var promise1 = ApiClient.getJSON(ApiClient.getUrl('Devices/Info', { Id: id })); - var promise2 = ApiClient.getJSON(ApiClient.getUrl('Devices/Capabilities', { Id: id })); - - Promise.all([promise1, promise2]).then(function (responses) { - - load(page, responses[0], responses[1]); - - Dashboard.hideLoadingMsg(); - }); - } - - function save(page) { - - var id = getParameterByName('id'); - - ApiClient.ajax({ - - url: ApiClient.getUrl('Devices/Options', { Id: id }), - type: 'POST', - data: JSON.stringify({ - - CustomName: $('#txtCustomName', page).val(), - CameraUploadPath: $('#txtUploadPath', page).val() - - }), - contentType: "application/json" - - }).then(Dashboard.processServerConfigurationUpdateResult); - } - - function onSubmit() { - var form = this; - var page = $(form).parents('.page'); - - save(page); - - return false; - } - - $(document).on('pageinit', "#devicePage", function () { - - var page = this; - - $('#btnSelectUploadPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - $('#txtUploadPath', page).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectUploadPath') - }); - }); - }); - - $('.deviceForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#devicePage", function () { - - var page = this; - - loadData(page); - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function load(page,device,capabilities){capabilities.SupportsContentUploading?$("#fldCameraUploadPath",page).removeClass("hide"):$("#fldCameraUploadPath",page).addClass("hide"),$("#txtCustomName",page).val(device.CustomName||""),$("#txtUploadPath",page).val(device.CameraUploadPath||""),$(".reportedName",page).html(device.ReportedName||"")}function loadData(page){Dashboard.showLoadingMsg();var id=getParameterByName("id"),promise1=ApiClient.getJSON(ApiClient.getUrl("Devices/Info",{Id:id})),promise2=ApiClient.getJSON(ApiClient.getUrl("Devices/Capabilities",{Id:id}));Promise.all([promise1,promise2]).then(function(responses){load(page,responses[0],responses[1]),Dashboard.hideLoadingMsg()})}function save(page){var id=getParameterByName("id");ApiClient.ajax({url:ApiClient.getUrl("Devices/Options",{Id:id}),type:"POST",data:JSON.stringify({CustomName:$("#txtCustomName",page).val(),CameraUploadPath:$("#txtUploadPath",page).val()}),contentType:"application/json"}).then(Dashboard.processServerConfigurationUpdateResult)}function onSubmit(){var form=this,page=$(form).parents(".page");return save(page),!1}$(document).on("pageinit","#devicePage",function(){var page=this;$("#btnSelectUploadPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtUploadPath",page).val(path),picker.close()},header:Globalize.translate("HeaderSelectUploadPath")})})}),$(".deviceForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#devicePage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/devices.js b/dashboard-ui/scripts/devices.js index 12f5c37e56..7dafef7422 100644 --- a/dashboard-ui/scripts/devices.js +++ b/dashboard-ui/scripts/devices.js @@ -1,113 +1 @@ -define(['jQuery', 'listViewStyle'], function ($) { - 'use strict'; - - function deleteDevice(page, id) { - - var msg = Globalize.translate('DeleteDeviceConfirmation'); - - require(['confirm'], function (confirm) { - - confirm(msg, Globalize.translate('HeaderDeleteDevice')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl('Devices', { - Id: id - }) - - }).then(function () { - - loadData(page); - }); - }); - - }); - } - - function load(page, devices) { - - var html = ''; - - if (devices.length) { - html += '
'; - } - - html += devices.map(function (d) { - - var deviceHtml = ''; - deviceHtml += '
'; - - deviceHtml += 'tablet_android'; - - if (d.AppName && d.LastUserName) { - deviceHtml += ''; - - return deviceHtml; - - }).join(''); - - if (devices.length) { - html += '
'; - } - - var elem = $('.devicesList', page).html(html).trigger('create'); - - $('.btnDeleteDevice', elem).on('click', function () { - - deleteDevice(page, this.getAttribute('data-id')); - }); - } - - function loadData(page) { - Dashboard.showLoadingMsg(); - - ApiClient.getJSON(ApiClient.getUrl('Devices', { - - SupportsPersistentIdentifier: true - - })).then(function (result) { - - load(page, result.Items); - - Dashboard.hideLoadingMsg(); - }); - } - - $(document).on('pageshow', "#devicesPage", function () { - - var page = this; - - loadData(page); - - }); - -}); \ No newline at end of file +define(["jQuery","listViewStyle"],function($){"use strict";function deleteDevice(page,id){var msg=Globalize.translate("DeleteDeviceConfirmation");require(["confirm"],function(confirm){confirm(msg,Globalize.translate("HeaderDeleteDevice")).then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Devices",{Id:id})}).then(function(){loadData(page)})})})}function load(page,devices){var html="";devices.length&&(html+='
'),html+=devices.map(function(d){var deviceHtml="";return deviceHtml+='
',deviceHtml+='tablet_android',deviceHtml+=d.AppName&&d.LastUserName?'"}).join(""),devices.length&&(html+="
");var elem=$(".devicesList",page).html(html).trigger("create");$(".btnDeleteDevice",elem).on("click",function(){deleteDevice(page,this.getAttribute("data-id"))})}function loadData(page){Dashboard.showLoadingMsg(),ApiClient.getJSON(ApiClient.getUrl("Devices",{SupportsPersistentIdentifier:!0})).then(function(result){load(page,result.Items),Dashboard.hideLoadingMsg()})}$(document).on("pageshow","#devicesPage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/dlnaprofile.js b/dashboard-ui/scripts/dlnaprofile.js index d7ebba257b..c481a9fb7a 100644 --- a/dashboard-ui/scripts/dlnaprofile.js +++ b/dashboard-ui/scripts/dlnaprofile.js @@ -1,1181 +1 @@ -define(['jQuery', 'fnchecked', 'jqmlistview', 'emby-select', 'emby-button', 'emby-input', 'emby-checkbox', 'listViewStyle'], function ($) { - 'use strict'; - - var currentProfile; - - var currentSubProfile; - var isSubProfileNew; - - var allText = Globalize.translate('LabelAll'); - - function loadProfile(page) { - - Dashboard.showLoadingMsg(); - - var promise1 = getProfile(); - var promise2 = ApiClient.getUsers(); - - Promise.all([promise1, promise2]).then(function (responses) { - - currentProfile = responses[0]; - - renderProfile(page, currentProfile, responses[1]); - - Dashboard.hideLoadingMsg(); - - }); - } - - function getProfile() { - - var id = getParameterByName('id'); - var url = id ? 'Dlna/Profiles/' + id : - 'Dlna/Profiles/Default'; - - return ApiClient.getJSON(ApiClient.getUrl(url)); - } - - function renderProfile(page, profile, users) { - - $('#txtName', page).val(profile.Name); - - $('.chkMediaType', page).each(function () { - this.checked = (profile.SupportedMediaTypes || '').split(',').indexOf(this.getAttribute('data-value')) != -1; - - }); - - $('#chkEnableAlbumArtInDidl', page).checked(profile.EnableAlbumArtInDidl); - $('#chkEnableSingleImageLimit', page).checked(profile.EnableSingleAlbumArtLimit); - - renderXmlDocumentAttributes(page, profile.XmlRootAttributes || []); - - var idInfo = profile.Identification || {}; - - renderIdentificationHeaders(page, idInfo.Headers || []); - renderSubtitleProfiles(page, profile.SubtitleProfiles || []); - - $('#txtInfoFriendlyName', page).val(profile.FriendlyName || ''); - $('#txtInfoModelName', page).val(profile.ModelName || ''); - $('#txtInfoModelNumber', page).val(profile.ModelNumber || ''); - $('#txtInfoModelDescription', page).val(profile.ModelDescription || ''); - $('#txtInfoModelUrl', page).val(profile.ModelUrl || ''); - $('#txtInfoManufacturer', page).val(profile.Manufacturer || ''); - $('#txtInfoManufacturerUrl', page).val(profile.ManufacturerUrl || ''); - $('#txtInfoSerialNumber', page).val(profile.SerialNumber || ''); - - $('#txtIdFriendlyName', page).val(idInfo.FriendlyName || ''); - $('#txtIdModelName', page).val(idInfo.ModelName || ''); - $('#txtIdModelNumber', page).val(idInfo.ModelNumber || ''); - $('#txtIdModelDescription', page).val(idInfo.ModelDescription || ''); - $('#txtIdModelUrl', page).val(idInfo.ModelUrl || ''); - $('#txtIdManufacturer', page).val(idInfo.Manufacturer || ''); - $('#txtIdManufacturerUrl', page).val(idInfo.ManufacturerUrl || ''); - $('#txtIdSerialNumber', page).val(idInfo.SerialNumber || ''); - $('#txtIdDeviceDescription', page).val(idInfo.DeviceDescription || ''); - - $('#txtAlbumArtPn', page).val(profile.AlbumArtPn || ''); - $('#txtAlbumArtMaxWidth', page).val(profile.MaxAlbumArtWidth || ''); - $('#txtAlbumArtMaxHeight', page).val(profile.MaxAlbumArtHeight || ''); - $('#txtIconMaxWidth', page).val(profile.MaxIconWidth || ''); - $('#txtIconMaxHeight', page).val(profile.MaxIconHeight || ''); - - $('#chkIgnoreTranscodeByteRangeRequests', page).checked(profile.IgnoreTranscodeByteRangeRequests); - $('#txtMaxAllowedBitrate', page).val(profile.MaxStreamingBitrate || ''); - - $('#txtMusicStreamingTranscodingBitrate', page).val(profile.MusicStreamingTranscodingBitrate || ''); - - $('#chkRequiresPlainFolders', page).checked(profile.RequiresPlainFolders); - $('#chkRequiresPlainVideoItems', page).checked(profile.RequiresPlainVideoItems); - - $('#txtProtocolInfo', page).val(profile.ProtocolInfo || ''); - $('#txtXDlnaCap', page).val(profile.XDlnaCap || ''); - $('#txtXDlnaDoc', page).val(profile.XDlnaDoc || ''); - $('#txtSonyAggregationFlags', page).val(profile.SonyAggregationFlags || ''); - - profile.DirectPlayProfiles = (profile.DirectPlayProfiles || []); - profile.TranscodingProfiles = (profile.TranscodingProfiles || []); - profile.ContainerProfiles = (profile.ContainerProfiles || []); - profile.CodecProfiles = (profile.CodecProfiles || []); - profile.ResponseProfiles = (profile.ResponseProfiles || []); - - var usersHtml = '' + users.map(function (u) { - return ''; - }).join(''); - $('#selectUser', page).html(usersHtml).val(profile.UserId || ''); - - renderSubProfiles(page, profile); - } - - function renderIdentificationHeaders(page, headers) { - - var index = 0; - - var html = '
' + headers.map(function (h) { - - var li = '
'; - - li += 'info'; - li += '
'; - - li += '

' + h.Name + ': ' + (h.Value || '') + '

'; - li += '
' + (h.Match || '') + '
'; - - li += '
'; - - li += ''; - - li += '
'; - - index++; - - return li; - - }).join('') + '
'; - - var elem = $('.httpHeaderIdentificationList', page).html(html).trigger('create'); - - $('.btnDeleteIdentificationHeader', elem).on('click', function () { - - var itemIndex = parseInt(this.getAttribute('data-index')); - - currentProfile.Identification.Headers.splice(itemIndex, 1); - - renderIdentificationHeaders(page, currentProfile.Identification.Headers); - }); - } - - function editIdentificationHeader(page, header) { - - isSubProfileNew = header == null; - header = header || {}; - currentSubProfile = header; - - var popup = $('#identificationHeaderPopup', page); - - $('#txtIdentificationHeaderName', popup).val(header.Name || ''); - $('#txtIdentificationHeaderValue', popup).val(header.Value || ''); - $('#selectMatchType', popup).val(header.Match || 'Equals'); - - popup.popup('open'); - } - - function saveIdentificationHeader(page) { - - currentSubProfile.Name = $('#txtIdentificationHeaderName', page).val(); - currentSubProfile.Value = $('#txtIdentificationHeaderValue', page).val(); - currentSubProfile.Match = $('#selectMatchType', page).val(); - - if (isSubProfileNew) { - - currentProfile.Identification = currentProfile.Identification || {}; - currentProfile.Identification.Headers = currentProfile.Identification.Headers || []; - - currentProfile.Identification.Headers.push(currentSubProfile); - } - - renderIdentificationHeaders(page, currentProfile.Identification.Headers); - - currentSubProfile = null; - - $('#identificationHeaderPopup', page).popup('close'); - } - - function renderXmlDocumentAttributes(page, attribute) { - - var index = 0; - - var html = '
' + attribute.map(function (h) { - - var li = '
'; - - li += 'info'; - li += '
'; - - li += '

' + h.Name + ' = ' + (h.Value || '') + '

'; - - li += '
'; - - li += ''; - - li += '
'; - - return li; - - }).join('') + '
'; - - var elem = $('.xmlDocumentAttributeList', page).html(html).trigger('create'); - - $('.btnDeleteXmlAttribute', elem).on('click', function () { - - var itemIndex = parseInt(this.getAttribute('data-index')); - - currentProfile.XmlRootAttributes.splice(itemIndex, 1); - - renderXmlDocumentAttributes(page, currentProfile.XmlRootAttributes); - }); - } - - function editXmlDocumentAttribute(page, attribute) { - - isSubProfileNew = attribute == null; - attribute = attribute || {}; - currentSubProfile = attribute; - - var popup = $('#xmlAttributePopup', page); - - $('#txtXmlAttributeName', popup).val(attribute.Name || ''); - $('#txtXmlAttributeValue', popup).val(attribute.Value || ''); - - popup.popup('open'); - } - - function saveXmlDocumentAttribute(page) { - - currentSubProfile.Name = $('#txtXmlAttributeName', page).val(); - currentSubProfile.Value = $('#txtXmlAttributeValue', page).val(); - - if (isSubProfileNew) { - - currentProfile.XmlRootAttributes.push(currentSubProfile); - } - - renderXmlDocumentAttributes(page, currentProfile.XmlRootAttributes); - - currentSubProfile = null; - - $('#xmlAttributePopup', page).popup('close'); - } - - function renderSubtitleProfiles(page, profiles) { - - var index = 0; - - var html = ''; - - var elem = $('.subtitleProfileList', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var itemIndex = parseInt(this.getAttribute('data-index')); - - currentProfile.SubtitleProfiles.splice(itemIndex, 1); - - renderSubtitleProfiles(page, currentProfile.SubtitleProfiles); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var itemIndex = parseInt(this.getAttribute('data-index')); - - editSubtitleProfile(page, currentProfile.SubtitleProfiles[itemIndex]); - }); - } - - function editSubtitleProfile(page, profile) { - - isSubProfileNew = profile == null; - profile = profile || {}; - currentSubProfile = profile; - - var popup = $('#subtitleProfilePopup', page); - - $('#txtSubtitleProfileFormat', popup).val(profile.Format || ''); - $('#selectSubtitleProfileMethod', popup).val(profile.Method || ''); - $('#selectSubtitleProfileDidlMode', popup).val(profile.DidlMode || ''); - - popup.popup('open'); - } - - function saveSubtitleProfile(page) { - - currentSubProfile.Format = $('#txtSubtitleProfileFormat', page).val(); - currentSubProfile.Method = $('#selectSubtitleProfileMethod', page).val(); - currentSubProfile.DidlMode = $('#selectSubtitleProfileDidlMode', page).val(); - - if (isSubProfileNew) { - - currentProfile.SubtitleProfiles.push(currentSubProfile); - } - - renderSubtitleProfiles(page, currentProfile.SubtitleProfiles); - - currentSubProfile = null; - - $('#subtitleProfilePopup', page).popup('close'); - } - - function renderSubProfiles(page, profile) { - - renderDirectPlayProfiles(page, profile.DirectPlayProfiles); - renderTranscodingProfiles(page, profile.TranscodingProfiles); - renderContainerProfiles(page, profile.ContainerProfiles); - renderCodecProfiles(page, profile.CodecProfiles); - renderResponseProfiles(page, profile.ResponseProfiles); - } - - function saveDirectPlayProfile(page) { - - currentSubProfile.Type = $('#selectDirectPlayProfileType', page).val(); - currentSubProfile.Container = $('#txtDirectPlayContainer', page).val(); - currentSubProfile.AudioCodec = $('#txtDirectPlayAudioCodec', page).val(); - currentSubProfile.VideoCodec = $('#txtDirectPlayVideoCodec', page).val(); - - if (isSubProfileNew) { - - currentProfile.DirectPlayProfiles.push(currentSubProfile); - } - - renderSubProfiles(page, currentProfile); - - currentSubProfile = null; - - $('#popupEditDirectPlayProfile', page).popup('close'); - } - - function renderDirectPlayProfiles(page, profiles) { - - var html = ''; - - html += ''; - - var elem = $('.directPlayProfiles', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var index = this.getAttribute('data-profileindex'); - deleteDirectPlayProfile(page, index); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var index = parseInt(this.getAttribute('data-profileindex')); - - editDirectPlayProfile(page, currentProfile.DirectPlayProfiles[index]); - }); - } - - function deleteDirectPlayProfile(page, index) { - - currentProfile.DirectPlayProfiles.splice(index, 1); - - renderDirectPlayProfiles(page, currentProfile.DirectPlayProfiles); - - } - - function editDirectPlayProfile(page, directPlayProfile) { - - isSubProfileNew = directPlayProfile == null; - directPlayProfile = directPlayProfile || {}; - currentSubProfile = directPlayProfile; - - var popup = $('#popupEditDirectPlayProfile', page); - - $('#selectDirectPlayProfileType', popup).val(directPlayProfile.Type || 'Video').trigger('change'); - $('#txtDirectPlayContainer', popup).val(directPlayProfile.Container || ''); - $('#txtDirectPlayAudioCodec', popup).val(directPlayProfile.AudioCodec || ''); - $('#txtDirectPlayVideoCodec', popup).val(directPlayProfile.VideoCodec || ''); - - popup.popup('open'); - } - - function renderTranscodingProfiles(page, profiles) { - - var html = ''; - - html += ''; - - var elem = $('.transcodingProfiles', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var index = this.getAttribute('data-profileindex'); - deleteTranscodingProfile(page, index); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var index = parseInt(this.getAttribute('data-profileindex')); - - editTranscodingProfile(page, currentProfile.TranscodingProfiles[index]); - }); - } - - function editTranscodingProfile(page, transcodingProfile) { - - isSubProfileNew = transcodingProfile == null; - transcodingProfile = transcodingProfile || {}; - currentSubProfile = transcodingProfile; - - var popup = $('#transcodingProfilePopup', page); - - $('#selectTranscodingProfileType', popup).val(transcodingProfile.Type || 'Video').trigger('change'); - $('#txtTranscodingContainer', popup).val(transcodingProfile.Container || ''); - $('#txtTranscodingAudioCodec', popup).val(transcodingProfile.AudioCodec || ''); - $('#txtTranscodingVideoCodec', popup).val(transcodingProfile.VideoCodec || ''); - $('#selectTranscodingProtocol', popup).val(transcodingProfile.Protocol || 'Http'); - - $('#chkEnableMpegtsM2TsMode', popup).checked(transcodingProfile.EnableMpegtsM2TsMode || false); - $('#chkEstimateContentLength', popup).checked(transcodingProfile.EstimateContentLength || false); - $('#chkReportByteRangeRequests', popup).checked(transcodingProfile.TranscodeSeekInfo == 'Bytes'); - - $('.radioTabButton:first', popup).trigger('click'); - - popup.popup('open'); - } - - function deleteTranscodingProfile(page, index) { - - currentProfile.TranscodingProfiles.splice(index, 1); - - renderTranscodingProfiles(page, currentProfile.TranscodingProfiles); - - } - - function saveTranscodingProfile(page) { - - currentSubProfile.Type = $('#selectTranscodingProfileType', page).val(); - currentSubProfile.Container = $('#txtTranscodingContainer', page).val(); - currentSubProfile.AudioCodec = $('#txtTranscodingAudioCodec', page).val(); - currentSubProfile.VideoCodec = $('#txtTranscodingVideoCodec', page).val(); - currentSubProfile.Protocol = $('#selectTranscodingProtocol', page).val(); - currentSubProfile.Context = 'Streaming'; - - currentSubProfile.EnableMpegtsM2TsMode = $('#chkEnableMpegtsM2TsMode', page).checked(); - currentSubProfile.EstimateContentLength = $('#chkEstimateContentLength', page).checked(); - currentSubProfile.TranscodeSeekInfo = $('#chkReportByteRangeRequests', page).checked() ? 'Bytes' : 'Auto'; - - if (isSubProfileNew) { - - currentProfile.TranscodingProfiles.push(currentSubProfile); - } - - renderSubProfiles(page, currentProfile); - - currentSubProfile = null; - - $('#transcodingProfilePopup', page).popup('close'); - } - - function renderContainerProfiles(page, profiles) { - - var html = ''; - - html += ''; - - var elem = $('.containerProfiles', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var index = this.getAttribute('data-profileindex'); - deleteContainerProfile(page, index); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var index = parseInt(this.getAttribute('data-profileindex')); - - editContainerProfile(page, currentProfile.ContainerProfiles[index]); - }); - } - - function deleteContainerProfile(page, index) { - - currentProfile.ContainerProfiles.splice(index, 1); - - renderContainerProfiles(page, currentProfile.ContainerProfiles); - - } - - function editContainerProfile(page, containerProfile) { - - isSubProfileNew = containerProfile == null; - containerProfile = containerProfile || {}; - currentSubProfile = containerProfile; - - var popup = $('#containerProfilePopup', page); - - $('#selectContainerProfileType', popup).val(containerProfile.Type || 'Video').trigger('change'); - $('#txtContainerProfileContainer', popup).val(containerProfile.Container || ''); - - $('.radioTabButton:first', popup).trigger('click'); - - popup.popup('open'); - } - - function saveContainerProfile(page) { - - currentSubProfile.Type = $('#selectContainerProfileType', page).val(); - currentSubProfile.Container = $('#txtContainerProfileContainer', page).val(); - - if (isSubProfileNew) { - - currentProfile.ContainerProfiles.push(currentSubProfile); - } - - renderSubProfiles(page, currentProfile); - - currentSubProfile = null; - - $('#containerProfilePopup', page).popup('close'); - } - - function renderCodecProfiles(page, profiles) { - - var html = ''; - - html += ''; - - var elem = $('.codecProfiles', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var index = this.getAttribute('data-profileindex'); - deleteCodecProfile(page, index); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var index = parseInt(this.getAttribute('data-profileindex')); - - editCodecProfile(page, currentProfile.CodecProfiles[index]); - }); - } - - function deleteCodecProfile(page, index) { - - currentProfile.CodecProfiles.splice(index, 1); - - renderCodecProfiles(page, currentProfile.CodecProfiles); - - } - - function editCodecProfile(page, codecProfile) { - - isSubProfileNew = codecProfile == null; - codecProfile = codecProfile || {}; - currentSubProfile = codecProfile; - - var popup = $('#codecProfilePopup', page); - - $('#selectCodecProfileType', popup).val(codecProfile.Type || 'Video').trigger('change'); - $('#txtCodecProfileCodec', popup).val(codecProfile.Codec || ''); - - $('.radioTabButton:first', popup).trigger('click'); - - popup.popup('open'); - } - - function saveCodecProfile(page) { - - currentSubProfile.Type = $('#selectCodecProfileType', page).val(); - currentSubProfile.Codec = $('#txtCodecProfileCodec', page).val(); - - if (isSubProfileNew) { - - currentProfile.CodecProfiles.push(currentSubProfile); - } - - renderSubProfiles(page, currentProfile); - - currentSubProfile = null; - - $('#codecProfilePopup', page).popup('close'); - } - - function renderResponseProfiles(page, profiles) { - - var html = ''; - - html += ''; - - var elem = $('.mediaProfiles', page).html(html).trigger('create'); - - $('.btnDeleteProfile', elem).on('click', function () { - - var index = this.getAttribute('data-profileindex'); - deleteResponseProfile(page, index); - }); - - $('.lnkEditSubProfile', elem).on('click', function () { - - var index = parseInt(this.getAttribute('data-profileindex')); - - editResponseProfile(page, currentProfile.ResponseProfiles[index]); - }); - } - - function deleteResponseProfile(page, index) { - - currentProfile.ResponseProfiles.splice(index, 1); - - renderResponseProfiles(page, currentProfile.ResponseProfiles); - } - - function editResponseProfile(page, responseProfile) { - - isSubProfileNew = responseProfile == null; - responseProfile = responseProfile || {}; - currentSubProfile = responseProfile; - - var popup = $('#responseProfilePopup', page); - - $('#selectResponseProfileType', popup).val(responseProfile.Type || 'Video').trigger('change'); - $('#txtResponseProfileContainer', popup).val(responseProfile.Container || ''); - $('#txtResponseProfileAudioCodec', popup).val(responseProfile.AudioCodec || ''); - $('#txtResponseProfileVideoCodec', popup).val(responseProfile.VideoCodec || ''); - - $('.radioTabButton:first', popup).trigger('click'); - - popup.popup('open'); - } - - function saveResponseProfile(page) { - - currentSubProfile.Type = $('#selectResponseProfileType', page).val(); - currentSubProfile.Container = $('#txtResponseProfileContainer', page).val(); - currentSubProfile.AudioCodec = $('#txtResponseProfileAudioCodec', page).val(); - currentSubProfile.VideoCodec = $('#txtResponseProfileVideoCodec', page).val(); - - if (isSubProfileNew) { - - currentProfile.ResponseProfiles.push(currentSubProfile); - } - - renderSubProfiles(page, currentProfile); - - currentSubProfile = null; - - $('#responseProfilePopup', page).popup('close'); - } - - function saveProfile(page, profile) { - - updateProfile(page, profile); - - var id = getParameterByName('id'); - - if (id) { - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl("Dlna/Profiles/" + id), - data: JSON.stringify(profile), - contentType: "application/json" - }).then(function () { - - require(['toast'], function (toast) { - toast('Settings saved.'); - }); - }, Dashboard.processErrorResponse); - - } else { - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl("Dlna/Profiles"), - data: JSON.stringify(profile), - contentType: "application/json" - }).then(function () { - - Dashboard.navigate('dlnaprofiles.html'); - - }, Dashboard.processErrorResponse); - - } - - Dashboard.hideLoadingMsg(); - } - - function updateProfile(page, profile) { - - profile.Name = $('#txtName', page).val(); - profile.EnableAlbumArtInDidl = $('#chkEnableAlbumArtInDidl', page).checked(); - profile.EnableSingleAlbumArtLimit = $('#chkEnableSingleImageLimit', page).checked(); - - profile.SupportedMediaTypes = $('.chkMediaType:checked', page).get().map(function (c) { - return c.getAttribute('data-value'); - }).join(','); - - profile.Identification = profile.Identification || {}; - - profile.FriendlyName = $('#txtInfoFriendlyName', page).val(); - profile.ModelName = $('#txtInfoModelName', page).val(); - profile.ModelNumber = $('#txtInfoModelNumber', page).val(); - profile.ModelDescription = $('#txtInfoModelDescription', page).val(); - profile.ModelUrl = $('#txtInfoModelUrl', page).val(); - profile.Manufacturer = $('#txtInfoManufacturer', page).val(); - profile.ManufacturerUrl = $('#txtInfoManufacturerUrl', page).val(); - profile.SerialNumber = $('#txtInfoSerialNumber', page).val(); - - profile.Identification.FriendlyName = $('#txtIdFriendlyName', page).val(); - profile.Identification.ModelName = $('#txtIdModelName', page).val(); - profile.Identification.ModelNumber = $('#txtIdModelNumber', page).val(); - profile.Identification.ModelDescription = $('#txtIdModelDescription', page).val(); - profile.Identification.ModelUrl = $('#txtIdModelUrl', page).val(); - profile.Identification.Manufacturer = $('#txtIdManufacturer', page).val(); - profile.Identification.ManufacturerUrl = $('#txtIdManufacturerUrl', page).val(); - profile.Identification.SerialNumber = $('#txtIdSerialNumber', page).val(); - profile.Identification.DeviceDescription = $('#txtIdDeviceDescription', page).val(); - - profile.AlbumArtPn = $('#txtAlbumArtPn', page).val(); - profile.MaxAlbumArtWidth = $('#txtAlbumArtMaxWidth', page).val(); - profile.MaxAlbumArtHeight = $('#txtAlbumArtMaxHeight', page).val(); - profile.MaxIconWidth = $('#txtIconMaxWidth', page).val(); - profile.MaxIconHeight = $('#txtIconMaxHeight', page).val(); - - profile.RequiresPlainFolders = $('#chkRequiresPlainFolders', page).checked(); - profile.RequiresPlainVideoItems = $('#chkRequiresPlainVideoItems', page).checked(); - - profile.IgnoreTranscodeByteRangeRequests = $('#chkIgnoreTranscodeByteRangeRequests', page).checked(); - profile.MaxStreamingBitrate = $('#txtMaxAllowedBitrate', page).val(); - - profile.MusicStreamingTranscodingBitrate = $('#txtMusicStreamingTranscodingBitrate', page).val(); - - profile.ProtocolInfo = $('#txtProtocolInfo', page).val(); - profile.XDlnaCap = $('#txtXDlnaCap', page).val(); - profile.XDlnaDoc = $('#txtXDlnaDoc', page).val(); - profile.SonyAggregationFlags = $('#txtSonyAggregationFlags', page).val(); - - profile.UserId = $('#selectUser', page).val(); - } - - $(document).on('pageinit', "#dlnaProfilePage", function () { - - var page = this; - - $('.radioTabButton', page).on('click', function () { - - $(this).siblings().removeClass('ui-btn-active'); - $(this).addClass('ui-btn-active'); - - var value = this.tagName == 'A' ? this.getAttribute('data-value') : this.value; - var elem = $('.' + value, page); - elem.siblings('.tabContent').hide(); - - elem.show(); - }); - - $('#selectDirectPlayProfileType', page).on('change', function () { - - if (this.value == 'Video') { - $('#fldDirectPlayVideoCodec', page).show(); - } else { - $('#fldDirectPlayVideoCodec', page).hide(); - } - - if (this.value == 'Photo') { - $('#fldDirectPlayAudioCodec', page).hide(); - } else { - $('#fldDirectPlayAudioCodec', page).show(); - } - - }); - - $('#selectTranscodingProfileType', page).on('change', function () { - - if (this.value == 'Video') { - $('#fldTranscodingVideoCodec', page).show(); - $('#fldTranscodingProtocol', page).show(); - $('#fldEnableMpegtsM2TsMode', page).show(); - } else { - $('#fldTranscodingVideoCodec', page).hide(); - $('#fldTranscodingProtocol', page).hide(); - $('#fldEnableMpegtsM2TsMode', page).hide(); - } - - if (this.value == 'Photo') { - $('#fldTranscodingAudioCodec', page).hide(); - - $('#fldEstimateContentLength', page).hide(); - $('#fldReportByteRangeRequests', page).hide(); - - } else { - $('#fldTranscodingAudioCodec', page).show(); - - $('#fldEstimateContentLength', page).show(); - $('#fldReportByteRangeRequests', page).show(); - } - - }); - - $('#selectResponseProfileType', page).on('change', function () { - - if (this.value == 'Video') { - $('#fldResponseProfileVideoCodec', page).show(); - } else { - $('#fldResponseProfileVideoCodec', page).hide(); - } - - if (this.value == 'Photo') { - $('#fldResponseProfileAudioCodec', page).hide(); - } else { - $('#fldResponseProfileAudioCodec', page).show(); - } - - }); - - $('.btnAddDirectPlayProfile', page).on('click', function () { - - editDirectPlayProfile(page); - - }); - - $('.btnAddTranscodingProfile', page).on('click', function () { - - editTranscodingProfile(page); - - }); - - $('.btnAddContainerProfile', page).on('click', function () { - - editContainerProfile(page); - - }); - - $('.btnAddCodecProfile', page).on('click', function () { - - editCodecProfile(page); - - }); - - $('.btnAddResponseProfile', page).on('click', function () { - - editResponseProfile(page); - - }); - - $('.btnAddIdentificationHttpHeader', page).on('click', function () { - - editIdentificationHeader(page); - }); - - $('.btnAddXmlDocumentAttribute', page).on('click', function () { - - editXmlDocumentAttribute(page); - }); - - $('.btnAddSubtitleProfile', page).on('click', function () { - - editSubtitleProfile(page); - }); - - $('.dlnaProfileForm').off('submit', DlnaProfilePage.onSubmit).on('submit', DlnaProfilePage.onSubmit); - $('.editDirectPlayProfileForm').off('submit', DlnaProfilePage.onDirectPlayFormSubmit).on('submit', DlnaProfilePage.onDirectPlayFormSubmit); - $('.transcodingProfileForm').off('submit', DlnaProfilePage.onTranscodingProfileFormSubmit).on('submit', DlnaProfilePage.onTranscodingProfileFormSubmit); - $('.containerProfileForm').off('submit', DlnaProfilePage.onContainerProfileFormSubmit).on('submit', DlnaProfilePage.onContainerProfileFormSubmit); - $('.codecProfileForm').off('submit', DlnaProfilePage.onCodecProfileFormSubmit).on('submit', DlnaProfilePage.onCodecProfileFormSubmit); - $('.editResponseProfileForm').off('submit', DlnaProfilePage.onResponseProfileFormSubmit).on('submit', DlnaProfilePage.onResponseProfileFormSubmit); - $('.identificationHeaderForm').off('submit', DlnaProfilePage.onIdentificationHeaderFormSubmit).on('submit', DlnaProfilePage.onIdentificationHeaderFormSubmit); - $('.xmlAttributeForm').off('submit', DlnaProfilePage.onXmlAttributeFormSubmit).on('submit', DlnaProfilePage.onXmlAttributeFormSubmit); - $('.subtitleProfileForm').off('submit', DlnaProfilePage.onSubtitleProfileFormSubmit).on('submit', DlnaProfilePage.onSubtitleProfileFormSubmit); - - }).on('pageshow', "#dlnaProfilePage", function () { - - var page = this; - - $('#radioInfo', page).trigger('click'); - - loadProfile(page); - }); - - window.DlnaProfilePage = { - onSubmit: function () { - - Dashboard.showLoadingMsg(); - - var form = this; - var page = $(form).parents('.page'); - - saveProfile(page, currentProfile); - - return false; - }, - - onDirectPlayFormSubmit: function () { - - var form = this; - var page = $(form).parents('.page'); - - saveDirectPlayProfile(page); - - return false; - }, - - onTranscodingProfileFormSubmit: function () { - - var form = this; - var page = $(form).parents('.page'); - - saveTranscodingProfile(page); - - return false; - - }, - - onContainerProfileFormSubmit: function () { - var form = this; - var page = $(form).parents('.page'); - - saveContainerProfile(page); - - return false; - - }, - - onCodecProfileFormSubmit: function () { - var form = this; - var page = $(form).parents('.page'); - - saveCodecProfile(page); - - return false; - }, - - onResponseProfileFormSubmit: function () { - var form = this; - var page = $(form).parents('.page'); - - saveResponseProfile(page); - - return false; - }, - - onIdentificationHeaderFormSubmit: function () { - - var form = this; - var page = $(form).parents('.page'); - - saveIdentificationHeader(page); - - return false; - }, - - onXmlAttributeFormSubmit: function () { - - var form = this; - var page = $(form).parents('.page'); - - saveXmlDocumentAttribute(page); - - return false; - }, - - onSubtitleProfileFormSubmit: function () { - - var form = this; - var page = $(form).parents('.page'); - - saveSubtitleProfile(page); - - return false; - } - }; - -}); \ No newline at end of file +define(["jQuery","fnchecked","jqmlistview","emby-select","emby-button","emby-input","emby-checkbox","listViewStyle"],function($){"use strict";function loadProfile(page){Dashboard.showLoadingMsg();var promise1=getProfile(),promise2=ApiClient.getUsers();Promise.all([promise1,promise2]).then(function(responses){currentProfile=responses[0],renderProfile(page,currentProfile,responses[1]),Dashboard.hideLoadingMsg()})}function getProfile(){var id=getParameterByName("id"),url=id?"Dlna/Profiles/"+id:"Dlna/Profiles/Default";return ApiClient.getJSON(ApiClient.getUrl(url))}function renderProfile(page,profile,users){$("#txtName",page).val(profile.Name),$(".chkMediaType",page).each(function(){this.checked=(profile.SupportedMediaTypes||"").split(",").indexOf(this.getAttribute("data-value"))!=-1}),$("#chkEnableAlbumArtInDidl",page).checked(profile.EnableAlbumArtInDidl),$("#chkEnableSingleImageLimit",page).checked(profile.EnableSingleAlbumArtLimit),renderXmlDocumentAttributes(page,profile.XmlRootAttributes||[]);var idInfo=profile.Identification||{};renderIdentificationHeaders(page,idInfo.Headers||[]),renderSubtitleProfiles(page,profile.SubtitleProfiles||[]),$("#txtInfoFriendlyName",page).val(profile.FriendlyName||""),$("#txtInfoModelName",page).val(profile.ModelName||""),$("#txtInfoModelNumber",page).val(profile.ModelNumber||""),$("#txtInfoModelDescription",page).val(profile.ModelDescription||""),$("#txtInfoModelUrl",page).val(profile.ModelUrl||""),$("#txtInfoManufacturer",page).val(profile.Manufacturer||""),$("#txtInfoManufacturerUrl",page).val(profile.ManufacturerUrl||""),$("#txtInfoSerialNumber",page).val(profile.SerialNumber||""),$("#txtIdFriendlyName",page).val(idInfo.FriendlyName||""),$("#txtIdModelName",page).val(idInfo.ModelName||""),$("#txtIdModelNumber",page).val(idInfo.ModelNumber||""),$("#txtIdModelDescription",page).val(idInfo.ModelDescription||""),$("#txtIdModelUrl",page).val(idInfo.ModelUrl||""),$("#txtIdManufacturer",page).val(idInfo.Manufacturer||""),$("#txtIdManufacturerUrl",page).val(idInfo.ManufacturerUrl||""),$("#txtIdSerialNumber",page).val(idInfo.SerialNumber||""),$("#txtIdDeviceDescription",page).val(idInfo.DeviceDescription||""),$("#txtAlbumArtPn",page).val(profile.AlbumArtPn||""),$("#txtAlbumArtMaxWidth",page).val(profile.MaxAlbumArtWidth||""),$("#txtAlbumArtMaxHeight",page).val(profile.MaxAlbumArtHeight||""),$("#txtIconMaxWidth",page).val(profile.MaxIconWidth||""),$("#txtIconMaxHeight",page).val(profile.MaxIconHeight||""),$("#chkIgnoreTranscodeByteRangeRequests",page).checked(profile.IgnoreTranscodeByteRangeRequests),$("#txtMaxAllowedBitrate",page).val(profile.MaxStreamingBitrate||""),$("#txtMusicStreamingTranscodingBitrate",page).val(profile.MusicStreamingTranscodingBitrate||""),$("#chkRequiresPlainFolders",page).checked(profile.RequiresPlainFolders),$("#chkRequiresPlainVideoItems",page).checked(profile.RequiresPlainVideoItems),$("#txtProtocolInfo",page).val(profile.ProtocolInfo||""),$("#txtXDlnaCap",page).val(profile.XDlnaCap||""),$("#txtXDlnaDoc",page).val(profile.XDlnaDoc||""),$("#txtSonyAggregationFlags",page).val(profile.SonyAggregationFlags||""),profile.DirectPlayProfiles=profile.DirectPlayProfiles||[],profile.TranscodingProfiles=profile.TranscodingProfiles||[],profile.ContainerProfiles=profile.ContainerProfiles||[],profile.CodecProfiles=profile.CodecProfiles||[],profile.ResponseProfiles=profile.ResponseProfiles||[];var usersHtml=""+users.map(function(u){return'"}).join("");$("#selectUser",page).html(usersHtml).val(profile.UserId||""),renderSubProfiles(page,profile)}function renderIdentificationHeaders(page,headers){var index=0,html='
'+headers.map(function(h){var li='
';return li+='info',li+='
',li+='

'+h.Name+": "+(h.Value||"")+"

",li+='
'+(h.Match||"")+"
",li+="
",li+='',li+="
",index++,li}).join("")+"
",elem=$(".httpHeaderIdentificationList",page).html(html).trigger("create");$(".btnDeleteIdentificationHeader",elem).on("click",function(){var itemIndex=parseInt(this.getAttribute("data-index"));currentProfile.Identification.Headers.splice(itemIndex,1),renderIdentificationHeaders(page,currentProfile.Identification.Headers)})}function editIdentificationHeader(page,header){isSubProfileNew=null==header,header=header||{},currentSubProfile=header;var popup=$("#identificationHeaderPopup",page);$("#txtIdentificationHeaderName",popup).val(header.Name||""),$("#txtIdentificationHeaderValue",popup).val(header.Value||""),$("#selectMatchType",popup).val(header.Match||"Equals"),popup.popup("open")}function saveIdentificationHeader(page){currentSubProfile.Name=$("#txtIdentificationHeaderName",page).val(),currentSubProfile.Value=$("#txtIdentificationHeaderValue",page).val(),currentSubProfile.Match=$("#selectMatchType",page).val(),isSubProfileNew&&(currentProfile.Identification=currentProfile.Identification||{},currentProfile.Identification.Headers=currentProfile.Identification.Headers||[],currentProfile.Identification.Headers.push(currentSubProfile)),renderIdentificationHeaders(page,currentProfile.Identification.Headers),currentSubProfile=null,$("#identificationHeaderPopup",page).popup("close")}function renderXmlDocumentAttributes(page,attribute){var index=0,html='
'+attribute.map(function(h){var li='
';return li+='info',li+='
',li+='

'+h.Name+" = "+(h.Value||"")+"

",li+="
",li+='',li+="
"}).join("")+"
",elem=$(".xmlDocumentAttributeList",page).html(html).trigger("create");$(".btnDeleteXmlAttribute",elem).on("click",function(){var itemIndex=parseInt(this.getAttribute("data-index"));currentProfile.XmlRootAttributes.splice(itemIndex,1),renderXmlDocumentAttributes(page,currentProfile.XmlRootAttributes)})}function editXmlDocumentAttribute(page,attribute){isSubProfileNew=null==attribute,attribute=attribute||{},currentSubProfile=attribute;var popup=$("#xmlAttributePopup",page);$("#txtXmlAttributeName",popup).val(attribute.Name||""),$("#txtXmlAttributeValue",popup).val(attribute.Value||""),popup.popup("open")}function saveXmlDocumentAttribute(page){currentSubProfile.Name=$("#txtXmlAttributeName",page).val(),currentSubProfile.Value=$("#txtXmlAttributeValue",page).val(),isSubProfileNew&¤tProfile.XmlRootAttributes.push(currentSubProfile),renderXmlDocumentAttributes(page,currentProfile.XmlRootAttributes),currentSubProfile=null,$("#xmlAttributePopup",page).popup("close")}function renderSubtitleProfiles(page,profiles){var index=0,html='",elem=$(".subtitleProfileList",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var itemIndex=parseInt(this.getAttribute("data-index"));currentProfile.SubtitleProfiles.splice(itemIndex,1),renderSubtitleProfiles(page,currentProfile.SubtitleProfiles)}),$(".lnkEditSubProfile",elem).on("click",function(){var itemIndex=parseInt(this.getAttribute("data-index"));editSubtitleProfile(page,currentProfile.SubtitleProfiles[itemIndex])})}function editSubtitleProfile(page,profile){isSubProfileNew=null==profile,profile=profile||{},currentSubProfile=profile;var popup=$("#subtitleProfilePopup",page);$("#txtSubtitleProfileFormat",popup).val(profile.Format||""),$("#selectSubtitleProfileMethod",popup).val(profile.Method||""),$("#selectSubtitleProfileDidlMode",popup).val(profile.DidlMode||""),popup.popup("open")}function saveSubtitleProfile(page){currentSubProfile.Format=$("#txtSubtitleProfileFormat",page).val(),currentSubProfile.Method=$("#selectSubtitleProfileMethod",page).val(),currentSubProfile.DidlMode=$("#selectSubtitleProfileDidlMode",page).val(),isSubProfileNew&¤tProfile.SubtitleProfiles.push(currentSubProfile),renderSubtitleProfiles(page,currentProfile.SubtitleProfiles),currentSubProfile=null,$("#subtitleProfilePopup",page).popup("close")}function renderSubProfiles(page,profile){renderDirectPlayProfiles(page,profile.DirectPlayProfiles),renderTranscodingProfiles(page,profile.TranscodingProfiles),renderContainerProfiles(page,profile.ContainerProfiles),renderCodecProfiles(page,profile.CodecProfiles),renderResponseProfiles(page,profile.ResponseProfiles)}function saveDirectPlayProfile(page){currentSubProfile.Type=$("#selectDirectPlayProfileType",page).val(),currentSubProfile.Container=$("#txtDirectPlayContainer",page).val(),currentSubProfile.AudioCodec=$("#txtDirectPlayAudioCodec",page).val(),currentSubProfile.VideoCodec=$("#txtDirectPlayVideoCodec",page).val(),isSubProfileNew&¤tProfile.DirectPlayProfiles.push(currentSubProfile),renderSubProfiles(page,currentProfile),currentSubProfile=null,$("#popupEditDirectPlayProfile",page).popup("close")}function renderDirectPlayProfiles(page,profiles){var html="";html+='";var elem=$(".directPlayProfiles",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var index=this.getAttribute("data-profileindex");deleteDirectPlayProfile(page,index)}),$(".lnkEditSubProfile",elem).on("click",function(){var index=parseInt(this.getAttribute("data-profileindex"));editDirectPlayProfile(page,currentProfile.DirectPlayProfiles[index])})}function deleteDirectPlayProfile(page,index){currentProfile.DirectPlayProfiles.splice(index,1),renderDirectPlayProfiles(page,currentProfile.DirectPlayProfiles)}function editDirectPlayProfile(page,directPlayProfile){isSubProfileNew=null==directPlayProfile,directPlayProfile=directPlayProfile||{},currentSubProfile=directPlayProfile;var popup=$("#popupEditDirectPlayProfile",page);$("#selectDirectPlayProfileType",popup).val(directPlayProfile.Type||"Video").trigger("change"),$("#txtDirectPlayContainer",popup).val(directPlayProfile.Container||""),$("#txtDirectPlayAudioCodec",popup).val(directPlayProfile.AudioCodec||""),$("#txtDirectPlayVideoCodec",popup).val(directPlayProfile.VideoCodec||""),popup.popup("open")}function renderTranscodingProfiles(page,profiles){var html="";html+='";var elem=$(".transcodingProfiles",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var index=this.getAttribute("data-profileindex");deleteTranscodingProfile(page,index)}),$(".lnkEditSubProfile",elem).on("click",function(){var index=parseInt(this.getAttribute("data-profileindex"));editTranscodingProfile(page,currentProfile.TranscodingProfiles[index])})}function editTranscodingProfile(page,transcodingProfile){isSubProfileNew=null==transcodingProfile,transcodingProfile=transcodingProfile||{},currentSubProfile=transcodingProfile;var popup=$("#transcodingProfilePopup",page);$("#selectTranscodingProfileType",popup).val(transcodingProfile.Type||"Video").trigger("change"),$("#txtTranscodingContainer",popup).val(transcodingProfile.Container||""),$("#txtTranscodingAudioCodec",popup).val(transcodingProfile.AudioCodec||""),$("#txtTranscodingVideoCodec",popup).val(transcodingProfile.VideoCodec||""),$("#selectTranscodingProtocol",popup).val(transcodingProfile.Protocol||"Http"),$("#chkEnableMpegtsM2TsMode",popup).checked(transcodingProfile.EnableMpegtsM2TsMode||!1),$("#chkEstimateContentLength",popup).checked(transcodingProfile.EstimateContentLength||!1),$("#chkReportByteRangeRequests",popup).checked("Bytes"==transcodingProfile.TranscodeSeekInfo),$(".radioTabButton:first",popup).trigger("click"),popup.popup("open")}function deleteTranscodingProfile(page,index){currentProfile.TranscodingProfiles.splice(index,1),renderTranscodingProfiles(page,currentProfile.TranscodingProfiles)}function saveTranscodingProfile(page){currentSubProfile.Type=$("#selectTranscodingProfileType",page).val(),currentSubProfile.Container=$("#txtTranscodingContainer",page).val(),currentSubProfile.AudioCodec=$("#txtTranscodingAudioCodec",page).val(),currentSubProfile.VideoCodec=$("#txtTranscodingVideoCodec",page).val(),currentSubProfile.Protocol=$("#selectTranscodingProtocol",page).val(),currentSubProfile.Context="Streaming",currentSubProfile.EnableMpegtsM2TsMode=$("#chkEnableMpegtsM2TsMode",page).checked(),currentSubProfile.EstimateContentLength=$("#chkEstimateContentLength",page).checked(),currentSubProfile.TranscodeSeekInfo=$("#chkReportByteRangeRequests",page).checked()?"Bytes":"Auto",isSubProfileNew&¤tProfile.TranscodingProfiles.push(currentSubProfile),renderSubProfiles(page,currentProfile),currentSubProfile=null,$("#transcodingProfilePopup",page).popup("close")}function renderContainerProfiles(page,profiles){var html="";html+='";var elem=$(".containerProfiles",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var index=this.getAttribute("data-profileindex");deleteContainerProfile(page,index)}),$(".lnkEditSubProfile",elem).on("click",function(){var index=parseInt(this.getAttribute("data-profileindex"));editContainerProfile(page,currentProfile.ContainerProfiles[index])})}function deleteContainerProfile(page,index){currentProfile.ContainerProfiles.splice(index,1),renderContainerProfiles(page,currentProfile.ContainerProfiles)}function editContainerProfile(page,containerProfile){isSubProfileNew=null==containerProfile,containerProfile=containerProfile||{},currentSubProfile=containerProfile;var popup=$("#containerProfilePopup",page);$("#selectContainerProfileType",popup).val(containerProfile.Type||"Video").trigger("change"),$("#txtContainerProfileContainer",popup).val(containerProfile.Container||""),$(".radioTabButton:first",popup).trigger("click"),popup.popup("open")}function saveContainerProfile(page){currentSubProfile.Type=$("#selectContainerProfileType",page).val(),currentSubProfile.Container=$("#txtContainerProfileContainer",page).val(),isSubProfileNew&¤tProfile.ContainerProfiles.push(currentSubProfile),renderSubProfiles(page,currentProfile),currentSubProfile=null,$("#containerProfilePopup",page).popup("close")}function renderCodecProfiles(page,profiles){var html="";html+='";var elem=$(".codecProfiles",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var index=this.getAttribute("data-profileindex");deleteCodecProfile(page,index)}),$(".lnkEditSubProfile",elem).on("click",function(){var index=parseInt(this.getAttribute("data-profileindex"));editCodecProfile(page,currentProfile.CodecProfiles[index])})}function deleteCodecProfile(page,index){currentProfile.CodecProfiles.splice(index,1),renderCodecProfiles(page,currentProfile.CodecProfiles)}function editCodecProfile(page,codecProfile){isSubProfileNew=null==codecProfile,codecProfile=codecProfile||{},currentSubProfile=codecProfile;var popup=$("#codecProfilePopup",page);$("#selectCodecProfileType",popup).val(codecProfile.Type||"Video").trigger("change"),$("#txtCodecProfileCodec",popup).val(codecProfile.Codec||""),$(".radioTabButton:first",popup).trigger("click"),popup.popup("open")}function saveCodecProfile(page){currentSubProfile.Type=$("#selectCodecProfileType",page).val(),currentSubProfile.Codec=$("#txtCodecProfileCodec",page).val(),isSubProfileNew&¤tProfile.CodecProfiles.push(currentSubProfile),renderSubProfiles(page,currentProfile),currentSubProfile=null,$("#codecProfilePopup",page).popup("close")}function renderResponseProfiles(page,profiles){var html="";html+='";var elem=$(".mediaProfiles",page).html(html).trigger("create");$(".btnDeleteProfile",elem).on("click",function(){var index=this.getAttribute("data-profileindex");deleteResponseProfile(page,index)}),$(".lnkEditSubProfile",elem).on("click",function(){var index=parseInt(this.getAttribute("data-profileindex"));editResponseProfile(page,currentProfile.ResponseProfiles[index])})}function deleteResponseProfile(page,index){currentProfile.ResponseProfiles.splice(index,1),renderResponseProfiles(page,currentProfile.ResponseProfiles)}function editResponseProfile(page,responseProfile){isSubProfileNew=null==responseProfile,responseProfile=responseProfile||{},currentSubProfile=responseProfile;var popup=$("#responseProfilePopup",page);$("#selectResponseProfileType",popup).val(responseProfile.Type||"Video").trigger("change"),$("#txtResponseProfileContainer",popup).val(responseProfile.Container||""),$("#txtResponseProfileAudioCodec",popup).val(responseProfile.AudioCodec||""),$("#txtResponseProfileVideoCodec",popup).val(responseProfile.VideoCodec||""),$(".radioTabButton:first",popup).trigger("click"),popup.popup("open")}function saveResponseProfile(page){currentSubProfile.Type=$("#selectResponseProfileType",page).val(),currentSubProfile.Container=$("#txtResponseProfileContainer",page).val(),currentSubProfile.AudioCodec=$("#txtResponseProfileAudioCodec",page).val(),currentSubProfile.VideoCodec=$("#txtResponseProfileVideoCodec",page).val(),isSubProfileNew&¤tProfile.ResponseProfiles.push(currentSubProfile),renderSubProfiles(page,currentProfile),currentSubProfile=null,$("#responseProfilePopup",page).popup("close")}function saveProfile(page,profile){updateProfile(page,profile);var id=getParameterByName("id");id?ApiClient.ajax({type:"POST",url:ApiClient.getUrl("Dlna/Profiles/"+id),data:JSON.stringify(profile),contentType:"application/json"}).then(function(){require(["toast"],function(toast){toast("Settings saved.")})},Dashboard.processErrorResponse):ApiClient.ajax({type:"POST",url:ApiClient.getUrl("Dlna/Profiles"),data:JSON.stringify(profile),contentType:"application/json"}).then(function(){Dashboard.navigate("dlnaprofiles.html")},Dashboard.processErrorResponse),Dashboard.hideLoadingMsg()}function updateProfile(page,profile){profile.Name=$("#txtName",page).val(),profile.EnableAlbumArtInDidl=$("#chkEnableAlbumArtInDidl",page).checked(),profile.EnableSingleAlbumArtLimit=$("#chkEnableSingleImageLimit",page).checked(),profile.SupportedMediaTypes=$(".chkMediaType:checked",page).get().map(function(c){return c.getAttribute("data-value")}).join(","),profile.Identification=profile.Identification||{},profile.FriendlyName=$("#txtInfoFriendlyName",page).val(),profile.ModelName=$("#txtInfoModelName",page).val(),profile.ModelNumber=$("#txtInfoModelNumber",page).val(),profile.ModelDescription=$("#txtInfoModelDescription",page).val(),profile.ModelUrl=$("#txtInfoModelUrl",page).val(),profile.Manufacturer=$("#txtInfoManufacturer",page).val(),profile.ManufacturerUrl=$("#txtInfoManufacturerUrl",page).val(),profile.SerialNumber=$("#txtInfoSerialNumber",page).val(),profile.Identification.FriendlyName=$("#txtIdFriendlyName",page).val(),profile.Identification.ModelName=$("#txtIdModelName",page).val(),profile.Identification.ModelNumber=$("#txtIdModelNumber",page).val(),profile.Identification.ModelDescription=$("#txtIdModelDescription",page).val(),profile.Identification.ModelUrl=$("#txtIdModelUrl",page).val(),profile.Identification.Manufacturer=$("#txtIdManufacturer",page).val(),profile.Identification.ManufacturerUrl=$("#txtIdManufacturerUrl",page).val(),profile.Identification.SerialNumber=$("#txtIdSerialNumber",page).val(),profile.Identification.DeviceDescription=$("#txtIdDeviceDescription",page).val(),profile.AlbumArtPn=$("#txtAlbumArtPn",page).val(),profile.MaxAlbumArtWidth=$("#txtAlbumArtMaxWidth",page).val(),profile.MaxAlbumArtHeight=$("#txtAlbumArtMaxHeight",page).val(),profile.MaxIconWidth=$("#txtIconMaxWidth",page).val(),profile.MaxIconHeight=$("#txtIconMaxHeight",page).val(),profile.RequiresPlainFolders=$("#chkRequiresPlainFolders",page).checked(),profile.RequiresPlainVideoItems=$("#chkRequiresPlainVideoItems",page).checked(),profile.IgnoreTranscodeByteRangeRequests=$("#chkIgnoreTranscodeByteRangeRequests",page).checked(),profile.MaxStreamingBitrate=$("#txtMaxAllowedBitrate",page).val(),profile.MusicStreamingTranscodingBitrate=$("#txtMusicStreamingTranscodingBitrate",page).val(),profile.ProtocolInfo=$("#txtProtocolInfo",page).val(),profile.XDlnaCap=$("#txtXDlnaCap",page).val(),profile.XDlnaDoc=$("#txtXDlnaDoc",page).val(),profile.SonyAggregationFlags=$("#txtSonyAggregationFlags",page).val(),profile.UserId=$("#selectUser",page).val()}var currentProfile,currentSubProfile,isSubProfileNew,allText=Globalize.translate("LabelAll");$(document).on("pageinit","#dlnaProfilePage",function(){var page=this;$(".radioTabButton",page).on("click",function(){$(this).siblings().removeClass("ui-btn-active"),$(this).addClass("ui-btn-active");var value="A"==this.tagName?this.getAttribute("data-value"):this.value,elem=$("."+value,page);elem.siblings(".tabContent").hide(),elem.show()}),$("#selectDirectPlayProfileType",page).on("change",function(){"Video"==this.value?$("#fldDirectPlayVideoCodec",page).show():$("#fldDirectPlayVideoCodec",page).hide(),"Photo"==this.value?$("#fldDirectPlayAudioCodec",page).hide():$("#fldDirectPlayAudioCodec",page).show()}),$("#selectTranscodingProfileType",page).on("change",function(){"Video"==this.value?($("#fldTranscodingVideoCodec",page).show(),$("#fldTranscodingProtocol",page).show(),$("#fldEnableMpegtsM2TsMode",page).show()):($("#fldTranscodingVideoCodec",page).hide(),$("#fldTranscodingProtocol",page).hide(),$("#fldEnableMpegtsM2TsMode",page).hide()),"Photo"==this.value?($("#fldTranscodingAudioCodec",page).hide(),$("#fldEstimateContentLength",page).hide(),$("#fldReportByteRangeRequests",page).hide()):($("#fldTranscodingAudioCodec",page).show(),$("#fldEstimateContentLength",page).show(),$("#fldReportByteRangeRequests",page).show())}),$("#selectResponseProfileType",page).on("change",function(){"Video"==this.value?$("#fldResponseProfileVideoCodec",page).show():$("#fldResponseProfileVideoCodec",page).hide(),"Photo"==this.value?$("#fldResponseProfileAudioCodec",page).hide():$("#fldResponseProfileAudioCodec",page).show()}),$(".btnAddDirectPlayProfile",page).on("click",function(){editDirectPlayProfile(page)}),$(".btnAddTranscodingProfile",page).on("click",function(){editTranscodingProfile(page)}),$(".btnAddContainerProfile",page).on("click",function(){editContainerProfile(page)}),$(".btnAddCodecProfile",page).on("click",function(){editCodecProfile(page)}),$(".btnAddResponseProfile",page).on("click",function(){editResponseProfile(page)}),$(".btnAddIdentificationHttpHeader",page).on("click",function(){editIdentificationHeader(page)}),$(".btnAddXmlDocumentAttribute",page).on("click",function(){editXmlDocumentAttribute(page)}),$(".btnAddSubtitleProfile",page).on("click",function(){editSubtitleProfile(page)}),$(".dlnaProfileForm").off("submit",DlnaProfilePage.onSubmit).on("submit",DlnaProfilePage.onSubmit),$(".editDirectPlayProfileForm").off("submit",DlnaProfilePage.onDirectPlayFormSubmit).on("submit",DlnaProfilePage.onDirectPlayFormSubmit),$(".transcodingProfileForm").off("submit",DlnaProfilePage.onTranscodingProfileFormSubmit).on("submit",DlnaProfilePage.onTranscodingProfileFormSubmit),$(".containerProfileForm").off("submit",DlnaProfilePage.onContainerProfileFormSubmit).on("submit",DlnaProfilePage.onContainerProfileFormSubmit),$(".codecProfileForm").off("submit",DlnaProfilePage.onCodecProfileFormSubmit).on("submit",DlnaProfilePage.onCodecProfileFormSubmit),$(".editResponseProfileForm").off("submit",DlnaProfilePage.onResponseProfileFormSubmit).on("submit",DlnaProfilePage.onResponseProfileFormSubmit),$(".identificationHeaderForm").off("submit",DlnaProfilePage.onIdentificationHeaderFormSubmit).on("submit",DlnaProfilePage.onIdentificationHeaderFormSubmit),$(".xmlAttributeForm").off("submit",DlnaProfilePage.onXmlAttributeFormSubmit).on("submit",DlnaProfilePage.onXmlAttributeFormSubmit),$(".subtitleProfileForm").off("submit",DlnaProfilePage.onSubtitleProfileFormSubmit).on("submit",DlnaProfilePage.onSubtitleProfileFormSubmit)}).on("pageshow","#dlnaProfilePage",function(){var page=this;$("#radioInfo",page).trigger("click"),loadProfile(page)}),window.DlnaProfilePage={onSubmit:function(){Dashboard.showLoadingMsg();var form=this,page=$(form).parents(".page");return saveProfile(page,currentProfile),!1},onDirectPlayFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveDirectPlayProfile(page),!1},onTranscodingProfileFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveTranscodingProfile(page),!1},onContainerProfileFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveContainerProfile(page),!1},onCodecProfileFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveCodecProfile(page),!1},onResponseProfileFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveResponseProfile(page),!1},onIdentificationHeaderFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveIdentificationHeader(page),!1},onXmlAttributeFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveXmlDocumentAttribute(page),!1},onSubtitleProfileFormSubmit:function(){var form=this,page=$(form).parents(".page");return saveSubtitleProfile(page),!1}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/dlnaprofiles.js b/dashboard-ui/scripts/dlnaprofiles.js index 636033f167..c41b4e770c 100644 --- a/dashboard-ui/scripts/dlnaprofiles.js +++ b/dashboard-ui/scripts/dlnaprofiles.js @@ -1,122 +1 @@ -define(['jQuery', 'listViewStyle'], function ($) { - 'use strict'; - - function loadProfiles(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getJSON(ApiClient.getUrl("Dlna/ProfileInfos")).then(function (result) { - - renderUserProfiles(page, result); - renderSystemProfiles(page, result); - - Dashboard.hideLoadingMsg(); - }); - - } - - function renderUserProfiles(page, profiles) { - - renderProfiles(page, page.querySelector('.customProfiles'), profiles.filter(function (p) { - return p.Type == 'User'; - })); - } - - function renderSystemProfiles(page, profiles) { - - renderProfiles(page, page.querySelector('.systemProfiles'), profiles.filter(function (p) { - return p.Type == 'System'; - })); - } - - function renderProfiles(page, element, profiles) { - - var html = ''; - - if (profiles.length) { - html += '
'; - } - - for (var i = 0, length = profiles.length; i < length; i++) { - - var profile = profiles[i]; - - html += '
'; - - html += ""; - html += 'dvr'; - html += ""; - - html += ''; - - if (profile.Type == 'User') { - html += ''; - } - - html += '
'; - } - - if (profiles.length) { - html += '
'; - } - - element.innerHTML = html; - - $('.btnDeleteProfile', element).on('click', function () { - - var id = this.getAttribute('data-profileid'); - deleteProfile(page, id); - }); - } - - function deleteProfile(page, id) { - - require(['confirm'], function (confirm) { - - confirm(Globalize.translate('MessageConfirmProfileDeletion'), Globalize.translate('HeaderConfirmProfileDeletion')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl("Dlna/Profiles/" + id) - - }).then(function () { - - Dashboard.hideLoadingMsg(); - - loadProfiles(page); - }); - }); - }); - } - - function getTabs() { - return [ - { - href: 'dlnasettings.html', - name: Globalize.translate('TabSettings') - }, - { - href: 'dlnaprofiles.html', - name: Globalize.translate('TabProfiles') - }]; - } - - $(document).on('pageshow', "#dlnaProfilesPage", function () { - - LibraryMenu.setTabs('dlna', 1, getTabs); - var page = this; - - loadProfiles(page); - - }); - -}); +define(["jQuery","listViewStyle"],function($){"use strict";function loadProfiles(page){Dashboard.showLoadingMsg(),ApiClient.getJSON(ApiClient.getUrl("Dlna/ProfileInfos")).then(function(result){renderUserProfiles(page,result),renderSystemProfiles(page,result),Dashboard.hideLoadingMsg()})}function renderUserProfiles(page,profiles){renderProfiles(page,page.querySelector(".customProfiles"),profiles.filter(function(p){return"User"==p.Type}))}function renderSystemProfiles(page,profiles){renderProfiles(page,page.querySelector(".systemProfiles"),profiles.filter(function(p){return"System"==p.Type}))}function renderProfiles(page,element,profiles){var html="";profiles.length&&(html+='
');for(var i=0,length=profiles.length;i',html+="",html+='dvr',html+="",html+='","User"==profile.Type&&(html+=''),html+="
"}profiles.length&&(html+="
"),element.innerHTML=html,$(".btnDeleteProfile",element).on("click",function(){var id=this.getAttribute("data-profileid");deleteProfile(page,id)})}function deleteProfile(page,id){require(["confirm"],function(confirm){confirm(Globalize.translate("MessageConfirmProfileDeletion"),Globalize.translate("HeaderConfirmProfileDeletion")).then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Dlna/Profiles/"+id)}).then(function(){Dashboard.hideLoadingMsg(),loadProfiles(page)})})})}function getTabs(){return[{href:"dlnasettings.html",name:Globalize.translate("TabSettings")},{href:"dlnaprofiles.html",name:Globalize.translate("TabProfiles")}]}$(document).on("pageshow","#dlnaProfilesPage",function(){LibraryMenu.setTabs("dlna",1,getTabs);var page=this;loadProfiles(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/dlnasettings.js b/dashboard-ui/scripts/dlnasettings.js index 91325e5de5..2ea7077265 100644 --- a/dashboard-ui/scripts/dlnasettings.js +++ b/dashboard-ui/scripts/dlnasettings.js @@ -1,83 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function loadPage(page, config, users) { - - page.querySelector('#chkEnablePlayTo').checked = config.EnablePlayTo; - page.querySelector('#chkEnableDlnaDebugLogging').checked = config.EnableDebugLog; - - $('#txtClientDiscoveryInterval', page).val(config.ClientDiscoveryIntervalSeconds); - - $('#chkEnableServer', page).checked(config.EnableServer); - $('#chkBlastAliveMessages', page).checked(config.BlastAliveMessages); - $('#txtBlastInterval', page).val(config.BlastAliveMessageIntervalSeconds); - - var usersHtml = users.map(function (u) { - return ''; - }).join(''); - - $('#selectUser', page).html(usersHtml).val(config.DefaultUserId || ''); - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getNamedConfiguration("dlna").then(function (config) { - - config.EnablePlayTo = form.querySelector('#chkEnablePlayTo').checked; - config.EnableDebugLog = form.querySelector('#chkEnableDlnaDebugLogging').checked; - - config.ClientDiscoveryIntervalSeconds = $('#txtClientDiscoveryInterval', form).val(); - - config.EnableServer = $('#chkEnableServer', form).checked(); - config.BlastAliveMessages = $('#chkBlastAliveMessages', form).checked(); - config.BlastAliveMessageIntervalSeconds = $('#txtBlastInterval', form).val(); - config.DefaultUserId = $('#selectUser', form).val(); - - ApiClient.updateNamedConfiguration("dlna", config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'dlnasettings.html', - name: Globalize.translate('TabSettings') - }, - { - href: 'dlnaprofiles.html', - name: Globalize.translate('TabProfiles') - }]; - } - - $(document).on('pageinit', "#dlnaSettingsPage", function () { - - $('.dlnaSettingsForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#dlnaSettingsPage", function () { - - LibraryMenu.setTabs('dlna', 0, getTabs); - Dashboard.showLoadingMsg(); - - var page = this; - - var promise1 = ApiClient.getNamedConfiguration("dlna"); - var promise2 = ApiClient.getUsers(); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadPage(page, responses[0], responses[1]); - - }); - - }); - -}); +define(["jQuery","fnchecked"],function($){"use strict";function loadPage(page,config,users){page.querySelector("#chkEnablePlayTo").checked=config.EnablePlayTo,page.querySelector("#chkEnableDlnaDebugLogging").checked=config.EnableDebugLog,$("#txtClientDiscoveryInterval",page).val(config.ClientDiscoveryIntervalSeconds),$("#chkEnableServer",page).checked(config.EnableServer),$("#chkBlastAliveMessages",page).checked(config.BlastAliveMessages),$("#txtBlastInterval",page).val(config.BlastAliveMessageIntervalSeconds);var usersHtml=users.map(function(u){return'"}).join("");$("#selectUser",page).html(usersHtml).val(config.DefaultUserId||""),Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getNamedConfiguration("dlna").then(function(config){config.EnablePlayTo=form.querySelector("#chkEnablePlayTo").checked,config.EnableDebugLog=form.querySelector("#chkEnableDlnaDebugLogging").checked,config.ClientDiscoveryIntervalSeconds=$("#txtClientDiscoveryInterval",form).val(),config.EnableServer=$("#chkEnableServer",form).checked(),config.BlastAliveMessages=$("#chkBlastAliveMessages",form).checked(),config.BlastAliveMessageIntervalSeconds=$("#txtBlastInterval",form).val(),config.DefaultUserId=$("#selectUser",form).val(),ApiClient.updateNamedConfiguration("dlna",config).then(Dashboard.processServerConfigurationUpdateResult)}),!1}function getTabs(){return[{href:"dlnasettings.html",name:Globalize.translate("TabSettings")},{href:"dlnaprofiles.html",name:Globalize.translate("TabProfiles")}]}$(document).on("pageinit","#dlnaSettingsPage",function(){$(".dlnaSettingsForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#dlnaSettingsPage",function(){LibraryMenu.setTabs("dlna",0,getTabs),Dashboard.showLoadingMsg();var page=this,promise1=ApiClient.getNamedConfiguration("dlna"),promise2=ApiClient.getUsers();Promise.all([promise1,promise2]).then(function(responses){loadPage(page,responses[0],responses[1])})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/edititemmetadata.js b/dashboard-ui/scripts/edititemmetadata.js index d99c2f9284..11b1edb0ee 100644 --- a/dashboard-ui/scripts/edititemmetadata.js +++ b/dashboard-ui/scripts/edititemmetadata.js @@ -1,38 +1 @@ -define(['loading'], function (loading) { - 'use strict'; - - function reload(context, itemId) { - - loading.show(); - - if (itemId) { - require(['metadataEditor'], function (metadataEditor) { - - metadataEditor.embed(context.querySelector('.editPageInnerContent'), itemId, ApiClient.serverInfo().Id); - }); - } else { - context.querySelector('.editPageInnerContent').innerHTML = ''; - loading.hide(); - } - } - - return function (view, params) { - - view.addEventListener('viewshow', function () { - reload(this, MetadataEditor.getCurrentItemId()); - }); - - MetadataEditor.setCurrentItemId(null); - - view.querySelector('.libraryTree').addEventListener('itemclicked', function (event) { - - var data = event.detail; - - if (data.id != MetadataEditor.getCurrentItemId()) { - - MetadataEditor.setCurrentItemId(data.id); - reload(view, data.id); - } - }); - }; -}); +define(["loading"],function(loading){"use strict";function reload(context,itemId){loading.show(),itemId?require(["metadataEditor"],function(metadataEditor){metadataEditor.embed(context.querySelector(".editPageInnerContent"),itemId,ApiClient.serverInfo().Id)}):(context.querySelector(".editPageInnerContent").innerHTML="",loading.hide())}return function(view,params){view.addEventListener("viewshow",function(){reload(this,MetadataEditor.getCurrentItemId())}),MetadataEditor.setCurrentItemId(null),view.querySelector(".libraryTree").addEventListener("itemclicked",function(event){var data=event.detail;data.id!=MetadataEditor.getCurrentItemId()&&(MetadataEditor.setCurrentItemId(data.id),reload(view,data.id))})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/editorsidebar.js b/dashboard-ui/scripts/editorsidebar.js index be3d853b7f..631eba0699 100644 --- a/dashboard-ui/scripts/editorsidebar.js +++ b/dashboard-ui/scripts/editorsidebar.js @@ -1,482 +1 @@ -define(['datetime', 'jQuery', 'material-icons'], function (datetime, $) { - 'use strict'; - - function getNode(item, folderState, selected) { - - var htmlName = getNodeInnerHtml(item); - - var node = { - id: item.Id, - text: htmlName, - - state: { - opened: item.IsFolder && folderState == 'open', - selected: selected - }, - - li_attr: { - serveritemtype: item.Type, - collectiontype: item.CollectionType - } - }; - - if (item.IsFolder) { - node.children = [ - { - text: 'Loading...', - icon: false - }]; - node.icon = false; - } - else { - node.icon = false; - } - - if (node.state.opened) { - node.li_attr.loadedFromServer = true; - } - - if (selected) { - selectedNodeId = item.Id; - } - - return node; - } - - function getNodeInnerHtml(item) { - - var name = item.Name; - - // Channel number - if (item.Number) { - name = item.Number + " - " + name; - } - if (item.IndexNumber != null && item.Type != "Season") { - name = item.IndexNumber + " - " + name; - } - - var cssClass = "editorNode"; - - if (item.LocationType == "Offline") { - cssClass += " offlineEditorNode"; - } - - var htmlName = "
"; - - if (item.LockData) { - htmlName += 'lock'; - } - - htmlName += name; - - if (!item.ImageTags || !item.ImageTags.Primary) { - htmlName += ''; - } - - if (!item.BackdropImageTags || !item.BackdropImageTags.length) { - if (item.Type !== "Episode" && item.Type !== "Season" && item.MediaType !== "Audio" && item.Type !== "TvChannel" && item.Type !== "MusicAlbum") { - htmlName += ''; - } - } - - if (!item.ImageTags || !item.ImageTags.Logo) { - if (item.Type == "Movie" || item.Type == "Trailer" || item.Type == "Series" || item.Type == "MusicArtist" || item.Type == "BoxSet") { - htmlName += ''; - } - } - - if (item.Type == "Episode" && item.LocationType == "Virtual") { - - try { - if (item.PremiereDate && (new Date().getTime() >= datetime.parseISO8601Date(item.PremiereDate, true).getTime())) { - htmlName += ''; - } - } catch (err) { - - } - - } - - htmlName += "
"; - - return htmlName; - } - - function loadChildrenOfRootNode(page, scope, callback) { - - ApiClient.getLiveTvChannels({ limit: 0 }).then(function (result) { - - var nodes = []; - - nodes.push({ - - id: 'MediaFolders', - text: Globalize.translate('HeaderMediaFolders'), - state: { - opened: true - }, - li_attr: { - itemtype: 'mediafolders', - loadedFromServer: true - }, - icon: false - }); - - if (result.TotalRecordCount) { - - nodes.push({ - - id: 'livetv', - text: Globalize.translate('HeaderLiveTV'), - state: { - opened: false - }, - li_attr: { - itemtype: 'livetv' - }, - children: [ - { - text: 'Loading...', - icon: false - }], - icon: false - }); - } - - callback.call(scope, nodes); - - nodesToLoad.push('MediaFolders'); - }); - } - - function loadLiveTvChannels(service, openItems, callback) { - - ApiClient.getLiveTvChannels({ - - ServiceName: service, - AddCurrentProgram: false - - }).then(function (result) { - - var nodes = result.Items.map(function (i) { - - var state = openItems.indexOf(i.Id) == -1 ? 'closed' : 'open'; - - return getNode(i, state, false); - - }); - - callback(nodes); - - }); - - } - - function loadMediaFolders(page, scope, openItems, callback) { - - ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders")).then(function (result) { - - var nodes = result.Items.map(function (n) { - - var state = openItems.indexOf(n.Id) == -1 ? 'closed' : 'open'; - - return getNode(n, state, false); - - }); - - callback.call(scope, nodes); - - for (var i = 0, length = nodes.length; i < length; i++) { - if (nodes[i].state.opened) { - - nodesToLoad.push(nodes[i].id); - } - } - - }); - - } - - function loadNode(page, scope, node, openItems, selectedId, currentUser, callback) { - - var id = node.id; - - if (id == '#') { - - loadChildrenOfRootNode(page, scope, callback); - return; - } - - if (id == 'livetv') { - - loadLiveTvChannels(id, openItems, callback); - return; - } - - if (id == 'MediaFolders') { - - loadMediaFolders(page, scope, openItems, callback); - return; - } - - var query = { - ParentId: id, - Fields: 'Settings' - }; - - var itemtype = node.li_attr.itemtype; - - if (itemtype != "Season" && itemtype != "Series") { - query.SortBy = "SortName"; - } - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - var nodes = result.Items.map(function (n) { - - var state = openItems.indexOf(n.Id) == -1 ? 'closed' : 'open'; - - return getNode(n, state, n.Id == selectedId); - - }); - - callback.call(scope, nodes); - - for (var i = 0, length = nodes.length; i < length; i++) { - if (nodes[i].state.opened) { - - nodesToLoad.push(nodes[i].id); - } - } - - }); - - } - - function scrollToNode(id) { - - var elem = $('#' + id)[0]; - - if (elem) { - // commenting out for now because it's causing the whole window to scroll in chrome - elem.scrollIntoView(); - } - } - - function initializeTree(page, currentUser, openItems, selectedId) { - - require(['jstree'], function () { - initializeTreeInternal(page, currentUser, openItems, selectedId); - }); - } - - function onNodeSelect(event, data) { - var node = data.node; - - var eventData = { - id: node.id, - itemType: node.li_attr.itemtype, - serverItemType: node.li_attr.serveritemtype, - collectionType: node.li_attr.collectiontype - }; - - if (eventData.itemType != 'livetv' && eventData.itemType != 'mediafolders') { - - // We'd like to prevent these from being editable but this removes the ability to perform a top level refresh - //if (eventData.serverItemType != 'UserView' && eventData.serverItemType != 'CollectionFolder' && !eventData.collectionType) - { - this.dispatchEvent(new CustomEvent('itemclicked', { - detail: eventData, - bubbles: true, - cancelable: false - })); - } - } - } - - function onNodeOpen(event, data) { - - var page = $(this).parents('.page')[0]; - var node = data.node; - - if (node.children && node.children) { - loadNodesToLoad(page, node); - } - - if (node.li_attr && node.id != '#' && !node.li_attr.loadedFromServer) { - - node.li_attr.loadedFromServer = true; - - $.jstree.reference(".libraryTree", page).load_node(node.id, loadNodeCallback); - } - } - - function onNodeLoad(event, data) { - - var page = $(this).parents('.page')[0]; - var node = data.node; - - if (node.children && node.children) { - loadNodesToLoad(page, node); - } - - if (node.li_attr && node.id != '#' && !node.li_attr.loadedFromServer) { - - node.li_attr.loadedFromServer = true; - - $.jstree.reference(".libraryTree", page).load_node(node.id, loadNodeCallback); - } - } - - function initializeTreeInternal(page, currentUser, openItems, selectedId) { - - nodesToLoad = []; - selectedNodeId = null; - - $.jstree.destroy(); - - $('.libraryTree', page).jstree({ - - "plugins": ["wholerow"], - - core: { - - check_callback: true, - data: function (node, callback) { - - loadNode(page, this, node, openItems, selectedId, currentUser, callback); - }, - - themes: { - variant: 'large' - } - } - - }).off('select_node.jstree', onNodeSelect).on('select_node.jstree', onNodeSelect).off('open_node.jstree', onNodeOpen).on('open_node.jstree', onNodeOpen).off('load_node.jstree', onNodeLoad).on('load_node.jstree', onNodeLoad); - } - - function loadNodesToLoad(page, node) { - - var children = node.children; - - for (var i = 0, length = children.length; i < length; i++) { - - var child = children[i]; - - if (nodesToLoad.indexOf(child) != -1) { - - nodesToLoad = nodesToLoad.filter(function (n) { - return n != child; - }); - - $.jstree.reference(".libraryTree", page).load_node(child, loadNodeCallback); - } - } - } - - function loadNodeCallback(node) { - - if (selectedNodeId && node.children && node.children.indexOf(selectedNodeId) != -1) { - - setTimeout(function () { - - scrollToNode(selectedNodeId); - }, 500); - } - } - - var nodesToLoad = []; - var selectedNodeId; - - function updateEditorNode(page, item) { - - var elem = $('#' + item.Id + '>a', page)[0]; - - if (elem == null) { - return; - } - - $('.editorNode', elem).remove(); - - $(elem).append(getNodeInnerHtml(item)); - - if (item.IsFolder) { - - var tree = jQuery.jstree._reference(".libraryTree"); - var currentNode = tree._get_node(null, false); - tree.refresh(currentNode); - } - } - - $(document).on('itemsaved', ".metadataEditorPage", function (e, item) { - - updateEditorNode(this, item); - - }).on('pagebeforeshow', ".metadataEditorPage", function () { - - require(['css!css/metadataeditor.css']); - - }).on('pagebeforeshow', ".metadataEditorPage", function () { - - var page = this; - - Dashboard.getCurrentUser().then(function (user) { - - var id = getCurrentItemId(); - - if (id) { - - ApiClient.getAncestorItems(id, user.Id).then(function (ancestors) { - - var ids = ancestors.map(function (i) { - return i.Id; - }); - - initializeTree(page, user, ids, id); - }); - - } else { - initializeTree(page, user, []); - } - - }); - - }).on('pagebeforehide', ".metadataEditorPage", function () { - - var page = this; - - $('.libraryTree', page).off('select_node.jstree', onNodeSelect).off('open_node.jstree', onNodeOpen).off('load_node.jstree', onNodeLoad); - - }); - - var itemId; - function setCurrentItemId(id) { - itemId = id; - } - - function getCurrentItemId() { - - if (itemId) { - return itemId; - } - - var url = window.location.hash || window.location.href; - - return getParameterByName('id', url); - } - - window.MetadataEditor = { - getItemPromise: function () { - var currentItemId = getCurrentItemId(); - - if (currentItemId) { - return ApiClient.getItem(Dashboard.getCurrentUserId(), currentItemId); - } - - return ApiClient.getRootFolder(Dashboard.getCurrentUserId()); - }, - getCurrentItemId: getCurrentItemId, - setCurrentItemId: setCurrentItemId - }; - -}); \ No newline at end of file +define(["datetime","jQuery","material-icons"],function(datetime,$){"use strict";function getNode(item,folderState,selected){var htmlName=getNodeInnerHtml(item),node={id:item.Id,text:htmlName,state:{opened:item.IsFolder&&"open"==folderState,selected:selected},li_attr:{serveritemtype:item.Type,collectiontype:item.CollectionType}};return item.IsFolder?(node.children=[{text:"Loading...",icon:!1}],node.icon=!1):node.icon=!1,node.state.opened&&(node.li_attr.loadedFromServer=!0),selected&&(selectedNodeId=item.Id),node}function getNodeInnerHtml(item){var name=item.Name;item.Number&&(name=item.Number+" - "+name),null!=item.IndexNumber&&"Season"!=item.Type&&(name=item.IndexNumber+" - "+name);var cssClass="editorNode";"Offline"==item.LocationType&&(cssClass+=" offlineEditorNode");var htmlName="
";if(item.LockData&&(htmlName+='lock'),htmlName+=name,item.ImageTags&&item.ImageTags.Primary||(htmlName+=''),item.BackdropImageTags&&item.BackdropImageTags.length||"Episode"!==item.Type&&"Season"!==item.Type&&"Audio"!==item.MediaType&&"TvChannel"!==item.Type&&"MusicAlbum"!==item.Type&&(htmlName+=''),item.ImageTags&&item.ImageTags.Logo||"Movie"!=item.Type&&"Trailer"!=item.Type&&"Series"!=item.Type&&"MusicArtist"!=item.Type&&"BoxSet"!=item.Type||(htmlName+=''),"Episode"==item.Type&&"Virtual"==item.LocationType)try{item.PremiereDate&&(new Date).getTime()>=datetime.parseISO8601Date(item.PremiereDate,!0).getTime()&&(htmlName+='')}catch(err){}return htmlName+="
"}function loadChildrenOfRootNode(page,scope,callback){ApiClient.getLiveTvChannels({limit:0}).then(function(result){var nodes=[];nodes.push({id:"MediaFolders",text:Globalize.translate("HeaderMediaFolders"),state:{opened:!0},li_attr:{itemtype:"mediafolders",loadedFromServer:!0},icon:!1}),result.TotalRecordCount&&nodes.push({id:"livetv",text:Globalize.translate("HeaderLiveTV"),state:{opened:!1},li_attr:{itemtype:"livetv"},children:[{text:"Loading...",icon:!1}],icon:!1}),callback.call(scope,nodes),nodesToLoad.push("MediaFolders")})}function loadLiveTvChannels(service,openItems,callback){ApiClient.getLiveTvChannels({ServiceName:service,AddCurrentProgram:!1}).then(function(result){var nodes=result.Items.map(function(i){var state=openItems.indexOf(i.Id)==-1?"closed":"open";return getNode(i,state,!1)});callback(nodes)})}function loadMediaFolders(page,scope,openItems,callback){ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders")).then(function(result){var nodes=result.Items.map(function(n){var state=openItems.indexOf(n.Id)==-1?"closed":"open";return getNode(n,state,!1)});callback.call(scope,nodes);for(var i=0,length=nodes.length;ia",page)[0];if(null!=elem&&($(".editorNode",elem).remove(),$(elem).append(getNodeInnerHtml(item)),item.IsFolder)){var tree=jQuery.jstree._reference(".libraryTree"),currentNode=tree._get_node(null,!1);tree.refresh(currentNode)}}function setCurrentItemId(id){itemId=id}function getCurrentItemId(){if(itemId)return itemId;var url=window.location.hash||window.location.href;return getParameterByName("id",url)}var selectedNodeId,nodesToLoad=[];$(document).on("itemsaved",".metadataEditorPage",function(e,item){updateEditorNode(this,item)}).on("pagebeforeshow",".metadataEditorPage",function(){require(["css!css/metadataeditor.css"])}).on("pagebeforeshow",".metadataEditorPage",function(){var page=this;Dashboard.getCurrentUser().then(function(user){var id=getCurrentItemId();id?ApiClient.getAncestorItems(id,user.Id).then(function(ancestors){var ids=ancestors.map(function(i){return i.Id});initializeTree(page,user,ids,id)}):initializeTree(page,user,[])})}).on("pagebeforehide",".metadataEditorPage",function(){var page=this;$(".libraryTree",page).off("select_node.jstree",onNodeSelect).off("open_node.jstree",onNodeOpen).off("load_node.jstree",onNodeLoad)});var itemId;window.MetadataEditor={getItemPromise:function(){var currentItemId=getCurrentItemId();return currentItemId?ApiClient.getItem(Dashboard.getCurrentUserId(),currentItemId):ApiClient.getRootFolder(Dashboard.getCurrentUserId())},getCurrentItemId:getCurrentItemId,setCurrentItemId:setCurrentItemId}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/encodingsettings.js b/dashboard-ui/scripts/encodingsettings.js index 211bd36c67..e17d6dde00 100644 --- a/dashboard-ui/scripts/encodingsettings.js +++ b/dashboard-ui/scripts/encodingsettings.js @@ -1,203 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function loadPage(page, config, systemInfo) { - - page.querySelector('#chkEnableThrottle').checked = config.EnableThrottling; - - $('#selectVideoDecoder', page).val(config.HardwareAccelerationType); - $('#selectThreadCount', page).val(config.EncodingThreadCount); - $('#txtDownMixAudioBoost', page).val(config.DownMixAudioBoost); - page.querySelector('.txtEncoderPath').value = config.EncoderAppPath || ''; - $('#txtTranscodingTempPath', page).val(config.TranscodingTempPath || ''); - $('#txtVaapiDevice', page).val(config.VaapiDevice || ''); - - page.querySelector('#selectH264Preset').value = config.H264Preset || ''; - page.querySelector('#txtH264Crf').value = config.H264Crf || ''; - - var selectEncoderPath = page.querySelector('#selectEncoderPath'); - - selectEncoderPath.value = systemInfo.EncoderLocationType; - onSelectEncoderPathChange.call(selectEncoderPath); - - page.querySelector('#selectVideoDecoder').dispatchEvent(new CustomEvent('change', { - bubbles: true - })); - - Dashboard.hideLoadingMsg(); - } - - function onSaveEncodingPathFailure(response) { - - Dashboard.hideLoadingMsg(); - - var msg = ''; - - // This is a fallback that handles both 404 and 400 (no path entered) - msg = Globalize.translate('FFmpegSavePathNotFound'); - - require(['alert'], function (alert) { - alert(msg); - }); - } - - function updateEncoder(form) { - - return ApiClient.getSystemInfo().then(function (systemInfo) { - - return ApiClient.ajax({ - url: ApiClient.getUrl('System/MediaEncoder/Path'), - type: 'POST', - data: { - Path: form.querySelector('.txtEncoderPath').value, - PathType: form.querySelector('#selectEncoderPath').value - } - }).then(Dashboard.processServerConfigurationUpdateResult, onSaveEncodingPathFailure); - }); - } - - function onSubmit() { - - var form = this; - - var onDecoderConfirmed = function () { - Dashboard.showLoadingMsg(); - - ApiClient.getNamedConfiguration("encoding").then(function (config) { - - config.DownMixAudioBoost = $('#txtDownMixAudioBoost', form).val(); - config.TranscodingTempPath = $('#txtTranscodingTempPath', form).val(); - config.EncodingThreadCount = $('#selectThreadCount', form).val(); - config.HardwareAccelerationType = $('#selectVideoDecoder', form).val(); - config.VaapiDevice = $('#txtVaapiDevice', form).val(); - - config.H264Preset = form.querySelector('#selectH264Preset').value; - config.H264Crf = parseInt(form.querySelector('#txtH264Crf').value || '0'); - - config.EnableThrottling = form.querySelector('#chkEnableThrottle').checked; - - ApiClient.updateNamedConfiguration("encoding", config).then(function () { - - updateEncoder(form); - }); - }); - }; - - if ($('#selectVideoDecoder', form).val()) { - - require(['alert'], function (alert) { - alert({ - title: Globalize.translate('TitleHardwareAcceleration'), - text: Globalize.translate('HardwareAccelerationWarning') - }).then(onDecoderConfirmed); - }); - - } else { - onDecoderConfirmed(); - } - - - // Disable default form submission - return false; - } - - function onSelectEncoderPathChange(e) { - - var page = $(this).parents('.page')[0]; - - if (this.value == 'Custom') { - page.querySelector('.fldEncoderPath').classList.remove('hide'); - page.querySelector('.txtEncoderPath').setAttribute('required', 'required'); - } else { - page.querySelector('.fldEncoderPath').classList.add('hide'); - page.querySelector('.txtEncoderPath').removeAttribute('required'); - } - } - - $(document).on('pageinit', "#encodingSettingsPage", function () { - - var page = this; - - page.querySelector('#selectVideoDecoder').addEventListener('change', function () { - - if (this.value == 'vaapi') { - - page.querySelector('.fldVaapiDevice').classList.remove('hide'); - page.querySelector('#txtVaapiDevice').setAttribute('required', 'required'); - - } else { - page.querySelector('.fldVaapiDevice').classList.add('hide'); - page.querySelector('#txtVaapiDevice').removeAttribute('required'); - } - }); - - $('#btnSelectEncoderPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - includeFiles: true, - callback: function (path) { - - if (path) { - $('.txtEncoderPath', page).val(path); - } - picker.close(); - } - }); - }); - }); - - $('#btnSelectTranscodingTempPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - - if (path) { - $('#txtTranscodingTempPath', page).val(path); - } - picker.close(); - }, - - header: Globalize.translate('HeaderSelectTranscodingPath'), - - instruction: Globalize.translate('HeaderSelectTranscodingPathHelp') - }); - }); - }); - - $('.encodingSettingsForm').off('submit', onSubmit).on('submit', onSubmit); - - page.querySelector('#selectEncoderPath').addEventListener('change', onSelectEncoderPathChange); - - }).on('pageshow', "#encodingSettingsPage", function () { - - Dashboard.showLoadingMsg(); - - var page = this; - - ApiClient.getNamedConfiguration("encoding").then(function (config) { - - ApiClient.getSystemInfo().then(function (systemInfo) { - - if (systemInfo.EncoderLocationType == "External") { - page.querySelector('.fldSelectEncoderPathType').classList.add('hide'); - } else { - page.querySelector('.fldSelectEncoderPathType').classList.remove('hide'); - } - - loadPage(page, config, systemInfo); - }); - }); - - }); - -}); +define(["jQuery"],function($){"use strict";function loadPage(page,config,systemInfo){page.querySelector("#chkEnableThrottle").checked=config.EnableThrottling,$("#selectVideoDecoder",page).val(config.HardwareAccelerationType),$("#selectThreadCount",page).val(config.EncodingThreadCount),$("#txtDownMixAudioBoost",page).val(config.DownMixAudioBoost),page.querySelector(".txtEncoderPath").value=config.EncoderAppPath||"",$("#txtTranscodingTempPath",page).val(config.TranscodingTempPath||""),$("#txtVaapiDevice",page).val(config.VaapiDevice||""),page.querySelector("#selectH264Preset").value=config.H264Preset||"",page.querySelector("#txtH264Crf").value=config.H264Crf||"";var selectEncoderPath=page.querySelector("#selectEncoderPath");selectEncoderPath.value=systemInfo.EncoderLocationType,onSelectEncoderPathChange.call(selectEncoderPath),page.querySelector("#selectVideoDecoder").dispatchEvent(new CustomEvent("change",{bubbles:!0})),Dashboard.hideLoadingMsg()}function onSaveEncodingPathFailure(response){Dashboard.hideLoadingMsg();var msg="";msg=Globalize.translate("FFmpegSavePathNotFound"),require(["alert"],function(alert){alert(msg)})}function updateEncoder(form){return ApiClient.getSystemInfo().then(function(systemInfo){return ApiClient.ajax({url:ApiClient.getUrl("System/MediaEncoder/Path"),type:"POST",data:{Path:form.querySelector(".txtEncoderPath").value,PathType:form.querySelector("#selectEncoderPath").value}}).then(Dashboard.processServerConfigurationUpdateResult,onSaveEncodingPathFailure)})}function onSubmit(){var form=this,onDecoderConfirmed=function(){Dashboard.showLoadingMsg(),ApiClient.getNamedConfiguration("encoding").then(function(config){config.DownMixAudioBoost=$("#txtDownMixAudioBoost",form).val(),config.TranscodingTempPath=$("#txtTranscodingTempPath",form).val(),config.EncodingThreadCount=$("#selectThreadCount",form).val(),config.HardwareAccelerationType=$("#selectVideoDecoder",form).val(),config.VaapiDevice=$("#txtVaapiDevice",form).val(),config.H264Preset=form.querySelector("#selectH264Preset").value,config.H264Crf=parseInt(form.querySelector("#txtH264Crf").value||"0"),config.EnableThrottling=form.querySelector("#chkEnableThrottle").checked,ApiClient.updateNamedConfiguration("encoding",config).then(function(){updateEncoder(form)})})};return $("#selectVideoDecoder",form).val()?require(["alert"],function(alert){alert({title:Globalize.translate("TitleHardwareAcceleration"),text:Globalize.translate("HardwareAccelerationWarning")}).then(onDecoderConfirmed)}):onDecoderConfirmed(),!1}function onSelectEncoderPathChange(e){var page=$(this).parents(".page")[0];"Custom"==this.value?(page.querySelector(".fldEncoderPath").classList.remove("hide"),page.querySelector(".txtEncoderPath").setAttribute("required","required")):(page.querySelector(".fldEncoderPath").classList.add("hide"),page.querySelector(".txtEncoderPath").removeAttribute("required"))}$(document).on("pageinit","#encodingSettingsPage",function(){var page=this;page.querySelector("#selectVideoDecoder").addEventListener("change",function(){"vaapi"==this.value?(page.querySelector(".fldVaapiDevice").classList.remove("hide"),page.querySelector("#txtVaapiDevice").setAttribute("required","required")):(page.querySelector(".fldVaapiDevice").classList.add("hide"),page.querySelector("#txtVaapiDevice").removeAttribute("required"))}),$("#btnSelectEncoderPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({includeFiles:!0,callback:function(path){path&&$(".txtEncoderPath",page).val(path),picker.close()}})})}),$("#btnSelectTranscodingTempPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtTranscodingTempPath",page).val(path),picker.close()},header:Globalize.translate("HeaderSelectTranscodingPath"),instruction:Globalize.translate("HeaderSelectTranscodingPathHelp")})})}),$(".encodingSettingsForm").off("submit",onSubmit).on("submit",onSubmit),page.querySelector("#selectEncoderPath").addEventListener("change",onSelectEncoderPathChange)}).on("pageshow","#encodingSettingsPage",function(){Dashboard.showLoadingMsg();var page=this;ApiClient.getNamedConfiguration("encoding").then(function(config){ApiClient.getSystemInfo().then(function(systemInfo){"External"==systemInfo.EncoderLocationType?page.querySelector(".fldSelectEncoderPathType").classList.add("hide"):page.querySelector(".fldSelectEncoderPathType").classList.remove("hide"),loadPage(page,config,systemInfo)})})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/episodes.js b/dashboard-ui/scripts/episodes.js index ea689eb89a..ae0aaa2b27 100644 --- a/dashboard-ui/scripts/episodes.js +++ b/dashboard-ui/scripts/episodes.js @@ -1,266 +1 @@ -define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'cardBuilder', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView, cardBuilder) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var pageSize = libraryBrowser.getDefaultPageSize(); - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SeriesSortName,SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Episode", - Recursive: true, - Fields: "PrimaryImageAspectRatio,MediaSourceCount,UserData", - IsMissing: false, - IsVirtualUnaired: false, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb", - StartIndex: 0, - Limit: pageSize - }, - view: libraryBrowser.getSavedView(key) || 'Poster' - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey('episodes'); - } - return context.savedQueryKey; - } - - function onViewStyleChange() { - - var viewStyle = self.getCurrentViewStyle(); - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: false, - sortButton: false, - filterButton: false - }); - - var viewStyle = self.getCurrentViewStyle(); - - var html; - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - sortBy: query.SortBy, - showParentTitle: true - }); - } - else if (viewStyle == "PosterCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - showTitle: true, - showParentTitle: true, - scalable: true, - cardLayout: true - }); - } - else { - - // poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - showTitle: true, - showParentTitle: true, - overlayText: true, - scalable: true, - overlayPlayButton: true - }); - } - - var i, length; - var elems = tabContent.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(tabContent); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(tabContent); - } - - elems = tabContent.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = tabContent.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.showFilterMenu = function () { - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(tabContent), - mode: 'episodes' - }); - - Events.on(filterDialog, 'filterchange', function () { - reloadItems(tabContent); - }); - - filterDialog.show(); - }); - }; - - function initPage(tabContent) { - - tabContent.querySelector('.itemsContainer').addEventListener('needsrefresh', function () { - - reloadItems(tabContent); - }); - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - self.showFilterMenu(); - }); - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionTvdbRating'), - id: 'CommunityRating,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionPremiereDate'), - id: 'PremiereDate,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionDatePlayed'), - id: 'DatePlayed,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionPlayCount'), - id: 'PlayCount,SeriesSortName,SortName' - }, - { - name: Globalize.translate('OptionRuntime'), - id: 'Runtime,SeriesSortName,SortName' - }], - callback: function () { - reloadItems(tabContent); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - - var btnSelectView = tabContent.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), 'List,Poster,PosterCard'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - - var viewStyle = e.detail.viewStyle; - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - onViewStyleChange(); - reloadItems(tabContent); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - onViewStyleChange(); - - self.renderTab = function () { - - reloadItems(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","listView","cardBuilder","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,listView,cardBuilder){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SeriesSortName,SortName",SortOrder:"Ascending",IncludeItemTypes:"Episode",Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,UserData",IsMissing:!1,IsVirtualUnaired:!1,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||"Poster"},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("episodes")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");html="List"==viewStyle?listView.getListViewHtml({items:result.Items,sortBy:query.SortBy,showParentTitle:!0}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,showParentTitle:!0,scalable:!0,cardLayout:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,showParentTitle:!0,overlayText:!0,scalable:!0,overlayPlayButton:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i",void Dashboard.alert({message:msg,title:Globalize.translate("HeaderForgotPassword")})}}return function(view,params){function onSubmit(e){return ApiClient.ajax({type:"POST",url:ApiClient.getUrl("Users/ForgotPassword"),dataType:"json",data:{EnteredUsername:view.querySelector("#txtName").value}}).then(processForgotPasswordResult),e.preventDefault(),!1}view.querySelector("form").addEventListener("submit",onSubmit)}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/forgotpasswordpin.js b/dashboard-ui/scripts/forgotpasswordpin.js index 5c167a094f..e23314ea11 100644 --- a/dashboard-ui/scripts/forgotpasswordpin.js +++ b/dashboard-ui/scripts/forgotpasswordpin.js @@ -1,56 +1 @@ -define([], function () { - 'use strict'; - - function processForgotPasswordResult(result) { - - if (result.Success) { - - var msg = Globalize.translate('MessagePasswordResetForUsers'); - - msg += '
'; - msg += '
'; - msg += result.UsersReset.join('
'); - - Dashboard.alert({ - - message: msg, - title: Globalize.translate('HeaderPasswordReset'), - - callback: function () { - - window.location.href = 'login.html'; - } - }); - return; - } - - Dashboard.alert({ - - message: Globalize.translate('MessageInvalidForgotPasswordPin'), - title: Globalize.translate('HeaderPasswordReset') - }); - return; - } - - return function (view, params) { - - function onSubmit(e) { - - ApiClient.ajax({ - - type: 'POST', - url: ApiClient.getUrl('Users/ForgotPassword/Pin'), - dataType: 'json', - data: { - Pin: view.querySelector('#txtPin').value - } - - }).then(processForgotPasswordResult); - - e.preventDefault(); - return false; - } - - view.querySelector('form').addEventListener('submit', onSubmit); - }; -}); \ No newline at end of file +define([],function(){"use strict";function processForgotPasswordResult(result){if(result.Success){var msg=Globalize.translate("MessagePasswordResetForUsers");return msg+="
",msg+="
",msg+=result.UsersReset.join("
"),void Dashboard.alert({message:msg,title:Globalize.translate("HeaderPasswordReset"),callback:function(){window.location.href="login.html"}})}Dashboard.alert({message:Globalize.translate("MessageInvalidForgotPasswordPin"),title:Globalize.translate("HeaderPasswordReset")})}return function(view,params){function onSubmit(e){return ApiClient.ajax({type:"POST",url:ApiClient.getUrl("Users/ForgotPassword/Pin"),dataType:"json",data:{Pin:view.querySelector("#txtPin").value}}).then(processForgotPasswordResult),e.preventDefault(),!1}view.querySelector("form").addEventListener("submit",onSubmit)}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/gamegenrepage.js b/dashboard-ui/scripts/gamegenrepage.js index f3af6e7e9f..7e294097e0 100644 --- a/dashboard-ui/scripts/gamegenrepage.js +++ b/dashboard-ui/scripts/gamegenrepage.js @@ -1,84 +1 @@ -define(['jQuery', 'imageLoader'], function ($, imageLoader) { - 'use strict'; - - // The base query options - var query = { - - SortBy: "SortName", - SortOrder: "Ascending", - Recursive: true, - Fields: "DateCreated,ItemCounts", - StartIndex: 0 - }; - - function getSavedQueryKey() { - - return LibraryBrowser.getSavedQueryKey(); - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getGameGenres(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - - $('.listTopPaging', page).html(LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false - })); - - html = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'games', - showItemCounts: true, - centerText: true, - lazy: true - }); - - var elem = page.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - $('.btnNextPage', page).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page); - }); - - $('.btnPreviousPage', page).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page); - }); - - LibraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - $(document).on('pagebeforeshow', "#gameGenresPage", function () { - - query.ParentId = LibraryMenu.getTopParentId(); - - var limit = LibraryBrowser.getDefaultPageSize(); - - // If the default page size has changed, the start index will have to be reset - if (limit != query.Limit) { - query.Limit = limit; - query.StartIndex = 0; - } - - LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(), query); - - reloadItems(this); - }); - -}); \ No newline at end of file +define(["jQuery","imageLoader"],function($,imageLoader){"use strict";function getSavedQueryKey(){return LibraryBrowser.getSavedQueryKey()}function reloadItems(page){Dashboard.showLoadingMsg(),ApiClient.getGameGenres(Dashboard.getCurrentUserId(),query).then(function(result){window.scrollTo(0,0);var html="";$(".listTopPaging",page).html(LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1})),html=LibraryBrowser.getPosterViewHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"games",showItemCounts:!0,centerText:!0,lazy:!0});var elem=page.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem),$(".btnNextPage",page).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page)}),$(".btnPreviousPage",page).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page)}),LibraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}var query={SortBy:"SortName",SortOrder:"Ascending",Recursive:!0,Fields:"DateCreated,ItemCounts",StartIndex:0};$(document).on("pagebeforeshow","#gameGenresPage",function(){query.ParentId=LibraryMenu.getTopParentId();var limit=LibraryBrowser.getDefaultPageSize();limit!=query.Limit&&(query.Limit=limit,query.StartIndex=0),LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(),query),reloadItems(this)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/gamespage.js b/dashboard-ui/scripts/gamespage.js index b97e6cf510..f42b133c16 100644 --- a/dashboard-ui/scripts/gamespage.js +++ b/dashboard-ui/scripts/gamespage.js @@ -1,186 +1 @@ -define(['jQuery', 'listView', 'imageLoader'], function ($, listView, imageLoader) { - 'use strict'; - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - MediaTypes: "Game", - Recursive: true, - Fields: "Genres,Studios,PrimaryImageAspectRatio,SortName", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: LibraryBrowser.getDefaultPageSize() - }, - view: LibraryBrowser.getSavedView(key) || 'Poster' - }; - - pageData.query.ParentId = LibraryMenu.getTopParentId(); - LibraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = LibraryBrowser.getSavedQueryKey('games'); - } - return context.savedQueryKey; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - - $('.listTopPaging', page).html(LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - filterButton: true - })); - - var view = getPageData(page).view; - - if (view == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - context: 'games', - sortBy: query.SortBy - }); - } - else if (view == "Poster") { - html = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - shape: "auto", - context: 'games', - showTitle: true, - showParentTitle: true, - centerText: true - }); - } - else if (view == "PosterCard") { - html = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - shape: "auto", - context: 'games', - showTitle: true, - showParentTitle: true, - cardLayout: true - }); - } - - var elem = page.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - $('.btnNextPage', page).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page); - }); - - $('.btnPreviousPage', page).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page); - }); - - $('.btnFilter', page).on('click', function () { - showFilterMenu(page); - }); - - LibraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - function showFilterMenu(page) { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(page), - mode: 'games' - }); - - Events.on(filterDialog, 'filterchange', function () { - reloadItems(page); - }); - - filterDialog.show(); - }); - } - - $(document).on('pageinit', "#gamesPage", function () { - - var page = this; - - $('.alphabetPicker', this).on('alphaselect', function (e, character) { - - var query = getQuery(page); - query.NameStartsWithOrGreater = character; - query.StartIndex = 0; - - reloadItems(page); - - }).on('alphaclear', function (e) { - - var query = getQuery(page); - query.NameStartsWithOrGreater = ''; - - reloadItems(page); - }); - - }).on('pagebeforeshow', "#gamesPage", function () { - - var page = this; - var query = getQuery(page); - query.ParentId = LibraryMenu.getTopParentId(); - - var limit = LibraryBrowser.getDefaultPageSize(); - - // If the default page size has changed, the start index will have to be reset - if (limit != query.Limit) { - query.Limit = limit; - query.StartIndex = 0; - } - - var viewkey = getSavedQueryKey(page); - - LibraryBrowser.loadSavedQueryValues(viewkey, query); - - LibraryBrowser.getSavedViewSetting(viewkey).then(function (val) { - - if (val) { - $('#selectView', page).val(val).trigger('change'); - } else { - reloadItems(page); - } - }); - }); - -}); \ No newline at end of file +define(["jQuery","listView","imageLoader"],function($,listView,imageLoader){"use strict";function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",MediaTypes:"Game",Recursive:!0,Fields:"Genres,Studios,PrimaryImageAspectRatio,SortName",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:LibraryBrowser.getDefaultPageSize()},view:LibraryBrowser.getSavedView(key)||"Poster"},pageData.query.ParentId=LibraryMenu.getTopParentId(),LibraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=LibraryBrowser.getSavedQueryKey("games")),context.savedQueryKey}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){window.scrollTo(0,0);var html="";$(".listTopPaging",page).html(LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,filterButton:!0}));var view=getPageData(page).view;"List"==view?html=listView.getListViewHtml({items:result.Items,context:"games",sortBy:query.SortBy}):"Poster"==view?html=LibraryBrowser.getPosterViewHtml({items:result.Items,shape:"auto",context:"games",showTitle:!0,showParentTitle:!0,centerText:!0}):"PosterCard"==view&&(html=LibraryBrowser.getPosterViewHtml({items:result.Items,shape:"auto",context:"games",showTitle:!0,showParentTitle:!0,cardLayout:!0}));var elem=page.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem),$(".btnNextPage",page).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page)}),$(".btnPreviousPage",page).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page)}),$(".btnFilter",page).on("click",function(){showFilterMenu(page)}),LibraryBrowser.saveQueryValues(getSavedQueryKey(page),query),Dashboard.hideLoadingMsg()})}function showFilterMenu(page){require(["components/filterdialog/filterdialog"],function(filterDialogFactory){var filterDialog=new filterDialogFactory({query:getQuery(page),mode:"games"});Events.on(filterDialog,"filterchange",function(){reloadItems(page)}),filterDialog.show()})}var data={};$(document).on("pageinit","#gamesPage",function(){var page=this;$(".alphabetPicker",this).on("alphaselect",function(e,character){var query=getQuery(page);query.NameStartsWithOrGreater=character,query.StartIndex=0,reloadItems(page)}).on("alphaclear",function(e){var query=getQuery(page);query.NameStartsWithOrGreater="",reloadItems(page)})}).on("pagebeforeshow","#gamesPage",function(){var page=this,query=getQuery(page);query.ParentId=LibraryMenu.getTopParentId();var limit=LibraryBrowser.getDefaultPageSize();limit!=query.Limit&&(query.Limit=limit,query.StartIndex=0);var viewkey=getSavedQueryKey(page);LibraryBrowser.loadSavedQueryValues(viewkey,query),LibraryBrowser.getSavedViewSetting(viewkey).then(function(val){val?$("#selectView",page).val(val).trigger("change"):reloadItems(page)})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/gamesrecommendedpage.js b/dashboard-ui/scripts/gamesrecommendedpage.js index b2e6dd1370..2d89ab7ed9 100644 --- a/dashboard-ui/scripts/gamesrecommendedpage.js +++ b/dashboard-ui/scripts/gamesrecommendedpage.js @@ -1,72 +1 @@ -define(['jQuery', 'imageLoader'], function ($, imageLoader) { - 'use strict'; - - $(document).on('pagebeforeshow', "#gamesRecommendedPage", function () { - - var parentId = LibraryMenu.getTopParentId(); - var userId = Dashboard.getCurrentUserId(); - - var page = this; - - var options = { - - IncludeItemTypes: "Game", - Limit: 18, - Fields: "PrimaryImageAspectRatio", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb" - }; - - ApiClient.getJSON(ApiClient.getUrl('Users/' + userId + '/Items/Latest', options)).then(function (items) { - - var recentlyAddedItems = page.querySelector('#recentlyAddedItems'); - recentlyAddedItems.innerHTML = LibraryBrowser.getPosterViewHtml({ - items: items, - transparent: true, - borderless: true, - shape: 'auto', - lazy: true - - }); - imageLoader.lazyChildren(recentlyAddedItems); - - }); - - options = { - - SortBy: "DatePlayed", - SortOrder: "Descending", - MediaTypes: "Game", - Limit: 18, - Recursive: true, - Filters: "IsPlayed", - Fields: "ItemCounts,AudioInfo,PrimaryImageAspectRatio", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb" - }; - - ApiClient.getItems(userId, options).then(function (result) { - - if (result.Items.length) { - $('#recentlyPlayedSection', page).show(); - } else { - $('#recentlyPlayedSection', page).hide(); - } - - var recentlyPlayedItems = page.querySelector('#recentlyPlayedItems'); - recentlyPlayedItems.innerHTML = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - transparent: true, - borderless: true, - shape: 'auto', - lazy: true - - }); - imageLoader.lazyChildren(recentlyPlayedItems); - }); - - }); - -}); \ No newline at end of file +define(["jQuery","imageLoader"],function($,imageLoader){"use strict";$(document).on("pagebeforeshow","#gamesRecommendedPage",function(){var parentId=LibraryMenu.getTopParentId(),userId=Dashboard.getCurrentUserId(),page=this,options={IncludeItemTypes:"Game",Limit:18,Fields:"PrimaryImageAspectRatio",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb"};ApiClient.getJSON(ApiClient.getUrl("Users/"+userId+"/Items/Latest",options)).then(function(items){var recentlyAddedItems=page.querySelector("#recentlyAddedItems");recentlyAddedItems.innerHTML=LibraryBrowser.getPosterViewHtml({items:items,transparent:!0,borderless:!0,shape:"auto",lazy:!0}),imageLoader.lazyChildren(recentlyAddedItems)}),options={SortBy:"DatePlayed",SortOrder:"Descending",MediaTypes:"Game",Limit:18,Recursive:!0,Filters:"IsPlayed",Fields:"ItemCounts,AudioInfo,PrimaryImageAspectRatio",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb"},ApiClient.getItems(userId,options).then(function(result){result.Items.length?$("#recentlyPlayedSection",page).show():$("#recentlyPlayedSection",page).hide();var recentlyPlayedItems=page.querySelector("#recentlyPlayedItems");recentlyPlayedItems.innerHTML=LibraryBrowser.getPosterViewHtml({items:result.Items,transparent:!0,borderless:!0,shape:"auto",lazy:!0}),imageLoader.lazyChildren(recentlyPlayedItems)})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/gamestudiospage.js b/dashboard-ui/scripts/gamestudiospage.js index a4548fa81f..faec9b4215 100644 --- a/dashboard-ui/scripts/gamestudiospage.js +++ b/dashboard-ui/scripts/gamestudiospage.js @@ -1,85 +1 @@ -define(['jQuery', 'imageLoader'], function ($, imageLoader) { - 'use strict'; - - // The base query options - var query = { - - SortBy: "SortName", - SortOrder: "Ascending", - MediaTypes: "Game", - Recursive: true, - Fields: "ItemCounts", - StartIndex: 0 - }; - - function getSavedQueryKey() { - - return LibraryBrowser.getSavedQueryKey(); - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getStudios(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - - $('.listTopPaging', page).html(LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false - })); - - html = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'games', - showItemCounts: true, - centerText: true, - lazy: true - }); - - var elem = page.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - $('.btnNextPage', page).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page); - }); - - $('.btnPreviousPage', page).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page); - }); - - LibraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - $(document).on('pagebeforeshow', "#gameStudiosPage", function () { - - query.ParentId = LibraryMenu.getTopParentId(); - - var limit = LibraryBrowser.getDefaultPageSize(); - - // If the default page size has changed, the start index will have to be reset - if (limit != query.Limit) { - query.Limit = limit; - query.StartIndex = 0; - } - - LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(), query); - - reloadItems(this); - }); - -}); \ No newline at end of file +define(["jQuery","imageLoader"],function($,imageLoader){"use strict";function getSavedQueryKey(){return LibraryBrowser.getSavedQueryKey()}function reloadItems(page){Dashboard.showLoadingMsg(),ApiClient.getStudios(Dashboard.getCurrentUserId(),query).then(function(result){window.scrollTo(0,0);var html="";$(".listTopPaging",page).html(LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1})),html=LibraryBrowser.getPosterViewHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"games",showItemCounts:!0,centerText:!0,lazy:!0});var elem=page.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem),$(".btnNextPage",page).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page)}),$(".btnPreviousPage",page).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page)}),LibraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}var query={SortBy:"SortName",SortOrder:"Ascending",MediaTypes:"Game",Recursive:!0,Fields:"ItemCounts",StartIndex:0};$(document).on("pagebeforeshow","#gameStudiosPage",function(){query.ParentId=LibraryMenu.getTopParentId();var limit=LibraryBrowser.getDefaultPageSize();limit!=query.Limit&&(query.Limit=limit,query.StartIndex=0),LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(),query),reloadItems(this)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/gamesystemspage.js b/dashboard-ui/scripts/gamesystemspage.js index b581eeb5f1..34babe5735 100644 --- a/dashboard-ui/scripts/gamesystemspage.js +++ b/dashboard-ui/scripts/gamesystemspage.js @@ -1,77 +1 @@ -define(['jQuery', 'imageLoader'], function ($, imageLoader) { - 'use strict'; - - // The base query options - var query = { - - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "GameSystem", - Recursive: true, - Fields: "DateCreated", - StartIndex: 0, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb" - }; - - function getSavedQueryKey() { - - return LibraryBrowser.getSavedQueryKey(); - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - updateFilterControls(page); - - var html = LibraryBrowser.getPosterViewHtml({ - items: result.Items, - shape: "backdrop", - context: 'games', - showTitle: true, - centerText: true, - lazy: true - - }); - - var elem = page.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - LibraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - function updateFilterControls(page) { - - // Reset form values using the last used query - } - - $(document).on('pagebeforeshow', "#gamesystemsPage", function () { - - query.ParentId = LibraryMenu.getTopParentId(); - - var limit = LibraryBrowser.getDefaultPageSize(); - - // If the default page size has changed, the start index will have to be reset - if (limit != query.Limit) { - query.Limit = limit; - query.StartIndex = 0; - } - - LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(), query); - - reloadItems(this); - - updateFilterControls(this); - }); - -}); +define(["jQuery","imageLoader"],function($,imageLoader){"use strict";function getSavedQueryKey(){return LibraryBrowser.getSavedQueryKey()}function reloadItems(page){Dashboard.showLoadingMsg(),ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){window.scrollTo(0,0),updateFilterControls(page);var html=LibraryBrowser.getPosterViewHtml({items:result.Items,shape:"backdrop",context:"games",showTitle:!0,centerText:!0,lazy:!0}),elem=page.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem),LibraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}function updateFilterControls(page){}var query={SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"GameSystem",Recursive:!0,Fields:"DateCreated",StartIndex:0,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb"};$(document).on("pagebeforeshow","#gamesystemsPage",function(){query.ParentId=LibraryMenu.getTopParentId();var limit=LibraryBrowser.getDefaultPageSize();limit!=query.Limit&&(query.Limit=limit,query.StartIndex=0),LibraryBrowser.loadSavedQueryValues(getSavedQueryKey(),query),reloadItems(this),updateFilterControls(this)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/homefavorites.js b/dashboard-ui/scripts/homefavorites.js index 499c1206d5..2c543785f2 100644 --- a/dashboard-ui/scripts/homefavorites.js +++ b/dashboard-ui/scripts/homefavorites.js @@ -1,15 +1 @@ -define(['components/favoriteitems'], function (favoriteItems) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - - self.renderTab = function () { - - var parentId = null; - favoriteItems.render(tabContent, Dashboard.getCurrentUserId(), parentId); - }; - }; - -}); \ No newline at end of file +define(["components/favoriteitems"],function(favoriteItems){"use strict";return function(view,params,tabContent){var self=this;self.renderTab=function(){var parentId=null;favoriteItems.render(tabContent,Dashboard.getCurrentUserId(),parentId)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/homenextup.js b/dashboard-ui/scripts/homenextup.js index cc27ea01b2..28c26a1fc5 100644 --- a/dashboard-ui/scripts/homenextup.js +++ b/dashboard-ui/scripts/homenextup.js @@ -1,71 +1 @@ -define(['components/categorysyncbuttons', 'cardBuilder', 'apphost', 'imageLoader', 'emby-itemscontainer'], function (categorysyncbuttons, cardBuilder, appHost, imageLoader) { - 'use strict'; - - function getNextUpPromise() { - - var query = { - - Limit: 24, - Fields: "PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo", - UserId: Dashboard.getCurrentUserId(), - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb" - }; - - return ApiClient.getNextUpEpisodes(query); - } - function loadNextUp(page, promise) { - - promise.then(function (result) { - - if (result.Items.length) { - page.querySelector('.noNextUpItems').classList.add('hide'); - } else { - page.querySelector('.noNextUpItems').classList.remove('hide'); - } - - var html = ''; - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - showTitle: true, - showParentTitle: true, - overlayText: false, - lazy: true, - preferThumb: true, - showDetailsMenu: true, - centerText: !supportsImageAnalysis, - overlayPlayButton: true, - context: 'home-nextup', - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - }); - - var elem = page.querySelector('#nextUpItems'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - Dashboard.hideLoadingMsg(); - }); - } - return function (view, params, tabContent) { - - var self = this; - var nextUpPromise; - - categorysyncbuttons.init(view); - - self.preRender = function () { - nextUpPromise = getNextUpPromise(); - }; - - self.renderTab = function () { - - Dashboard.showLoadingMsg(); - loadNextUp(view, nextUpPromise); - }; - }; - -}); \ No newline at end of file +define(["components/categorysyncbuttons","cardBuilder","apphost","imageLoader","emby-itemscontainer"],function(categorysyncbuttons,cardBuilder,appHost,imageLoader){"use strict";function getNextUpPromise(){var query={Limit:24,Fields:"PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo",UserId:Dashboard.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb"};return ApiClient.getNextUpEpisodes(query)}function loadNextUp(page,promise){promise.then(function(result){result.Items.length?page.querySelector(".noNextUpItems").classList.add("hide"):page.querySelector(".noNextUpItems").classList.remove("hide");var html="",supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,showParentTitle:!0,overlayText:!1,lazy:!0,preferThumb:!0,showDetailsMenu:!0,centerText:!supportsImageAnalysis,overlayPlayButton:!0,context:"home-nextup",cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis});var elem=page.querySelector("#nextUpItems");elem.innerHTML=html,imageLoader.lazyChildren(elem),Dashboard.hideLoadingMsg()})}return function(view,params,tabContent){var nextUpPromise,self=this;categorysyncbuttons.init(view),self.preRender=function(){nextUpPromise=getNextUpPromise()},self.renderTab=function(){Dashboard.showLoadingMsg(),loadNextUp(view,nextUpPromise)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/homeupcoming.js b/dashboard-ui/scripts/homeupcoming.js index f5084c03e2..7f2eb69b37 100644 --- a/dashboard-ui/scripts/homeupcoming.js +++ b/dashboard-ui/scripts/homeupcoming.js @@ -1,155 +1 @@ -define(['datetime', 'cardBuilder', 'apphost', 'imageLoader', 'emby-itemscontainer', 'scrollStyles'], function (datetime, cardBuilder, appHost, imageLoader) { - 'use strict'; - - function getUpcomingPromise() { - - Dashboard.showLoadingMsg(); - - var query = { - - Limit: 40, - Fields: "AirTime,UserData", - UserId: Dashboard.getCurrentUserId(), - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - return ApiClient.getJSON(ApiClient.getUrl("Shows/Upcoming", query)); - } - - function loadUpcoming(page, promise) { - - promise.then(function (result) { - - var items = result.Items; - - if (items.length) { - page.querySelector('.noItemsMessage').style.display = 'none'; - } else { - page.querySelector('.noItemsMessage').style.display = 'block'; - } - - var elem = page.querySelector('#upcomingItems'); - renderUpcoming(elem, items); - - Dashboard.hideLoadingMsg(); - }); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function getThumbShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function renderUpcoming(elem, items) { - - var groups = []; - - var currentGroupName = ''; - var currentGroup = []; - - var i, length; - - for (i = 0, length = items.length; i < length; i++) { - - var item = items[i]; - - var dateText = ''; - - if (item.PremiereDate) { - try { - - var premiereDate = datetime.parseISO8601Date(item.PremiereDate, true); - - if (datetime.isRelativeDay(premiereDate, -1)) { - dateText = Globalize.translate('Yesterday'); - } else { - dateText = LibraryBrowser.getFutureDateText(premiereDate, true); - } - - } catch (err) { - } - } - - if (dateText != currentGroupName) { - - if (currentGroup.length) { - groups.push({ - name: currentGroupName, - items: currentGroup - }); - } - - currentGroupName = dateText; - currentGroup = [item]; - } else { - currentGroup.push(item); - } - } - - var html = ''; - - for (i = 0, length = groups.length; i < length; i++) { - - var group = groups[i]; - - html += '
'; - html += '

' + group.name + '

'; - - var allowBottomPadding = true; - - if (enableScrollX()) { - allowBottomPadding = false; - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: group.items, - showLocationTypeIndicator: false, - shape: getThumbShape(), - showTitle: true, - preferThumb: true, - lazy: true, - showDetailsMenu: true, - centerText: !supportsImageAnalysis, - context: 'home-upcoming', - overlayMoreButton: !supportsImageAnalysis, - showParentTitle: true, - allowBottomPadding: allowBottomPadding, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - html += '
'; - - html += '
'; - } - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - } - return function (view, params, tabContent) { - - var self = this; - var upcomingPromise; - - self.preRender = function () { - upcomingPromise = getUpcomingPromise(); - }; - - self.renderTab = function () { - - Dashboard.showLoadingMsg(); - loadUpcoming(view, upcomingPromise); - }; - }; - -}); \ No newline at end of file +define(["datetime","cardBuilder","apphost","imageLoader","emby-itemscontainer","scrollStyles"],function(datetime,cardBuilder,appHost,imageLoader){"use strict";function getUpcomingPromise(){Dashboard.showLoadingMsg();var query={Limit:40,Fields:"AirTime,UserData",UserId:Dashboard.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};return ApiClient.getJSON(ApiClient.getUrl("Shows/Upcoming",query))}function loadUpcoming(page,promise){promise.then(function(result){var items=result.Items;items.length?page.querySelector(".noItemsMessage").style.display="none":page.querySelector(".noItemsMessage").style.display="block";var elem=page.querySelector("#upcomingItems");renderUpcoming(elem,items),Dashboard.hideLoadingMsg()})}function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function renderUpcoming(elem,items){var i,length,groups=[],currentGroupName="",currentGroup=[];for(i=0,length=items.length;i',html+='

'+group.name+"

";var allowBottomPadding=!0;enableScrollX()?(allowBottomPadding=!1,html+='
'):html+='
';var supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:group.items,showLocationTypeIndicator:!1,shape:getThumbShape(),showTitle:!0,preferThumb:!0,lazy:!0,showDetailsMenu:!0,centerText:!supportsImageAnalysis,context:"home-upcoming",overlayMoreButton:!supportsImageAnalysis,showParentTitle:!0,allowBottomPadding:allowBottomPadding,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
",html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)}return function(view,params,tabContent){var upcomingPromise,self=this;self.preRender=function(){upcomingPromise=getUpcomingPromise()},self.renderTab=function(){Dashboard.showLoadingMsg(),loadUpcoming(view,upcomingPromise)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/indexpage.js b/dashboard-ui/scripts/indexpage.js index 2be50971d8..62cf4c6e27 100644 --- a/dashboard-ui/scripts/indexpage.js +++ b/dashboard-ui/scripts/indexpage.js @@ -1,368 +1 @@ -define(['libraryBrowser', 'playbackManager', 'emby-tabs', 'emby-button'], function (libraryBrowser, playbackManager) { - 'use strict'; - - var defaultFirstSection = 'smalllibrarytiles'; - - function getDefaultSection(index) { - - switch (index) { - - case 0: - return defaultFirstSection; - case 1: - return 'resume'; - case 2: - return 'nextup'; - case 3: - return 'latestmedia'; - case 4: - return 'latesttvrecordings'; - default: - return ''; - } - } - - function loadSection(page, user, userSettings, index) { - - var userId = user.Id; - - var section = userSettings.get('homesection' + index) || getDefaultSection(index); - - if (section == 'folders') { - section = defaultFirstSection; - } - - var elem = page.querySelector('.section' + index); - - if (section == 'latestmedia') { - return Sections.loadRecentlyAdded(elem, user); - } - else if (section == 'librarytiles') { - return Sections.loadLibraryTiles(elem, user, 'backdrop', index); - } - else if (section == 'smalllibrarytiles') { - return Sections.loadLibraryTiles(elem, user, 'smallBackdrop', index); - } - else if (section == 'smalllibrarytiles-automobile') { - return Sections.loadLibraryTiles(elem, user, 'smallBackdrop', index); - } - else if (section == 'librarytiles-automobile') { - return Sections.loadLibraryTiles(elem, user, 'backdrop', index); - } - else if (section == 'librarybuttons') { - return Sections.loadlibraryButtons(elem, userId, index); - } - else if (section == 'resume') { - return Sections.loadResume(elem, userId); - } - else if (section == 'nextup') { - return Sections.loadNextUp(elem, userId); - } - else if (section == 'latesttvrecordings') { - return Sections.loadLatestLiveTvRecordings(elem, userId); - } - else if (section == 'latestchannelmedia') { - return Sections.loadLatestChannelMedia(elem, userId); - - } else { - - elem.innerHTML = ''; - - return Promise.resolve(); - } - } - - function loadSections(page, user, userSettings) { - - var i, length; - var sectionCount = 5; - - var elem = page.querySelector('.sections'); - - //if (!elem.innerHTML.length) { - var html = ''; - for (i = 0, length = sectionCount; i < length; i++) { - - html += '
'; - } - - elem.innerHTML = html; - //} - - var promises = []; - - for (i = 0, length = sectionCount; i < length; i++) { - - promises.push(loadSection(page, user, userSettings, i)); - } - - return Promise.all(promises); - } - - var homePageDismissValue = '14'; - var homePageTourKey = 'homePageTour'; - - function displayPreferencesKey() { - if (AppInfo.isNativeApp) { - return 'Emby Mobile'; - } - - return 'webclient'; - } - - function dismissWelcome(page, userId) { - - getDisplayPreferences('home', userId).then(function (result) { - - result.CustomPrefs[homePageTourKey] = homePageDismissValue; - ApiClient.updateDisplayPreferences('home', result, userId, displayPreferencesKey()); - }); - } - - function showWelcomeIfNeeded(page, displayPreferences) { - - if (displayPreferences.CustomPrefs[homePageTourKey] == homePageDismissValue) { - page.querySelector('.welcomeMessage').classList.add('hide'); - } else { - - Dashboard.hideLoadingMsg(); - - var elem = page.querySelector('.welcomeMessage'); - elem.classList.remove('hide'); - - if (displayPreferences.CustomPrefs[homePageTourKey]) { - - elem.querySelector('.tourHeader').innerHTML = Globalize.translate('HeaderWelcomeBack'); - elem.querySelector('.tourButtonText').innerHTML = Globalize.translate('ButtonTakeTheTourToSeeWhatsNew'); - - } else { - - elem.querySelector('.tourHeader').innerHTML = Globalize.translate('HeaderWelcomeToProjectWebClient'); - elem.querySelector('.tourButtonText').innerHTML = Globalize.translate('ButtonTakeTheTour'); - } - } - } - - function takeTour(page, userId) { - - require(['slideshow'], function () { - - var slides = [ - { imageUrl: 'css/images/tour/web/tourcontent.jpg', title: Globalize.translate('WebClientTourContent') }, - { imageUrl: 'css/images/tour/web/tourmovies.jpg', title: Globalize.translate('WebClientTourMovies') }, - { imageUrl: 'css/images/tour/web/tourmouseover.jpg', title: Globalize.translate('WebClientTourMouseOver') }, - { imageUrl: 'css/images/tour/web/tourtaphold.jpg', title: Globalize.translate('WebClientTourTapHold') }, - { imageUrl: 'css/images/tour/web/tourmysync.png', title: Globalize.translate('WebClientTourMySync') }, - { imageUrl: 'css/images/tour/web/toureditor.png', title: Globalize.translate('WebClientTourMetadataManager') }, - { imageUrl: 'css/images/tour/web/tourplaylist.png', title: Globalize.translate('WebClientTourPlaylists') }, - { imageUrl: 'css/images/tour/web/tourcollections.jpg', title: Globalize.translate('WebClientTourCollections') }, - { imageUrl: 'css/images/tour/web/tourusersettings1.png', title: Globalize.translate('WebClientTourUserPreferences1') }, - { imageUrl: 'css/images/tour/web/tourusersettings2.png', title: Globalize.translate('WebClientTourUserPreferences2') }, - { imageUrl: 'css/images/tour/web/tourusersettings3.png', title: Globalize.translate('WebClientTourUserPreferences3') }, - { imageUrl: 'css/images/tour/web/tourusersettings4.png', title: Globalize.translate('WebClientTourUserPreferences4') }, - { imageUrl: 'css/images/tour/web/tourmobile1.jpg', title: Globalize.translate('WebClientTourMobile1') }, - { imageUrl: 'css/images/tour/web/tourmobile2.png', title: Globalize.translate('WebClientTourMobile2') }, - { imageUrl: 'css/images/tour/enjoy.jpg', title: Globalize.translate('MessageEnjoyYourStay') } - ]; - - require(['slideshow'], function (slideshow) { - - var newSlideShow = new slideshow({ - slides: slides, - interactive: true, - loop: false - }); - - newSlideShow.show(); - - dismissWelcome(page, userId); - page.querySelector('.welcomeMessage').classList.add('hide'); - }); - }); - } - - function getRequirePromise(deps) { - - return new Promise(function (resolve, reject) { - - require(deps, resolve); - }); - } - - function loadHomeTab(page, tabContent) { - - if (window.ApiClient) { - var userId = Dashboard.getCurrentUserId(); - Dashboard.showLoadingMsg(); - - var promises = [ - getDisplayPreferences('home', userId), - Dashboard.getCurrentUser(), - getRequirePromise(['userSettings']) - ]; - - Promise.all(promises).then(function(responses) { - var displayPreferences = responses[0]; - var user = responses[1]; - var userSettings = responses[2]; - - loadSections(tabContent, user, userSettings).then(function () { - - if (!AppInfo.isNativeApp) { - showWelcomeIfNeeded(page, displayPreferences); - } - Dashboard.hideLoadingMsg(); - }); - }); - } - } - - function getDisplayPreferences(key, userId) { - - return ApiClient.getDisplayPreferences(key, userId, displayPreferencesKey()); - } - - return function (view, params) { - - var self = this; - - self.renderTab = function () { - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - loadHomeTab(view, tabContent); - }; - - var viewTabs = view.querySelector('.libraryViewNav'); - - libraryBrowser.configurePaperLibraryTabs(view, viewTabs, view.querySelectorAll('.pageTabContent'), [0, 1, 2, 3], AppInfo.enableHomeTabs); - - var tabControllers = []; - var renderedTabs = []; - - function getTabController(page, index, callback) { - - var depends = []; - - switch (index) { - - case 0: - depends.push('scripts/sections'); - break; - case 1: - depends.push('scripts/homenextup'); - break; - case 2: - depends.push('scripts/homefavorites'); - break; - case 3: - depends.push('scripts/homeupcoming'); - break; - default: - return; - } - - require(depends, function (controllerFactory) { - var tabContent; - if (index == 0) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - self.tabContent = tabContent; - } - var controller = tabControllers[index]; - if (!controller) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - controller = index ? new controllerFactory(view, params, tabContent) : self; - tabControllers[index] = controller; - - if (controller.initTab) { - controller.initTab(); - } - } - - callback(controller); - }); - } - - function preLoadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - if (controller.preRender) { - controller.preRender(); - } - } - }); - } - - function loadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - renderedTabs.push(index); - controller.renderTab(); - } - }); - } - - viewTabs.addEventListener('beforetabchange', function (e) { - preLoadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - viewTabs.addEventListener('tabchange', function (e) { - loadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - view.querySelector('.btnTakeTour').addEventListener('click', function () { - takeTour(view, Dashboard.getCurrentUserId()); - }); - - if (AppInfo.enableHomeTabs) { - view.classList.remove('noSecondaryNavPage'); - view.querySelector('.libraryViewNav').classList.remove('hide'); - } else { - view.classList.add('noSecondaryNavPage'); - view.querySelector('.libraryViewNav').classList.add('hide'); - } - - function onPlaybackStop(e, state) { - - if (state.NowPlayingItem && state.NowPlayingItem.MediaType == 'Video') { - - viewTabs.triggerTabChange(); - } - } - - function onWebSocketMessage(e, data) { - - var msg = data; - - if (msg.MessageType === "UserDataChanged") { - - if (msg.Data.UserId == Dashboard.getCurrentUserId()) { - - renderedTabs = []; - } - } - - } - - view.addEventListener('viewshow', function (e) { - Events.on(playbackManager, 'playbackstop', onPlaybackStop); - Events.on(ApiClient, "websocketmessage", onWebSocketMessage); - }); - - view.addEventListener('viewbeforehide', function (e) { - Events.off(playbackManager, 'playbackstop', onPlaybackStop); - Events.off(ApiClient, "websocketmessage", onWebSocketMessage); - }); - - require(["headroom-window"], function (headroom) { - headroom.add(viewTabs); - self.headroom = headroom; - }); - - view.addEventListener('viewdestroy', function (e) { - if (self.headroom) { - self.headroom.remove(viewTabs); - } - }); - }; -}); \ No newline at end of file +define(["libraryBrowser","playbackManager","emby-tabs","emby-button"],function(libraryBrowser,playbackManager){"use strict";function getDefaultSection(index){switch(index){case 0:return defaultFirstSection;case 1:return"resume";case 2:return"nextup";case 3:return"latestmedia";case 4:return"latesttvrecordings";default:return""}}function loadSection(page,user,userSettings,index){var userId=user.Id,section=userSettings.get("homesection"+index)||getDefaultSection(index);"folders"==section&&(section=defaultFirstSection);var elem=page.querySelector(".section"+index);return"latestmedia"==section?Sections.loadRecentlyAdded(elem,user):"librarytiles"==section?Sections.loadLibraryTiles(elem,user,"backdrop",index):"smalllibrarytiles"==section?Sections.loadLibraryTiles(elem,user,"smallBackdrop",index):"smalllibrarytiles-automobile"==section?Sections.loadLibraryTiles(elem,user,"smallBackdrop",index):"librarytiles-automobile"==section?Sections.loadLibraryTiles(elem,user,"backdrop",index):"librarybuttons"==section?Sections.loadlibraryButtons(elem,userId,index):"resume"==section?Sections.loadResume(elem,userId):"nextup"==section?Sections.loadNextUp(elem,userId):"latesttvrecordings"==section?Sections.loadLatestLiveTvRecordings(elem,userId):"latestchannelmedia"==section?Sections.loadLatestChannelMedia(elem,userId):(elem.innerHTML="",Promise.resolve())}function loadSections(page,user,userSettings){var i,length,sectionCount=5,elem=page.querySelector(".sections"),html="";for(i=0,length=sectionCount;i
';elem.innerHTML=html;var promises=[];for(i=0,length=sectionCount;i'; - - html += '
'; - html += '

'; - html += section.name; - html += '

'; - html += ''; - html += '
'; - - html += '
'; - html += '
'; - - html += '
'; - - return html; - - }).join(''); - - var sectionElems = elem.querySelectorAll('.homePageSection'); - for (var i = 0, length = sectionElems.length; i < length; i++) { - renderSection(page, item, sectionElems[i], sectionElems[i].getAttribute('data-type')); - } - } - - function renderSection(page, item, element, type) { - - switch (type) { - - case 'Program': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Program", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "backdrop", - showTitle: true, - centerText: true, - overlayMoreButton: true, - preferThumb: true, - overlayText: false, - showAirTime: true, - showAirDateTime: true, - showChannelName: true - }); - break; - - case 'Movie': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Movie", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "portrait", - showTitle: true, - centerText: true, - overlayMoreButton: true, - overlayText: false - }); - break; - - case 'MusicVideo': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "MusicVideo", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "portrait", - showTitle: true, - centerText: true, - overlayPlayButton: true - }); - break; - - case 'Game': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Game", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "portrait", - showTitle: true, - centerText: true, - overlayMoreButton: true - }); - break; - - case 'Trailer': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Trailer", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "portrait", - showTitle: true, - centerText: true, - overlayPlayButton: true - }); - break; - - case 'Series': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Series", - PersonTypes: "", - ArtistIds: "", - Limit: 10 - }, { - shape: "portrait", - showTitle: true, - centerText: true, - overlayMoreButton: true - }); - break; - - case 'MusicAlbum': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "MusicAlbum", - PersonTypes: "", - ArtistIds: "", - Limit: 8 - }, { - shape: "square", - playFromHere: true, - showTitle: true, - showParentTitle: true, - coverImage: true, - centerText: true, - overlayPlayButton: true - }); - break; - - case 'MusicArtist': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "MusicArtist", - PersonTypes: "", - ArtistIds: "", - Limit: 8 - }, { - shape: "square", - playFromHere: true, - showTitle: true, - showParentTitle: true, - coverImage: true, - centerText: true, - overlayPlayButton: true - }); - break; - - case 'Episode': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Episode", - PersonTypes: "", - ArtistIds: "", - Limit: 6 - }, { - shape: "backdrop", - showTitle: true, - showParentTitle: true, - centerText: true, - overlayPlayButton: true - }); - break; - - case 'Audio': - loadItems(element, item, type, { - MediaTypes: "", - IncludeItemTypes: "Audio", - PersonTypes: "", - ArtistIds: "", - Limit: 40 - }, { - playFromHere: true, - action: 'playallfromhere', - smallIcon: true, - artist: true - }); - break; - - default: - break; - } - } - - function loadItems(element, item, type, query, listOptions) { - - query = getQuery(query, item); - - getItemsFunction(query, item)(query.StartIndex, query.Limit, query.Fields).then(function (result) { - - var html = ''; - - if (query.Limit && result.TotalRecordCount > query.Limit) { - // Add more button - var link = element.querySelector('a'); - link.classList.remove('hide'); - link.setAttribute('href', getMoreItemsHref(item, type)); - } else { - element.querySelector('a').classList.add('hide'); - } - - listOptions.items = result.Items; - var itemsContainer = element.querySelector('.itemsContainer'); - - if (type == 'Audio') { - html = listView.getListViewHtml(listOptions); - itemsContainer.classList.remove('vertical-wrap'); - itemsContainer.classList.add('vertical-list'); - } else { - html = cardBuilder.getCardsHtml(listOptions); - itemsContainer.classList.add('vertical-wrap'); - itemsContainer.classList.remove('vertical-list'); - } - - itemsContainer.innerHTML = html; - - imageLoader.lazyChildren(itemsContainer); - }); - } - - function getMoreItemsHref(item, type) { - - if (item.Type == 'Genre' || item.Type == 'MusicGenre' || item.Type == 'GameGenre') { - return 'secondaryitems.html?type=' + type + '&genreId=' + item.Id; - } - - if (item.Type == 'Studio') { - return 'secondaryitems.html?type=' + type + '&studioId=' + item.Id; - } - - if (item.Type == 'MusicArtist') { - return 'secondaryitems.html?type=' + type + '&artistId=' + item.Id; - } - - if (item.Type == 'Person') { - return 'secondaryitems.html?type=' + type + '&personId=' + item.Id; - } - - return 'secondaryitems.html?type=' + type + '&parentId=' + item.Id; - } - - function addCurrentItemToQuery(query, item) { - - if (item.Type == "Person") { - query.PersonIds = item.Id; - } - else if (item.Type == "Genre") { - query.Genres = item.Name; - } - else if (item.Type == "MusicGenre") { - query.Genres = item.Name; - } - else if (item.Type == "GameGenre") { - query.Genres = item.Name; - } - else if (item.Type == "Studio") { - query.StudioIds = item.Id; - } - else if (item.Type == "MusicArtist") { - query.ArtistIds = item.Id; - } - } - - function getQuery(options, item) { - - var query = { - - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "", - Recursive: true, - Fields: "AudioInfo,SeriesInfo,ParentId,PrimaryImageAspectRatio,BasicSyncInfo", - Limit: LibraryBrowser.getDefaultPageSize(), - StartIndex: 0, - CollapseBoxSetItems: false - }; - - query = Object.assign(query, options || {}); - - if (query.IncludeItemTypes == "Audio") { - query.SortBy = "AlbumArtist,Album,SortName"; - } - - addCurrentItemToQuery(query, item); - - return query; - } - - function getItemsFunction(options, item) { - - var query = getQuery(options, item); - - return function (index, limit, fields) { - - query.StartIndex = index; - query.Limit = limit; - - if (fields) { - query.Fields += "," + fields; - } - - return ApiClient.getItems(Dashboard.getCurrentUserId(), query); - - }; - - } - - window.ItemsByName = { - renderItems: renderItems - }; - -}); \ No newline at end of file +define(["listView","cardBuilder","imageLoader","emby-itemscontainer"],function(listView,cardBuilder,imageLoader){"use strict";function renderItems(page,item){var sections=[];item.ArtistCount&§ions.push({name:Globalize.translate("TabArtists"),type:"MusicArtist"}),item.ProgramCount&&"Person"==item.Type&§ions.push({name:Globalize.translate("HeaderUpcomingOnTV"),type:"Program"}),item.MovieCount&§ions.push({name:Globalize.translate("TabMovies"),type:"Movie"}),item.SeriesCount&§ions.push({name:Globalize.translate("TabSeries"),type:"Series"}),item.EpisodeCount&§ions.push({name:Globalize.translate("TabEpisodes"),type:"Episode"}),item.TrailerCount&§ions.push({name:Globalize.translate("TabTrailers"),type:"Trailer"}),item.GameCount&§ions.push({name:Globalize.translate("TabGames"),type:"Game"}),item.AlbumCount&§ions.push({name:Globalize.translate("TabAlbums"),type:"MusicAlbum"}),item.SongCount&§ions.push({name:Globalize.translate("TabSongs"),type:"Audio"}),item.MusicVideoCount&§ions.push({name:Globalize.translate("TabMusicVideos"),type:"MusicVideo"});var elem=page.querySelector("#childrenContent");elem.innerHTML=sections.map(function(section){var html="";return html+='
',html+="
",html+='

',html+=section.name,html+="

",html+='",html+="
",html+='
',html+="
",html+="
"}).join("");for(var sectionElems=elem.querySelectorAll(".homePageSection"),i=0,length=sectionElems.length;iquery.Limit){var link=element.querySelector("a");link.classList.remove("hide"),link.setAttribute("href",getMoreItemsHref(item,type))}else element.querySelector("a").classList.add("hide");listOptions.items=result.Items;var itemsContainer=element.querySelector(".itemsContainer");"Audio"==type?(html=listView.getListViewHtml(listOptions),itemsContainer.classList.remove("vertical-wrap"),itemsContainer.classList.add("vertical-list")):(html=cardBuilder.getCardsHtml(listOptions),itemsContainer.classList.add("vertical-wrap"),itemsContainer.classList.remove("vertical-list")),itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer)})}function getMoreItemsHref(item,type){return"Genre"==item.Type||"MusicGenre"==item.Type||"GameGenre"==item.Type?"secondaryitems.html?type="+type+"&genreId="+item.Id:"Studio"==item.Type?"secondaryitems.html?type="+type+"&studioId="+item.Id:"MusicArtist"==item.Type?"secondaryitems.html?type="+type+"&artistId="+item.Id:"Person"==item.Type?"secondaryitems.html?type="+type+"&personId="+item.Id:"secondaryitems.html?type="+type+"&parentId="+item.Id}function addCurrentItemToQuery(query,item){"Person"==item.Type?query.PersonIds=item.Id:"Genre"==item.Type?query.Genres=item.Name:"MusicGenre"==item.Type?query.Genres=item.Name:"GameGenre"==item.Type?query.Genres=item.Name:"Studio"==item.Type?query.StudioIds=item.Id:"MusicArtist"==item.Type&&(query.ArtistIds=item.Id)}function getQuery(options,item){var query={SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"",Recursive:!0,Fields:"AudioInfo,SeriesInfo,ParentId,PrimaryImageAspectRatio,BasicSyncInfo",Limit:LibraryBrowser.getDefaultPageSize(),StartIndex:0,CollapseBoxSetItems:!1};return query=Object.assign(query,options||{}),"Audio"==query.IncludeItemTypes&&(query.SortBy="AlbumArtist,Album,SortName"),addCurrentItemToQuery(query,item),query}function getItemsFunction(options,item){var query=getQuery(options,item);return function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,fields&&(query.Fields+=","+fields),ApiClient.getItems(Dashboard.getCurrentUserId(),query)}}window.ItemsByName={renderItems:renderItems}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/itemdetailpage.js b/dashboard-ui/scripts/itemdetailpage.js index c5d0494021..931440a29e 100644 --- a/dashboard-ui/scripts/itemdetailpage.js +++ b/dashboard-ui/scripts/itemdetailpage.js @@ -1,2465 +1,2 @@ -define(['layoutManager', 'cardBuilder', 'datetime', 'mediaInfo', 'backdrop', 'listView', 'itemContextMenu', 'itemHelper', 'userdataButtons', 'dom', 'indicators', 'apphost', 'imageLoader', 'libraryMenu', 'globalize', 'browser', 'events', 'scrollHelper', 'playbackManager', 'scrollStyles', 'emby-itemscontainer', 'emby-checkbox'], function (layoutManager, cardBuilder, datetime, mediaInfo, backdrop, listView, itemContextMenu, itemHelper, userdataButtons, dom, indicators, appHost, imageLoader, libraryMenu, globalize, browser, events, scrollHelper, playbackManager) { - 'use strict'; - - function getPromise(params) { - - var id = params.id; - - if (id) { - return ApiClient.getItem(Dashboard.getCurrentUserId(), id); - } - - if (params.seriesTimerId) { - return ApiClient.getLiveTvSeriesTimer(params.seriesTimerId); - } - - var name = params.genre; - - if (name) { - return ApiClient.getGenre(name, Dashboard.getCurrentUserId()); - } - - name = params.musicgenre; - - if (name) { - return ApiClient.getMusicGenre(name, Dashboard.getCurrentUserId()); - } - - name = params.gamegenre; - - if (name) { - return ApiClient.getGameGenre(name, Dashboard.getCurrentUserId()); - } - - name = params.musicartist; - - if (name) { - return ApiClient.getArtist(name, Dashboard.getCurrentUserId()); - } - else { - throw new Error('Invalid request'); - } - } - - var currentItem; - var currentRecordingFields; - - function reload(page, params) { - - Dashboard.showLoadingMsg(); - - getPromise(params).then(function (item) { - - reloadFromItem(page, params, item); - }); - } - - function hideAll(page, className, show) { - - var i, length; - var elems = page.querySelectorAll('.' + className); - for (i = 0, length = elems.length; i < length; i++) { - if (show) { - elems[i].classList.remove('hide'); - } else { - elems[i].classList.add('hide'); - } - } - } - - function getContextMenuOptions(item, button) { - - var options = { - item: item, - open: false, - play: false, - playAllFromHere: false, - queueAllFromHere: false, - positionTo: button, - cancelTimer: false, - record: false, - deleteItem: item.IsFolder === true, - shuffle: false, - instantMix: false - }; - - if (appHost.supports('sync')) { - // Will be displayed via button - options.syncLocal = false; - } - - return options; - } - - function renderSyncLocalContainer(page, params, user, item) { - - if (page.syncToggleInstance) { - page.syncToggleInstance.refresh(item); - return; - } - - require(['syncToggle'], function (syncToggle) { - - page.syncToggleInstance = new syncToggle({ - user: user, - item: item, - container: page.querySelector('.syncLocalContainer') - }); - - events.on(page.syncToggleInstance, 'sync', function () { - reload(page, params); - }); - }); - } - - function getProgramScheduleHtml(items, options) { - - options = options || {}; - - var html = ''; - html += '
'; - html += listView.getListViewHtml({ - items: items, - enableUserDataButtons: false, - image: false, - showProgramDateTime: true, - mediaInfo: false, - action: 'none', - moreButton: false, - recordButton: false - }); - - html += '
'; - - return html; - } - - function renderSeriesTimerSchedule(page, seriesTimerId) { - - ApiClient.getLiveTvTimers({ - UserId: ApiClient.getCurrentUserId(), - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb", - SortBy: "StartDate", - EnableTotalRecordCount: false, - EnableUserData: false, - SeriesTimerId: seriesTimerId, - Fields: "ChannelInfo" - - }).then(function (result) { - - if (result.Items.length && result.Items[0].SeriesTimerId != seriesTimerId) { - result.Items = []; - } - - var html = getProgramScheduleHtml(result.Items); - - var scheduleTab = page.querySelector('.seriesTimerSchedule'); - scheduleTab.innerHTML = html; - - imageLoader.lazyChildren(scheduleTab); - }); - } - - function renderSeriesTimerEditor(page, item, user) { - - if (item.Type !== 'SeriesTimer') { - return; - } - - if (!user.Policy.EnableLiveTvManagement) { - page.querySelector('.seriesTimerScheduleSection').classList.add('hide'); - page.querySelector('.btnCancelSeriesTimer').classList.add('hide'); - return; - } - - require(['seriesRecordingEditor'], function (seriesRecordingEditor) { - seriesRecordingEditor.embed(item, ApiClient.serverId(), { - context: page.querySelector('.seriesRecordingEditor') - }); - }); - - page.querySelector('.seriesTimerScheduleSection').classList.remove('hide'); - page.querySelector('.btnCancelSeriesTimer').classList.remove('hide'); - - renderSeriesTimerSchedule(page, item.Id); - } - - function reloadFromItem(page, params, item) { - - currentItem = item; - - var context = params.context; - - LibraryBrowser.renderName(item, page.querySelector('.itemName'), false, context); - LibraryBrowser.renderParentName(item, page.querySelector('.parentName'), context); - libraryMenu.setTitle(''); - - Dashboard.getCurrentUser().then(function (user) { - - window.scrollTo(0, 0); - - renderSeriesTimerEditor(page, item, user); - - renderImage(page, item, user); - renderLogo(page, item, ApiClient); - - setInitialCollapsibleState(page, item, context, user); - renderDetails(page, item, context); - - if (dom.getWindowSize().innerWidth >= 800) { - backdrop.setBackdrops([item]); - } else { - backdrop.clear(); - } - - LibraryBrowser.renderDetailPageBackdrop(page, item, imageLoader); - - libraryMenu.setTransparentMenu(true); - - var canPlay = false; - - if (item.Type == 'Program') { - - var now = new Date(); - - if (now >= datetime.parseISO8601Date(item.StartDate, true) && now < datetime.parseISO8601Date(item.EndDate, true)) { - hideAll(page, 'btnPlay', true); - canPlay = true; - } else { - hideAll(page, 'btnPlay'); - } - hideAll(page, 'btnResume'); - hideAll(page, 'btnInstantMix'); - hideAll(page, 'btnShuffle'); - } - else if (playbackManager.canPlay(item)) { - hideAll(page, 'btnPlay', true); - - var enableInstantMix = ['Audio', 'MusicAlbum', 'MusicGenre', 'MusicArtist'].indexOf(item.Type) !== -1; - hideAll(page, 'btnInstantMix', enableInstantMix); - - var enableShuffle = item.IsFolder || ['MusicAlbum', 'MusicGenre', 'MusicArtist'].indexOf(item.Type) !== -1; - hideAll(page, 'btnShuffle', enableShuffle); - - canPlay = true; - - hideAll(page, 'btnResume', item.UserData && item.UserData.PlaybackPositionTicks > 0); - } - else { - hideAll(page, 'btnPlay'); - hideAll(page, 'btnResume'); - hideAll(page, 'btnInstantMix'); - hideAll(page, 'btnShuffle'); - } - - var hasAnyButton = canPlay; - - if ((item.LocalTrailerCount || (item.RemoteTrailers && item.RemoteTrailers.length)) && item.PlayAccess == 'Full') { - hideAll(page, 'btnPlayTrailer', true); - hasAnyButton = true; - } else { - hideAll(page, 'btnPlayTrailer'); - } - - if (item.CanDelete && !item.IsFolder) { - hideAll(page, 'btnDeleteItem', true); - hasAnyButton = true; - } else { - hideAll(page, 'btnDeleteItem'); - } - - renderSyncLocalContainer(page, params, user, item); - - if (hasAnyButton || item.Type !== 'Program') { - hideAll(page, 'mainDetailButtons', true); - } else { - hideAll(page, 'mainDetailButtons'); - } - - showRecordingFields(page, item, user); - - var groupedVersions = (item.MediaSources || []).filter(function (g) { - return g.Type == "Grouping"; - }); - - if (user.Policy.IsAdministrator && groupedVersions.length) { - page.querySelector('.splitVersionContainer').classList.remove('hide'); - } else { - page.querySelector('.splitVersionContainer').classList.add('hide'); - } - - itemContextMenu.getCommands(getContextMenuOptions(item)).then(function (commands) { - if (commands.length) { - hideAll(page, 'btnMoreCommands', true); - } else { - hideAll(page, 'btnMoreCommands'); - } - }); - - var itemBirthday = page.querySelector('#itemBirthday'); - if (item.Type == "Person" && item.PremiereDate) { - - try { - var birthday = datetime.parseISO8601Date(item.PremiereDate, true).toDateString(); - - itemBirthday.classList.remove('hide'); - itemBirthday.innerHTML = globalize.translate('BirthDateValue').replace('{0}', birthday); - } - catch (err) { - itemBirthday.classList.add('hide'); - } - } else { - itemBirthday.classList.add('hide'); - } - - var itemDeathDate = page.querySelector('#itemDeathDate'); - if (item.Type == "Person" && item.EndDate) { - - try { - var deathday = datetime.parseISO8601Date(item.EndDate, true).toDateString(); - - itemDeathDate.classList.remove('hide'); - itemDeathDate.innerHTML = globalize.translate('DeathDateValue').replace('{0}', deathday); - } - catch (err) { - itemDeathDate.classList.add('hide'); - } - } else { - } - - var itemBirthLocation = page.querySelector('#itemBirthLocation'); - if (item.Type == "Person" && item.ProductionLocations && item.ProductionLocations.length) { - - var gmap = '' + item.ProductionLocations[0] + ''; - - itemBirthLocation.classList.remove('hide'); - itemBirthLocation.innerHTML = globalize.translate('BirthPlaceValue').replace('{0}', gmap); - } else { - itemBirthLocation.classList.add('hide'); - } - }); - - setPeopleHeader(page, item); - - page.dispatchEvent(new CustomEvent("displayingitem", { - detail: { - item: item, - context: context - }, - bubbles: true - })); - - Dashboard.hideLoadingMsg(); - } - - function logoImageUrl(item, apiClient, options) { - - options = options || {}; - options.type = "Logo"; - - if (item.ImageTags && item.ImageTags.Logo) { - - options.tag = item.ImageTags.Logo; - return apiClient.getScaledImageUrl(item.Id, options); - } - - if (item.ParentLogoImageTag) { - options.tag = item.ParentLogoImageTag; - return apiClient.getScaledImageUrl(item.ParentLogoItemId, options); - } - - return null; - } - - function bounceIn(elem) { - var keyframes = [ - { transform: 'scale3d(.3, .3, .3)', opacity: '0', offset: 0 }, - { transform: 'scale3d(1.1, 1.1, 1.1)', offset: 0.2 }, - { transform: 'scale3d(.9, .9, .9)', offset: 0.4 }, - { transform: 'scale3d(1.03, 1.03, 1.03)', opacity: '1', offset: 0.6 }, - { transform: 'scale3d(.97, .97, .97)', offset: 0.8 }, - { transform: 'scale3d(1, 1, 1)', opacity: '1', offset: 1 }]; - var timing = { duration: 900, iterations: 1, easing: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)' }; - return elem.animate(keyframes, timing); - } - - function renderLogo(page, item, apiClient) { - var url = logoImageUrl(item, apiClient, { - maxWidth: 300 - }); - - var detailLogo = page.querySelector('.detailLogo'); - - if (url) { - detailLogo.classList.remove('hide'); - detailLogo.classList.add('lazy'); - detailLogo.setAttribute('data-src', url); - imageLoader.lazyImage(detailLogo); - - //if (detailLogo.animate) { - // setTimeout(function() { - // bounceIn(detailLogo); - // }, 100); - //} - - } else { - detailLogo.classList.add('hide'); - } - } - - function showRecordingFields(page, item, user) { - - if (currentRecordingFields) { - return; - } - - var recordingFieldsElement = page.querySelector('.recordingFields'); - - if (item.Type == 'Program' && user.Policy.EnableLiveTvManagement) { - - require(['recordingFields'], function (recordingFields) { - - currentRecordingFields = new recordingFields({ - parent: recordingFieldsElement, - programId: item.Id, - serverId: item.ServerId - }); - recordingFieldsElement.classList.remove('hide'); - }); - } else { - recordingFieldsElement.classList.add('hide'); - recordingFieldsElement.innerHTML = ''; - } - } - - function renderLinks(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(''); - - linksElem.innerHTML = html; - linksElem.classList.remove('hide'); - - } else { - linksElem.classList.add('hide'); - } - } - - function shadeBlendConvert(p, from, to) { - if (typeof (p) != "number" || p < -1 || p > 1 || typeof (from) != "string" || (from[0] != 'r' && from[0] != '#') || (typeof (to) != "string" && typeof (to) != "undefined")) return null; //ErrorCheck - - var sbcRip = function (d) { - var l = d.length, RGB = new Object(); - if (l > 9) { - d = d.split(","); - if (d.length < 3 || d.length > 4) return null; //ErrorCheck - RGB[0] = i(d[0].slice(4)), RGB[1] = i(d[1]), RGB[2] = i(d[2]), RGB[3] = d[3] ? parseFloat(d[3]) : -1; - } else { - if (l == 8 || l == 6 || l < 4) return null; //ErrorCheck - if (l < 6) d = "#" + d[1] + d[1] + d[2] + d[2] + d[3] + d[3] + (l > 4 ? d[4] + "" + d[4] : ""); //3 digit - d = i(d.slice(1), 16), RGB[0] = d >> 16 & 255, RGB[1] = d >> 8 & 255, RGB[2] = d & 255, RGB[3] = l == 9 || l == 5 ? r(((d >> 24 & 255) / 255) * 10000) / 10000 : -1; - } - return RGB; - }; - - var i = parseInt, r = Math.round, h = from.length > 9, h = typeof (to) == "string" ? to.length > 9 ? true : to == "c" ? !h : false : h, b = p < 0, p = b ? p * -1 : p, to = to && to != "c" ? to : b ? "#000000" : "#FFFFFF", f = sbcRip(from), t = sbcRip(to); - if (!f || !t) return null; //ErrorCheck - if (h) return "rgb(" + r((t[0] - f[0]) * p + f[0]) + "," + r((t[1] - f[1]) * p + f[1]) + "," + r((t[2] - f[2]) * p + f[2]) + (f[3] < 0 && t[3] < 0 ? ")" : "," + (f[3] > -1 && t[3] > -1 ? r(((t[3] - f[3]) * p + f[3]) * 10000) / 10000 : t[3] < 0 ? f[3] : t[3]) + ")"); - else return "#" + (0x100000000 + (f[3] > -1 && t[3] > -1 ? r(((t[3] - f[3]) * p + f[3]) * 255) : t[3] > -1 ? r(t[3] * 255) : f[3] > -1 ? r(f[3] * 255) : 255) * 0x1000000 + r((t[0] - f[0]) * p + f[0]) * 0x10000 + r((t[1] - f[1]) * p + f[1]) * 0x100 + r((t[2] - f[2]) * p + f[2])).toString(16).slice(f[3] > -1 || t[3] > -1 ? 1 : 3); - } - - function loadSwatch(page, item) { - - var imageTags = item.ImageTags || {}; - - if (item.PrimaryImageTag) { - imageTags.Primary = item.PrimaryImageTag; - } - - var url; - var imageHeight = 300; - - if (item.SeriesId && item.SeriesPrimaryImageTag) { - - url = ApiClient.getScaledImageUrl(item.SeriesId, { - type: "Primary", - maxHeight: imageHeight, - tag: item.SeriesPrimaryImageTag - }); - } - else if (imageTags.Primary) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Primary", - maxHeight: imageHeight, - tag: item.ImageTags.Primary - }); - } - - if (!url) { - return; - } - - var img = new Image(); - img.onload = function () { - - imageLoader.getVibrantInfoFromElement(img, url).then(function (vibrantInfo) { - - vibrantInfo = vibrantInfo.split('|'); - var detailPageContent = page.querySelector('.detailPageContent'); - var detailPagePrimaryContainer = page.querySelector('.detailPagePrimaryContainer'); - - detailPageContent.style.color = vibrantInfo[1]; - - detailPagePrimaryContainer.style.backgroundColor = vibrantInfo[0]; - - }); - }; - - img.src = url; - } - - function renderImage(page, item, user) { - - var container = page.querySelector('.detailImageContainer'); - - LibraryBrowser.renderDetailImage(container, item, user.Policy.IsAdministrator && item.MediaType != 'Photo', null, imageLoader, indicators); - - //loadSwatch(page, item); - } - - function refreshDetailImageUserData(elem, item) { - - var detailImageProgressContainer = elem.querySelector('.detailImageProgressContainer'); - - detailImageProgressContainer.innerHTML = indicators.getProgressBarHtml(item); - } - - function refreshImage(page, item, user) { - - refreshDetailImageUserData(page.querySelector('.detailImageContainer'), item); - } - - function setPeopleHeader(page, item) { - - if (item.MediaType == "Audio" || item.Type == "MusicAlbum" || item.MediaType == "Book" || item.MediaType == "Photo") { - page.querySelector('#peopleHeader').innerHTML = globalize.translate('HeaderPeople'); - } else { - page.querySelector('#peopleHeader').innerHTML = globalize.translate('HeaderCastAndCrew'); - } - - } - - function renderNextUp(page, item, user) { - - var section = page.querySelector('.nextUpSection'); - - if (item.Type != 'Series') { - section.classList.add('hide'); - return; - } - - ApiClient.getNextUpEpisodes({ - - SeriesId: item.Id, - UserId: user.Id - - }).then(function (result) { - - if (result.Items.length) { - section.classList.remove('hide'); - } else { - section.classList.add('hide'); - } - - var html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: getThumbShape(false), - showTitle: true, - displayAsSpecial: item.Type == "Season" && item.IndexNumber, - overlayText: true, - lazy: true, - overlayPlayButton: true - }); - - var itemsContainer = section.querySelector('.nextUpItems'); - - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - }); - } - - function setInitialCollapsibleState(page, item, context, user) { - - page.querySelector('.collectionItems').innerHTML = ''; - - if (item.Type == 'TvChannel') { - - page.querySelector('#childrenCollapsible').classList.remove('hide'); - renderChannelGuide(page, item, user); - } - else if (item.Type == 'Playlist') { - - page.querySelector('#childrenCollapsible').classList.remove('hide'); - renderPlaylistItems(page, item, user); - } - else if (item.Type == 'Studio' || item.Type == 'Person' || item.Type == 'Genre' || item.Type == 'MusicGenre' || item.Type == 'GameGenre' || item.Type == 'MusicArtist') { - - page.querySelector('#childrenCollapsible').classList.remove('hide'); - renderItemsByName(page, item, user); - } - else if (item.IsFolder || item.Type == 'Episode') { - - if (item.Type == "BoxSet") { - page.querySelector('#childrenCollapsible').classList.add('hide'); - } - renderChildren(page, item); - } - else { - page.querySelector('#childrenCollapsible').classList.add('hide'); - } - - if (item.Type == 'Series') { - - renderSeriesSchedule(page, item, user); - } - - if (item.Type == 'Series') { - - renderNextUp(page, item, user); - } else { - page.querySelector('.nextUpSection').classList.add('hide'); - } - - if (item.MediaSources && item.MediaSources.length) { - renderMediaSources(page, user, item); - } - - renderScenes(page, item); - - if (!item.SpecialFeatureCount || item.SpecialFeatureCount == 0 || item.Type == "Series") { - page.querySelector('#specialsCollapsible').classList.add('hide'); - } else { - page.querySelector('#specialsCollapsible').classList.remove('hide'); - renderSpecials(page, item, user, 6); - } - if (!item.People || !item.People.length) { - page.querySelector('#castCollapsible').classList.add('hide'); - } else { - page.querySelector('#castCollapsible').classList.remove('hide'); - renderCast(page, item, context, enableScrollX() ? null : 12); - } - - if (item.PartCount && item.PartCount > 1) { - page.querySelector('#additionalPartsCollapsible').classList.remove('hide'); - renderAdditionalParts(page, item, user); - } else { - page.querySelector('#additionalPartsCollapsible').classList.add('hide'); - } - - page.querySelector('#themeSongsCollapsible').classList.add('hide'); - page.querySelector('#themeVideosCollapsible').classList.add('hide'); - - if (item.Type == "MusicAlbum") { - renderMusicVideos(page, item, user); - } else { - page.querySelector('#musicVideosCollapsible').classList.add('hide'); - } - - renderThemeMedia(page, item, user); - - if (enableScrollX()) { - renderCriticReviews(page, item); - } else { - renderCriticReviews(page, item, 1); - } - } - - function renderOverview(elems, item) { - - for (var i = 0, length = elems.length; i < length; i++) { - var elem = elems[i]; - var overview = item.Overview || ''; - - if (overview) { - elem.innerHTML = overview; - - elem.classList.remove('hide'); - - var anchors = elem.querySelectorAll('a'); - for (var j = 0, length2 = anchors.length; j < length2; j++) { - anchors[j].setAttribute("target", "_blank"); - } - - } else { - elem.innerHTML = ''; - - elem.classList.add('hide'); - } - } - } - - function renderDetails(page, item, context, isStatic) { - - renderSimilarItems(page, item, context); - renderMoreFromItems(page, item); - - var taglineElement = page.querySelector('.tagline'); - - if (item.Taglines && item.Taglines.length) { - taglineElement.classList.remove('hide'); - taglineElement.innerHTML = item.Taglines[0]; - } else { - taglineElement.classList.add('hide'); - } - - var overview = page.querySelector('.overview'); - var externalLinksElem = page.querySelector('.itemExternalLinks'); - - if (item.Type === 'Season' || item.Type === 'MusicAlbum' || item.Type === 'MusicArtist') { - overview.classList.add('detailsHiddenOnMobile'); - externalLinksElem.classList.add('detailsHiddenOnMobile'); - } - - renderOverview([overview], item); - - renderAwardSummary(page.querySelector('#awardSummary'), item); - - var i, length; - var itemMiscInfo = page.querySelectorAll('.itemMiscInfo-primary'); - for (i = 0, length = itemMiscInfo.length; i < length; i++) { - mediaInfo.fillPrimaryMediaInfo(itemMiscInfo[i], item, { - interactive: true, - episodeTitle: false - }); - if (itemMiscInfo[i].innerHTML) { - itemMiscInfo[i].classList.remove('hide'); - } else { - itemMiscInfo[i].classList.add('hide'); - } - } - itemMiscInfo = page.querySelectorAll('.itemMiscInfo-secondary'); - for (i = 0, length = itemMiscInfo.length; i < length; i++) { - mediaInfo.fillSecondaryMediaInfo(itemMiscInfo[i], item, { - interactive: true - }); - if (itemMiscInfo[i].innerHTML) { - itemMiscInfo[i].classList.remove('hide'); - } else { - itemMiscInfo[i].classList.add('hide'); - } - } - var itemGenres = page.querySelectorAll('.itemGenres'); - for (i = 0, length = itemGenres.length; i < length; i++) { - renderGenres(itemGenres[i], item, null, isStatic); - } - - renderStudios(page.querySelector('.itemStudios'), item, isStatic); - renderUserDataIcons(page, item); - renderLinks(externalLinksElem, item); - - page.querySelector('.criticRatingScore').innerHTML = (item.CriticRating || '0') + '%'; - - if (item.CriticRatingSummary) { - page.querySelector('#criticRatingSummary').classList.remove('hide'); - page.querySelector('.criticRatingSummaryText').innerHTML = item.CriticRatingSummary; - - } else { - page.querySelector('#criticRatingSummary').classList.add('hide'); - } - - renderTags(page, item); - - renderSeriesAirTime(page, item, isStatic); - - if (renderDynamicMediaIcons(page, item)) { - page.querySelector('.mediaInfoIcons').classList.remove('hide'); - } else { - page.querySelector('.mediaInfoIcons').classList.add('hide'); - } - - var artist = page.querySelectorAll('.artist'); - for (i = 0, length = artist.length; i < length; i++) { - if (item.ArtistItems && item.ArtistItems.length && item.Type != "MusicAlbum") { - artist[i].classList.remove('hide'); - artist[i].innerHTML = getArtistLinksHtml(item.ArtistItems, context); - } else { - artist[i].classList.add('hide'); - } - } - - if (item.MediaSources && item.MediaSources.length && item.Path) { - page.querySelector('.audioVideoMediaInfo').classList.remove('hide'); - } else { - page.querySelector('.audioVideoMediaInfo').classList.add('hide'); - } - - if (item.MediaType == 'Photo') { - page.querySelector('.photoInfo').classList.remove('hide'); - renderPhotoInfo(page, item); - } else { - page.querySelector('.photoInfo').classList.add('hide'); - } - } - - function renderDynamicMediaIcons(view, item) { - - var html = mediaInfo.getMediaInfoStats(item).map(function (mediaInfoItem) { - - var text = mediaInfoItem.text; - - if (mediaInfoItem.type === 'added') { - return '
' + text + '
'; - } - - return '
' + text + '
'; - - }).join(''); - - view.querySelector('.mediaInfoIcons').innerHTML = html; - - return html; - } - - function renderPhotoInfo(page, item) { - - var html = ''; - - var attributes = []; - - if (item.CameraMake) { - attributes.push(createAttribute(globalize.translate('MediaInfoCameraMake'), item.CameraMake)); - } - - if (item.CameraModel) { - attributes.push(createAttribute(globalize.translate('MediaInfoCameraModel'), item.CameraModel)); - } - - if (item.Altitude) { - attributes.push(createAttribute(globalize.translate('MediaInfoAltitude'), item.Altitude.toFixed(1))); - } - - if (item.Aperture) { - attributes.push(createAttribute(globalize.translate('MediaInfoAperture'), 'F' + item.Aperture.toFixed(1))); - } - - if (item.ExposureTime) { - - var val = 1 / item.ExposureTime; - - attributes.push(createAttribute(globalize.translate('MediaInfoExposureTime'), '1/' + val + ' s')); - } - - if (item.FocalLength) { - attributes.push(createAttribute(globalize.translate('MediaInfoFocalLength'), item.FocalLength.toFixed(1) + ' mm')); - } - - if (item.ImageOrientation) { - //attributes.push(createAttribute(Globalize.translate('MediaInfoOrientation'), item.ImageOrientation)); - } - - if (item.IsoSpeedRating) { - attributes.push(createAttribute(globalize.translate('MediaInfoIsoSpeedRating'), item.IsoSpeedRating)); - } - - if (item.Latitude) { - attributes.push(createAttribute(globalize.translate('MediaInfoLatitude'), item.Latitude.toFixed(1))); - } - - if (item.Longitude) { - attributes.push(createAttribute(globalize.translate('MediaInfoLongitude'), item.Longitude.toFixed(1))); - } - - if (item.ShutterSpeed) { - attributes.push(createAttribute(globalize.translate('MediaInfoShutterSpeed'), item.ShutterSpeed)); - } - - if (item.Software) { - attributes.push(createAttribute(globalize.translate('MediaInfoSoftware'), item.Software)); - } - - html += attributes.join('
'); - - page.querySelector('.photoInfoContent').innerHTML = html; - } - - function getArtistLinksHtml(artists, context) { - - var html = []; - - for (var i = 0, length = artists.length; i < length; i++) { - - var artist = artists[i]; - - html.push('' + artist.Name + ''); - - } - - html = html.join(' / '); - - if (artists.length == 1) { - return globalize.translate('ValueArtist', html); - } - if (artists.length > 1) { - return globalize.translate('ValueArtists', html); - } - - return html; - } - - function enableScrollX() { - return browserInfo.mobile && screen.availWidth <= 1000; - } - - function getPortraitShape(scrollX) { - if (scrollX == null) { - scrollX = enableScrollX(); - } - return scrollX ? 'overflowPortrait' : 'portrait'; - } - - function getSquareShape(scrollX) { - if (scrollX == null) { - scrollX = enableScrollX(); - } - return scrollX ? 'overflowSquare' : 'square'; - } - - function getThumbShape(scrollX) { - - if (scrollX == null) { - scrollX = enableScrollX(); - } - return scrollX ? 'overflowBackdrop' : 'backdrop'; - } - - function renderMoreFromItems(page, item) { - - var moreFromSection = page.querySelector('#moreFromSection'); - - if (!moreFromSection) { - return; - } - - if (item.Type != 'MusicAlbum' || !item.AlbumArtists || !item.AlbumArtists.length) { - moreFromSection.classList.add('hide'); - return; - } - - ApiClient.getItems(Dashboard.getCurrentUserId(), { - - IncludeItemTypes: "MusicAlbum", - ArtistIds: item.AlbumArtists[0].Id, - Recursive: true, - ExcludeItemIds: item.Id - - }).then(function (result) { - - if (!result.Items.length) { - moreFromSection.classList.add('hide'); - return; - } - moreFromSection.classList.remove('hide'); - - moreFromSection.querySelector('.moreFromHeader').innerHTML = globalize.translate('MoreFromValue', item.AlbumArtists[0].Name); - - var html = ''; - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var shape = item.Type == "MusicAlbum" || item.Type == "MusicArtist" ? getSquareShape() : getPortraitShape(); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: shape, - showParentTitle: item.Type == "MusicAlbum", - centerText: !supportsImageAnalysis, - showTitle: item.Type == "MusicAlbum" || item.Type == "Game" || item.Type == "MusicArtist", - coverImage: item.Type == "MusicAlbum" || item.Type == "MusicArtist", - overlayPlayButton: true, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - }); - html += '
'; - - var similarContent = page.querySelector('#moreFromItems'); - similarContent.innerHTML = html; - imageLoader.lazyChildren(similarContent); - }); - } - - function renderSimilarItems(page, item, context) { - - var similarCollapsible = page.querySelector('#similarCollapsible'); - - if (!similarCollapsible) { - return; - } - - if (item.Type == "Movie" || item.Type == "Trailer" || item.Type == "Series" || item.Type == "Program" || item.Type == "Recording" || item.Type == "Game" || item.Type == "MusicAlbum" || item.Type == "MusicArtist" || item.Type == "ChannelVideoItem") { - similarCollapsible.classList.remove('hide'); - } - else { - similarCollapsible.classList.add('hide'); - return; - } - - var shape = item.Type == "MusicAlbum" || item.Type == "MusicArtist" ? getSquareShape() : getPortraitShape(); - - var options = { - userId: Dashboard.getCurrentUserId(), - limit: item.Type == "MusicAlbum" || item.Type == "MusicArtist" ? 8 : 10, - fields: "PrimaryImageAspectRatio,UserData,CanDelete" - }; - - if (item.Type == 'MusicAlbum' && item.AlbumArtists && item.AlbumArtists.length) { - options.ExcludeArtistIds = item.AlbumArtists[0].Id; - } - - if (enableScrollX()) { - options.limit = 12; - } - - ApiClient.getSimilarItems(item.Id, options).then(function (result) { - - if (!result.Items.length) { - - similarCollapsible.classList.add('hide'); - return; - } - - similarCollapsible.classList.remove('hide'); - - var html = ''; - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = supportsImageAnalysis && (item.Type == "MusicAlbum" || item.Type == "Game" || item.Type == "MusicArtist"); - - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: shape, - showParentTitle: item.Type == "MusicAlbum", - centerText: !cardLayout, - showTitle: item.Type == "MusicAlbum" || item.Type == "Game" || item.Type == "MusicArtist", - context: context, - lazy: true, - showDetailsMenu: true, - coverImage: item.Type == "MusicAlbum" || item.Type == "MusicArtist", - overlayPlayButton: true, - cardLayout: cardLayout, - vibrant: cardLayout && supportsImageAnalysis - }); - html += '
'; - - var similarContent = similarCollapsible.querySelector('.similarContent'); - similarContent.innerHTML = html; - imageLoader.lazyChildren(similarContent); - }); - } - - function renderSeriesAirTime(page, item, isStatic) { - - var seriesAirTime = page.querySelector('#seriesAirTime'); - - if (item.Type != "Series") { - seriesAirTime.classList.add('hide'); - return; - } - - var html = ''; - - if (item.AirDays && item.AirDays.length) { - html += item.AirDays.length == 7 ? 'daily' : item.AirDays.map(function (a) { - return a + "s"; - - }).join(','); - } - - if (item.AirTime) { - html += ' at ' + item.AirTime; - } - - if (item.Studios.length) { - - if (isStatic) { - html += ' on ' + item.Studios[0].Name; - } else { - - var context = inferContext(item); - - var href = LibraryBrowser.getHref(item.Studios[0], context); - html += ' on ' + item.Studios[0].Name + ''; - } - } - - if (html) { - html = (item.Status == 'Ended' ? 'Aired ' : 'Airs ') + html; - - seriesAirTime.innerHTML = html; - seriesAirTime.classList.remove('hide'); - } else { - seriesAirTime.classList.add('hide'); - } - } - - function renderTags(page, item) { - - var itemTags = page.querySelector('.itemTags'); - - if (item.Tags && item.Tags.length) { - - var html = ''; - for (var i = 0, length = item.Tags.length; i < length; i++) { - - html += '
' + item.Tags[i] + '
'; - - } - - itemTags.innerHTML = html; - itemTags.classList.remove('hide'); - - } else { - itemTags.classList.add('hide'); - } - } - - function getEpisodesFunction(seriesId, query) { - - query = Object.assign({}, query); - - return function (index, limit, fields) { - - query.StartIndex = index; - query.Limit = limit; - query.Fields = fields; - - return ApiClient.getEpisodes(seriesId, query); - - }; - - } - - function getAlbumSongsFunction(query) { - - query = Object.assign({}, query); - - return function (index, limit, fields) { - - query.StartIndex = index; - query.Limit = limit; - query.Fields = fields; - - return ApiClient.getItems(Dashboard.getCurrentUserId(), query); - - }; - - } - - var _childrenItemsFunction = null; - function renderChildren(page, item) { - - _childrenItemsFunction = null; - - var fields = "ItemCounts,AudioInfo,PrimaryImageAspectRatio,BasicSyncInfo,CanDelete"; - - var query = { - ParentId: item.Id, - Fields: fields - }; - - // Let the server pre-sort boxsets - if (item.Type !== "BoxSet") { - query.SortBy = "SortName"; - } - - var userId = Dashboard.getCurrentUserId(); - var promise; - - if (item.Type == "Series") { - - promise = ApiClient.getSeasons(item.Id, { - - userId: userId, - Fields: fields - }); - } - else if (item.Type == "Season") { - - // Use dedicated episodes endpoint - promise = ApiClient.getEpisodes(item.SeriesId, { - - seasonId: item.Id, - userId: userId, - Fields: fields - }); - - _childrenItemsFunction = getEpisodesFunction(item.SeriesId, { - - seasonId: item.Id, - userId: userId, - Fields: fields - }); - } - else if (item.Type == "Episode" && item.SeriesId && item.SeasonId) { - - // Use dedicated episodes endpoint - promise = ApiClient.getEpisodes(item.SeriesId, { - - seasonId: item.SeasonId, - userId: userId, - Fields: fields - }); - - _childrenItemsFunction = getEpisodesFunction(item.SeriesId, { - - seasonId: item.SeasonId, - userId: userId, - Fields: fields - }); - } - else if (item.Type == "MusicAlbum") { - - _childrenItemsFunction = getAlbumSongsFunction(query); - } - - promise = promise || ApiClient.getItems(Dashboard.getCurrentUserId(), query); - - promise.then(function (result) { - - var html = ''; - - var scrollX = false; - var isList = false; - - var scrollClass = 'hiddenScrollX'; - var childrenItemsContainer = page.querySelector('.childrenItemsContainer'); - - if (item.Type == "MusicAlbum") { - - html = listView.getListViewHtml({ - items: result.Items, - smallIcon: true, - showIndex: true, - index: 'disc', - showIndexNumber: true, - playFromHere: true, - action: 'playallfromhere', - image: false, - artist: 'auto', - containerAlbumArtist: item.AlbumArtist, - addToListButton: true - }); - isList = true; - } - else if (item.Type == "Series") { - - scrollX = enableScrollX(); - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: getPortraitShape(), - showTitle: true, - centerText: true, - lazy: true, - overlayPlayButton: true, - allowBottomPadding: !scrollX - }); - } - else if (item.Type == "Season" || item.Type == "Episode") { - - if (item.Type === 'Episode') { - childrenItemsContainer.classList.add('darkScroller'); - } - - scrollX = item.Type == "Episode"; - if (!browser.touch) { - scrollClass = 'smoothScrollX'; - } - - if (result.Items.length == 1 && item.Type === 'Episode') { - - return; - - } else { - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: getThumbShape(scrollX), - showTitle: true, - displayAsSpecial: item.Type == "Season" && item.IndexNumber, - playFromHere: true, - overlayText: true, - lazy: true, - showDetailsMenu: true, - overlayPlayButton: true, - allowBottomPadding: !scrollX, - includeParentInfoInTitle: false - }); - } - } - else if (item.Type == "GameSystem") { - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "auto", - showTitle: true, - centerText: true, - lazy: true, - showDetailsMenu: true - }); - } - - page.querySelector('#childrenCollapsible').classList.remove('hide'); - - if (scrollX) { - childrenItemsContainer.classList.add(scrollClass); - childrenItemsContainer.classList.remove('vertical-wrap'); - childrenItemsContainer.classList.remove('vertical-list'); - } else { - childrenItemsContainer.classList.remove('hiddenScrollX'); - childrenItemsContainer.classList.remove('smoothScrollX'); - - if (isList) { - childrenItemsContainer.classList.add('vertical-list'); - childrenItemsContainer.classList.remove('vertical-wrap'); - } else { - childrenItemsContainer.classList.add('vertical-wrap'); - childrenItemsContainer.classList.remove('vertical-list'); - } - } - - childrenItemsContainer.innerHTML = html; - imageLoader.lazyChildren(childrenItemsContainer); - - if (item.Type == "BoxSet") { - - var collectionItemTypes = [ - { name: globalize.translate('HeaderMovies'), type: 'Movie' }, - { name: globalize.translate('HeaderSeries'), type: 'Series' }, - { name: globalize.translate('HeaderAlbums'), type: 'MusicAlbum' }, - { name: globalize.translate('HeaderGames'), type: 'Game' }, - { name: globalize.translate('HeaderBooks'), type: 'Book' } - ]; - - renderCollectionItems(page, item, collectionItemTypes, result.Items); - } - else if (item.Type === 'Episode') { - - var card = childrenItemsContainer.querySelector('.card[data-id="' + item.Id + '"]'); - if (card) { - scrollHelper.toStart(childrenItemsContainer, card.previousSibling || card, true); - } - } - }); - - if (item.Type == "Season") { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('HeaderEpisodes'); - } - else if (item.Type == "Episode") { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('MoreFromValue', item.SeasonName); - } - else if (item.Type == "Series") { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('HeaderSeasons'); - } - else if (item.Type == "MusicAlbum") { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('HeaderTracks'); - } - else if (item.Type == "GameSystem") { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('HeaderGames'); - } - else { - page.querySelector('#childrenTitle').innerHTML = globalize.translate('HeaderItems'); - } - - if (item.Type == "MusicAlbum") { - page.querySelector('.childrenSectionHeader', page).classList.add('hide'); - } else { - page.querySelector('.childrenSectionHeader', page).classList.remove('hide'); - } - } - - function renderItemsByName(page, item, user) { - - require('scripts/itembynamedetailpage'.split(','), function () { - - - window.ItemsByName.renderItems(page, item); - }); - } - - function renderPlaylistItems(page, item, user) { - - require('scripts/playlistedit'.split(','), function () { - - - PlaylistViewer.render(page, item); - }); - } - - function renderChannelGuide(page, item, user) { - - require('scripts/livetvchannel,scripts/livetvcomponents,livetvcss'.split(','), function (liveTvChannelPage) { - - liveTvChannelPage.renderPrograms(page, item.Id); - }); - } - - function renderSeriesSchedule(page, item, user) { - - return; - ApiClient.getLiveTvPrograms({ - - UserId: Dashboard.getCurrentUserId(), - HasAired: false, - SortBy: "StartDate", - EnableTotalRecordCount: false, - EnableImages: false, - ImageTypeLimit: 0, - Limit: 50, - EnableUserData: false, - LibrarySeriesId: item.Id - - }).then(function (result) { - - if (result.Items.length) { - page.querySelector('#seriesScheduleSection').classList.remove('hide'); - - } else { - page.querySelector('#seriesScheduleSection').classList.add('hide'); - } - - page.querySelector('#seriesScheduleList').innerHTML = listView.getListViewHtml({ - items: result.Items, - enableUserDataButtons: false, - showParentTitle: false, - image: false, - showProgramDateTime: true, - mediaInfo: false, - showTitle: true, - moreButton: false, - action: 'programdialog' - }); - - Dashboard.hideLoadingMsg(); - }); - } - - function inferContext(item) { - - if (item.Type == 'Movie' || item.Type == 'BoxSet') { - return 'movies'; - } - if (item.Type == 'Series' || item.Type == 'Season' || item.Type == 'Episode') { - return 'tvshows'; - } - if (item.Type == 'Game' || item.Type == 'GameSystem') { - return 'games'; - } - if (item.Type == 'Game' || item.Type == 'GameSystem') { - return 'games'; - } - if (item.Type == 'MusicArtist' || item.Type == 'MusicAlbum') { - return 'music'; - } - - return null; - } - - function renderStudios(elem, item, isStatic) { - - var context = inferContext(item); - - if (item.Studios && item.Studios.length && item.Type != "Series" && false) { - - var html = ''; - - for (var i = 0, length = item.Studios.length; i < length; i++) { - - if (i > 0) { - html += '  /  '; - } - - if (isStatic) { - html += item.Studios[i].Name; - } else { - - item.Studios[i].Type = 'Studio'; - var href = LibraryBrowser.getHref(item.Studios[i], context); - html += '' + item.Studios[i].Name + ''; - } - } - - var translationKey = item.Studios.length > 1 ? "ValueStudios" : "ValueStudio"; - - html = globalize.translate(translationKey, html); - - elem.innerHTML = html; - elem.classList.remove('hide'); - - } else { - elem.classList.add('hide'); - } - } - - function renderGenres(elem, item, limit, isStatic) { - - var context = inferContext(item); - - var html = ''; - - var genres = item.Genres || []; - - for (var i = 0, length = genres.length; i < length; i++) { - - if (limit && i >= limit) { - break; - } - - if (i > 0) { - html += ''; - } - - var param = item.Type == "Audio" || item.Type == "MusicArtist" || item.Type == "MusicAlbum" ? "musicgenre" : "genre"; - - if (item.MediaType == "Game") { - param = "gamegenre"; - } - - if (isStatic) { - html += genres[i]; - } else { - - var type; - switch (context) { - case 'tvshows': - type = 'Series'; - break; - case 'games': - type = 'Game'; - break; - case 'music': - type = 'MusicAlbum'; - break; - default: - type = 'Movie'; - break; - } - - var url = "secondaryitems.html?type=" + type + "&" + param + "=" + ApiClient.encodeName(genres[i]); - - html += '' + genres[i] + ''; - } - } - - elem.innerHTML = html; - } - - function renderAwardSummary(elem, item) { - if (item.AwardSummary) { - elem.classList.remove('hide'); - elem.innerHTML = globalize.translate('ValueAwards', item.AwardSummary); - } else { - elem.classList.add('hide'); - } - } - - function renderCollectionItems(page, parentItem, types, items) { - - // First empty out existing content - page.querySelector('.collectionItems').innerHTML = ''; - var i, length; - - for (i = 0, length = types.length; i < length; i++) { - - var type = types[i]; - - var typeItems = items.filter(function (curr) { - - return curr.Type == type.type; - - }); - - if (typeItems.length) { - renderCollectionItemType(page, parentItem, type, typeItems); - } - } - - var otherType = { name: globalize.translate('HeaderOtherItems') }; - - var otherTypeItems = items.filter(function (curr) { - - return !types.filter(function (t) { - - return t.type == curr.Type; - - }).length; - - }); - - if (otherTypeItems.length) { - renderCollectionItemType(page, parentItem, otherType, otherTypeItems); - } - - if (!items.length) { - renderCollectionItemType(page, parentItem, { name: globalize.translate('HeaderItems') }, items); - } - } - - function renderCollectionItemType(page, parentItem, type, items) { - - var html = ''; - - html += '
'; - - html += '
'; - html += '

'; - html += '' + type.name + ''; - - html += '

'; - html += ''; - html += '
'; - - html += '
'; - - var shape = type.type == 'MusicAlbum' ? getSquareShape(false) : getPortraitShape(false); - - html += cardBuilder.getCardsHtml({ - items: items, - shape: shape, - showTitle: true, - centerText: true, - lazy: true, - showDetailsMenu: true, - overlayMoreButton: true, - showAddToCollection: false, - showRemoveFromCollection: true, - collectionId: parentItem.Id - }); - html += '
'; - - html += '
'; - - var collectionItems = page.querySelector('.collectionItems'); - collectionItems.insertAdjacentHTML('beforeend', html); - imageLoader.lazyChildren(collectionItems); - - collectionItems.querySelector('.btnAddToCollection').addEventListener('click', function () { - require(['alert'], function (alert) { - alert({ - text: globalize.translate('AddItemToCollectionHelp'), - html: globalize.translate('AddItemToCollectionHelp') + '

' + globalize.translate('ButtonLearnMore') + '' - }); - }); - }); - } - - function renderUserDataIcons(page, item) { - - var userDataIcons = page.querySelectorAll('.userDataIcons'); - - for (var i = 0, length = userDataIcons.length; i < length; i++) { - - if (item.Type == 'Program' || item.Type == 'SeriesTimer') { - userDataIcons[i].classList.add('hide'); - } else { - userDataIcons[i].classList.remove('hide'); - } - - userdataButtons.fill({ - item: item, - style: 'fab-mini', - element: userDataIcons[i] - }); - } - } - - function renderCriticReviews(page, item, limit) { - - if (item.Type != "Movie" && item.Type != "Trailer" && item.Type != "MusicVideo") { - page.querySelector('#criticReviewsCollapsible').classList.add('hide'); - return; - } - - var options = {}; - - if (limit) { - options.limit = limit; - } - - ApiClient.getCriticReviews(item.Id, options).then(function (result) { - - if (result.TotalRecordCount || item.CriticRatingSummary || item.AwardSummary) { - page.querySelector('#criticReviewsCollapsible').classList.remove('hide'); - renderCriticReviewsContent(page, result, limit); - } else { - page.querySelector('#criticReviewsCollapsible').classList.add('hide'); - } - }); - } - - function renderCriticReviewsContent(page, result, limit) { - - var html = ''; - - var reviews = result.Items; - for (var i = 0, length = reviews.length; i < length; i++) { - - var review = reviews[i]; - - html += '
'; - html += '
'; - - if (review.Score != null) { - //html += review.Score; - } - else if (review.Likes != null) { - - if (review.Likes) { - html += '
'; - } else { - html += '
'; - } - } - - html += '
'; - - html += '

' + review.Caption + '

'; - - var vals = []; - - if (review.ReviewerName) { - vals.push(review.ReviewerName); - } - if (review.Publisher) { - vals.push(review.Publisher); - } - - html += '
' + vals.join(', ') + '.'; - if (review.Date) { - - try { - - var date = datetime.toLocaleDateString(datetime.parseISO8601Date(review.Date, true)); - - html += '' + date + ''; - } - catch (error) { - - } - - } - html += '
'; - - if (review.Url) { - html += ''; - } - - html += '
'; - - html += '
'; - html += '
'; - } - - if (limit && result.TotalRecordCount > limit) { - html += '

'; - } - - var criticReviewsContent = page.querySelector('#criticReviewsContent'); - criticReviewsContent.innerHTML = html; - - if (enableScrollX()) { - criticReviewsContent.classList.add('hiddenScrollX'); - } else { - criticReviewsContent.classList.remove('hiddenScrollX'); - } - } - - function renderThemeMedia(page, item) { - - if (item.Type === 'SeriesTimer' || item.Type === 'Timer' || item.Type === 'Genre' || item.Type === 'MusicGenre' || item.Type === 'GameGenre' || item.Type === 'Studio' || item.Type === 'Person') { - return; - } - - ApiClient.getThemeMedia(Dashboard.getCurrentUserId(), item.Id, true).then(function (result) { - - var themeSongs = result.ThemeSongsResult.OwnerId == item.Id ? - result.ThemeSongsResult.Items : - []; - - var themeVideos = result.ThemeVideosResult.OwnerId == item.Id ? - result.ThemeVideosResult.Items : - []; - - renderThemeSongs(page, themeSongs); - renderThemeVideos(page, themeVideos); - }); - } - - function renderThemeSongs(page, items) { - - if (items.length) { - - page.querySelector('#themeSongsCollapsible').classList.remove('hide'); - - var html = listView.getListViewHtml({ - items: items - }); - - page.querySelector('#themeSongsContent').innerHTML = html; - } else { - page.querySelector('#themeSongsCollapsible').classList.add('hide'); - } - } - - function renderThemeVideos(page, items, user) { - - if (items.length) { - - page.querySelector('#themeVideosCollapsible').classList.remove('hide'); - - var themeVideosContent = page.querySelector('#themeVideosContent'); - themeVideosContent.innerHTML = getVideosHtml(items, user); - imageLoader.lazyChildren(themeVideosContent); - } else { - page.querySelector('#themeVideosCollapsible').classList.add('hide'); - } - } - - function renderMusicVideos(page, item, user) { - - ApiClient.getItems(user.Id, { - - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "MusicVideo", - Recursive: true, - Fields: "DateCreated,CanDelete", - Albums: item.Name - - }).then(function (result) { - if (result.Items.length) { - - page.querySelector('#musicVideosCollapsible').classList.remove('hide'); - - var musicVideosContent = page.querySelector('.musicVideosContent'); - musicVideosContent.innerHTML = getVideosHtml(result.Items, user); - imageLoader.lazyChildren(musicVideosContent); - - } else { - page.querySelector('#musicVideosCollapsible').classList.add('hide'); - } - }); - - } - - function renderAdditionalParts(page, item, user) { - - ApiClient.getAdditionalVideoParts(user.Id, item.Id).then(function (result) { - - if (result.Items.length) { - - page.querySelector('#additionalPartsCollapsible').classList.remove('hide'); - - var additionalPartsContent = page.querySelector('#additionalPartsContent'); - additionalPartsContent.innerHTML = getVideosHtml(result.Items, user); - imageLoader.lazyChildren(additionalPartsContent); - - } else { - page.querySelector('#additionalPartsCollapsible').classList.add('hide'); - } - }); - } - - function renderScenes(page, item) { - - var chapters = item.Chapters || []; - - // If there are no chapter images, don't show a bunch of empty tiles - if (chapters.length && !chapters[0].ImageTag) { - chapters = []; - } - - if (!chapters.length) { - page.querySelector('#scenesCollapsible').classList.add('hide'); - } else { - page.querySelector('#scenesCollapsible').classList.remove('hide'); - - var scenesContent = page.querySelector('#scenesContent'); - - if (enableScrollX()) { - scenesContent.classList.add('smoothScrollX'); - } else { - scenesContent.classList.add('vertical-wrap'); - } - - require(['chaptercardbuilder'], function (chaptercardbuilder) { - - chaptercardbuilder.buildChapterCards(item, chapters, { - itemsContainer: scenesContent, - coverImage: true, - width: 400, - backdropShape: getThumbShape(), - squareShape: getSquareShape() - }); - }); - } - } - - function renderMediaSources(page, user, item) { - - var html = item.MediaSources.map(function (v) { - - return getMediaSourceHtml(user, item, v); - - }).join('
'); - - if (item.MediaSources.length > 1) { - html = '
' + html; - } - - var mediaInfoContent = page.querySelector('#mediaInfoContent'); - mediaInfoContent.innerHTML = html; - } - - function getMediaSourceHtml(user, item, version) { - - var html = ''; - - if (version.Name && item.MediaSources.length > 1) { - html += '
' + version.Name + '

'; - } - - for (var i = 0, length = version.MediaStreams.length; i < length; i++) { - - var stream = version.MediaStreams[i]; - - if (stream.Type == "Data") { - continue; - } - - html += '
'; - - var displayType = globalize.translate('MediaInfoStreamType' + stream.Type); - - html += '

' + displayType + '

'; - - var attributes = []; - - if (stream.Language && stream.Type != "Video") { - attributes.push(createAttribute(globalize.translate('MediaInfoLanguage'), stream.Language)); - } - - if (stream.Codec) { - attributes.push(createAttribute(globalize.translate('MediaInfoCodec'), stream.Codec.toUpperCase())); - } - - if (stream.CodecTag) { - attributes.push(createAttribute(globalize.translate('MediaInfoCodecTag'), stream.CodecTag)); - } - - if (stream.IsAVC != null) { - attributes.push(createAttribute('AVC', (stream.IsAVC ? 'Yes' : 'No'))); - } - - if (stream.Profile) { - attributes.push(createAttribute(globalize.translate('MediaInfoProfile'), stream.Profile)); - } - - if (stream.Level) { - attributes.push(createAttribute(globalize.translate('MediaInfoLevel'), stream.Level)); - } - - if (stream.Width || stream.Height) { - attributes.push(createAttribute(globalize.translate('MediaInfoResolution'), stream.Width + 'x' + stream.Height)); - } - - if (stream.AspectRatio && stream.Codec != "mjpeg") { - attributes.push(createAttribute(globalize.translate('MediaInfoAspectRatio'), stream.AspectRatio)); - } - - if (stream.Type == "Video") { - if (stream.IsAnamorphic != null) { - attributes.push(createAttribute(globalize.translate('MediaInfoAnamorphic'), (stream.IsAnamorphic ? 'Yes' : 'No'))); - } - - attributes.push(createAttribute(globalize.translate('MediaInfoInterlaced'), (stream.IsInterlaced ? 'Yes' : 'No'))); - } - - if (stream.AverageFrameRate || stream.RealFrameRate) { - attributes.push(createAttribute(globalize.translate('MediaInfoFramerate'), (stream.AverageFrameRate || stream.RealFrameRate))); - } - - if (stream.ChannelLayout) { - attributes.push(createAttribute(globalize.translate('MediaInfoLayout'), stream.ChannelLayout)); - } - if (stream.Channels) { - attributes.push(createAttribute(globalize.translate('MediaInfoChannels'), stream.Channels + ' ch')); - } - - if (stream.BitRate && stream.Codec != "mjpeg") { - attributes.push(createAttribute(globalize.translate('MediaInfoBitrate'), (parseInt(stream.BitRate / 1000)) + ' kbps')); - } - - if (stream.SampleRate) { - attributes.push(createAttribute(globalize.translate('MediaInfoSampleRate'), stream.SampleRate + ' Hz')); - } - - if (stream.BitDepth) { - attributes.push(createAttribute(globalize.translate('MediaInfoBitDepth'), stream.BitDepth + ' bit')); - } - - if (stream.PixelFormat) { - attributes.push(createAttribute(globalize.translate('MediaInfoPixelFormat'), stream.PixelFormat)); - } - - if (stream.RefFrames) { - attributes.push(createAttribute(globalize.translate('MediaInfoRefFrames'), stream.RefFrames)); - } - - if (stream.NalLengthSize) { - attributes.push(createAttribute('NAL', stream.NalLengthSize)); - } - - if (stream.Type != "Video") { - attributes.push(createAttribute(globalize.translate('MediaInfoDefault'), (stream.IsDefault ? 'Yes' : 'No'))); - } - if (stream.Type == "Subtitle") { - attributes.push(createAttribute(globalize.translate('MediaInfoForced'), (stream.IsForced ? 'Yes' : 'No'))); - attributes.push(createAttribute(globalize.translate('MediaInfoExternal'), (stream.IsExternal ? 'Yes' : 'No'))); - } - - if (stream.Type == "Video" && version.Timestamp) { - attributes.push(createAttribute(globalize.translate('MediaInfoTimestamp'), version.Timestamp)); - } - - if (stream.DisplayTitle) { - attributes.push(createAttribute('Title', stream.DisplayTitle)); - } - - html += attributes.join('
'); - - html += '
'; - } - - if (version.Container) { - html += '
' + globalize.translate('MediaInfoContainer') + '' + version.Container + '
'; - } - - if (version.Formats && version.Formats.length) { - //html += '
'+Globalize.translate('MediaInfoFormat')+'' + version.Formats.join(',') + '
'; - } - - if (version.Path && version.Protocol != 'Http' && user && user.Policy.IsAdministrator) { - html += '
' + globalize.translate('MediaInfoPath') + '' + version.Path + '
'; - } - - if (version.Size) { - - var size = (version.Size / (1024 * 1024)).toFixed(0); - - html += '
' + globalize.translate('MediaInfoSize') + '' + size + ' MB
'; - } - - return html; - } - - function createAttribute(label, value) { - return '' + label + '' + value + '' - } - - function getVideosHtml(items, user, limit, moreButtonClass) { - - var html = cardBuilder.getCardsHtml({ - items: items, - shape: "auto", - showTitle: true, - action: 'play', - overlayText: true, - showRuntime: true - }); - - if (limit && items.length > limit) { - html += '

'; - } - - return html; - } - - function renderSpecials(page, item, user, limit) { - - ApiClient.getSpecialFeatures(user.Id, item.Id).then(function (specials) { - - var specialsContent = page.querySelector('#specialsContent'); - specialsContent.innerHTML = getVideosHtml(specials, user, limit, "moreSpecials"); - imageLoader.lazyChildren(specialsContent); - - }); - } - - function renderCast(page, item, context, limit, isStatic) { - - var people = item.People || []; - var castContent = page.querySelector('#castContent'); - - if (enableScrollX()) { - castContent.classList.add('smoothScrollX'); - limit = 32; - } else { - castContent.classList.add('vertical-wrap'); - } - - var limitExceeded = limit && people.length > limit; - - if (limitExceeded) { - people = people.slice(0); - people.length = Math.min(limit, people.length); - } - - require(['peoplecardbuilder'], function (peoplecardbuilder) { - - peoplecardbuilder.buildPeopleCards(people, { - itemsContainer: castContent, - coverImage: true, - serverId: item.ServerId, - width: 160, - shape: getPortraitShape() - }); - }); - - var morePeopleButton = page.querySelector('.morePeople'); - if (morePeopleButton) { - if (limitExceeded && !enableScrollX()) { - morePeopleButton.classList.remove('hide'); - } else { - morePeopleButton.classList.add('hide'); - } - } - } - - function play(startPosition) { - - playbackManager.play({ - items: [currentItem], - startPositionTicks: startPosition - }); - } - - function splitVersions(page, params) { - - require(['confirm'], function (confirm) { - - confirm("Are you sure you wish to split the media sources into separate items?", "Split Media Apart").then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl("Videos/" + params.id + "/AlternateSources") - - }).then(function () { - - Dashboard.hideLoadingMsg(); - - reload(page, params); - }); - }); - }); - } - - function playTrailer(page) { - - playbackManager.playTrailers(currentItem); - } - - function showPlayMenu(item, target) { - - require(['playMenu'], function (playMenu) { - playMenu.show({ - item: item, - positionTo: target - }); - }); - } - - function playCurrentItem(button, mode) { - - var item = currentItem; - - if (item.Type === 'Program') { - - ApiClient.getLiveTvChannel(item.ChannelId, Dashboard.getCurrentUserId()).then(function (channel) { - - playbackManager.play({ - items: [channel] - }); - }); - - return; - } - - if (mode === 'playmenu') { - showPlayMenu(item, button); - } else { - playbackManager.play({ - items: [item], - startPositionTicks: item.UserData && mode === 'resume' ? item.UserData.PlaybackPositionTicks : 0 - }); - } - } - - function deleteTimer(page, params, id) { - - require(['confirm'], function (confirm) { - - confirm(globalize.translate('MessageConfirmRecordingCancellation'), globalize.translate('HeaderConfirmRecordingCancellation')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.cancelLiveTvTimer(id).then(function () { - - require(['toast'], function (toast) { - toast(globalize.translate('MessageRecordingCancelled')); - }); - - reload(page, params); - }); - }); - }); - } - - function itemDetailPage() { - - var self = this; - - self.play = play; - self.setInitialCollapsibleState = setInitialCollapsibleState; - self.renderDetails = renderDetails; - self.renderCriticReviews = renderCriticReviews; - self.renderCast = renderCast; - self.renderScenes = renderScenes; - self.renderMediaSources = renderMediaSources; - } - - window.ItemDetailPage = new itemDetailPage(); - - function onPlayClick() { - - var mode = this.getAttribute('data-mode'); - playCurrentItem(this, mode); - } - - function onInstantMixClick() { - playbackManager.instantMix(currentItem); - } - - function onShuffleClick() { - playbackManager.shuffle(currentItem); - } - - function onDeleteClick() { - - require(['deleteHelper'], function (deleteHelper) { - - deleteHelper.deleteItem({ - item: currentItem, - navigate: true - }); - }); - } - - function onCancelSeriesTimerClick() { - - require(['recordingHelper'], function (recordingHelper) { - - recordingHelper.cancelSeriesTimerWithConfirmation(currentItem.Id, currentItem.ServerId).then(function () { - Dashboard.navigate('livetv.html'); - }); - }); - } - - return function (view, params) { - - function onPlayTrailerClick() { - playTrailer(view); - } - - function onMoreCommandsClick() { - var button = this; - - itemContextMenu.show(getContextMenuOptions(currentItem, button)).then(function (result) { - - if (result.deleted) { - Emby.Page.goHome(); - - } else if (result.updated) { - reload(view, params); - } - }); - } - - var elems = view.querySelectorAll('.btnPlay'); - var i, length; - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPlayClick); - } - - view.querySelector('.btnResume').addEventListener('click', onPlayClick); - view.querySelector('.btnInstantMix').addEventListener('click', onInstantMixClick); - view.querySelector('.btnShuffle').addEventListener('click', onShuffleClick); - - elems = view.querySelectorAll('.btnPlayTrailer'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPlayTrailerClick); - } - - elems = view.querySelectorAll('.btnCancelSeriesTimer'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onCancelSeriesTimerClick); - } - - elems = view.querySelectorAll('.btnDeleteItem'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onDeleteClick); - } - - view.querySelector('.btnSplitVersions').addEventListener('click', function () { - - splitVersions(view, params); - }); - - elems = view.querySelectorAll('.btnMoreCommands'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onMoreCommandsClick); - } - - view.addEventListener('click', function (e) { - - if (dom.parentWithClass(e.target, 'moreScenes')) { - Dashboard.getCurrentUser().then(function (user) { - renderScenes(view, currentItem, user); - }); - } - else if (dom.parentWithClass(e.target, 'morePeople')) { - renderCast(view, currentItem, params.context); - } - else if (dom.parentWithClass(e.target, 'moreSpecials')) { - Dashboard.getCurrentUser().then(function (user) { - renderSpecials(view, currentItem, user); - }); - } - else if (dom.parentWithClass(e.target, 'moreCriticReviews')) { - renderCriticReviews(view, currentItem); - } - }); - - view.querySelector('.collectionItems').addEventListener('needsrefresh', function (e) { - - renderChildren(view, currentItem); - }); - - function editImages() { - return new Promise(function (resolve, reject) { - - require(['imageEditor'], function (imageEditor) { - - imageEditor.show({ - - itemId: currentItem.Id, - serverId: currentItem.ServerId - - }).then(resolve, reject); - }); - }); - } - - view.querySelector('.detailImageContainer').addEventListener('click', function (e) { - var itemDetailGalleryLink = dom.parentWithClass(e.target, 'itemDetailGalleryLink'); - if (itemDetailGalleryLink) { - editImages().then(function () { - reload(view, params); - }); - } - }); - - function onWebSocketMessage(e, data) { - - var msg = data; - - if (msg.MessageType === "UserDataChanged") { - - if (currentItem && msg.Data.UserId == Dashboard.getCurrentUserId()) { - - var key = currentItem.UserData.Key; - - var userData = msg.Data.UserDataList.filter(function (u) { - - return u.Key == key; - })[0]; - - if (userData) { - - currentItem.UserData = userData; - - Dashboard.getCurrentUser().then(function (user) { - - refreshImage(view, currentItem, user); - }); - } - } - } - - } - - view.addEventListener('viewbeforeshow', function () { - var page = this; - reload(page, params); - - events.on(ApiClient, 'websocketmessage', onWebSocketMessage); - }); - - view.addEventListener('viewbeforehide', function () { - - currentItem = null; - currentRecordingFields = null; - - events.off(ApiClient, 'websocketmessage', onWebSocketMessage); - libraryMenu.setTransparentMenu(false); - }); - - view.addEventListener('viewdestroy', function () { - - if (view.syncToggleInstance) { - view.syncToggleInstance.destroy(); - view.syncToggleInstance = null; - } - }); - }; -}); \ No newline at end of file +define(["layoutManager","cardBuilder","datetime","mediaInfo","backdrop","listView","itemContextMenu","itemHelper","userdataButtons","dom","indicators","apphost","imageLoader","libraryMenu","globalize","browser","events","scrollHelper","playbackManager","scrollStyles","emby-itemscontainer","emby-checkbox"],function(layoutManager,cardBuilder,datetime,mediaInfo,backdrop,listView,itemContextMenu,itemHelper,userdataButtons,dom,indicators,appHost,imageLoader,libraryMenu,globalize,browser,events,scrollHelper,playbackManager){"use strict";function getPromise(params){var id=params.id;if(id)return ApiClient.getItem(Dashboard.getCurrentUserId(),id);if(params.seriesTimerId)return ApiClient.getLiveTvSeriesTimer(params.seriesTimerId);var name=params.genre;if(name)return ApiClient.getGenre(name,Dashboard.getCurrentUserId());if(name=params.musicgenre)return ApiClient.getMusicGenre(name,Dashboard.getCurrentUserId());if(name=params.gamegenre)return ApiClient.getGameGenre(name,Dashboard.getCurrentUserId());if(name=params.musicartist)return ApiClient.getArtist(name,Dashboard.getCurrentUserId());throw new Error("Invalid request")}function reload(page,params){Dashboard.showLoadingMsg(),getPromise(params).then(function(item){reloadFromItem(page,params,item)})}function hideAll(page,className,show){var i,length,elems=page.querySelectorAll("."+className);for(i=0,length=elems.length;i"}function renderSeriesTimerSchedule(page,seriesTimerId){ApiClient.getLiveTvTimers({UserId:ApiClient.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",SortBy:"StartDate",EnableTotalRecordCount:!1,EnableUserData:!1,SeriesTimerId:seriesTimerId,Fields:"ChannelInfo"}).then(function(result){result.Items.length&&result.Items[0].SeriesTimerId!=seriesTimerId&&(result.Items=[]);var html=getProgramScheduleHtml(result.Items),scheduleTab=page.querySelector(".seriesTimerSchedule");scheduleTab.innerHTML=html,imageLoader.lazyChildren(scheduleTab)})}function renderSeriesTimerEditor(page,item,user){if("SeriesTimer"===item.Type){if(!user.Policy.EnableLiveTvManagement)return page.querySelector(".seriesTimerScheduleSection").classList.add("hide"),void page.querySelector(".btnCancelSeriesTimer").classList.add("hide");require(["seriesRecordingEditor"],function(seriesRecordingEditor){seriesRecordingEditor.embed(item,ApiClient.serverId(),{context:page.querySelector(".seriesRecordingEditor")})}),page.querySelector(".seriesTimerScheduleSection").classList.remove("hide"),page.querySelector(".btnCancelSeriesTimer").classList.remove("hide"),renderSeriesTimerSchedule(page,item.Id)}}function reloadFromItem(page,params,item){currentItem=item;var context=params.context;LibraryBrowser.renderName(item,page.querySelector(".itemName"),!1,context),LibraryBrowser.renderParentName(item,page.querySelector(".parentName"),context),libraryMenu.setTitle(""),Dashboard.getCurrentUser().then(function(user){window.scrollTo(0,0),renderSeriesTimerEditor(page,item,user),renderImage(page,item,user),renderLogo(page,item,ApiClient),setInitialCollapsibleState(page,item,context,user),renderDetails(page,item,context),dom.getWindowSize().innerWidth>=800?backdrop.setBackdrops([item]):backdrop.clear(),LibraryBrowser.renderDetailPageBackdrop(page,item,imageLoader),libraryMenu.setTransparentMenu(!0);var canPlay=!1;if("Program"==item.Type){var now=new Date;now>=datetime.parseISO8601Date(item.StartDate,!0)&&now0)}else hideAll(page,"btnPlay"),hideAll(page,"btnResume"),hideAll(page,"btnInstantMix"),hideAll(page,"btnShuffle");var hasAnyButton=canPlay;(item.LocalTrailerCount||item.RemoteTrailers&&item.RemoteTrailers.length)&&"Full"==item.PlayAccess?(hideAll(page,"btnPlayTrailer",!0),hasAnyButton=!0):hideAll(page,"btnPlayTrailer"),item.CanDelete&&!item.IsFolder?(hideAll(page,"btnDeleteItem",!0),hasAnyButton=!0):hideAll(page,"btnDeleteItem"),renderSyncLocalContainer(page,params,user,item),hasAnyButton||"Program"!==item.Type?hideAll(page,"mainDetailButtons",!0):hideAll(page,"mainDetailButtons"),showRecordingFields(page,item,user);var groupedVersions=(item.MediaSources||[]).filter(function(g){return"Grouping"==g.Type});user.Policy.IsAdministrator&&groupedVersions.length?page.querySelector(".splitVersionContainer").classList.remove("hide"):page.querySelector(".splitVersionContainer").classList.add("hide"),itemContextMenu.getCommands(getContextMenuOptions(item)).then(function(commands){commands.length?hideAll(page,"btnMoreCommands",!0):hideAll(page,"btnMoreCommands")});var itemBirthday=page.querySelector("#itemBirthday");if("Person"==item.Type&&item.PremiereDate)try{var birthday=datetime.parseISO8601Date(item.PremiereDate,!0).toDateString();itemBirthday.classList.remove("hide"),itemBirthday.innerHTML=globalize.translate("BirthDateValue").replace("{0}",birthday)}catch(err){itemBirthday.classList.add("hide")}else itemBirthday.classList.add("hide");var itemDeathDate=page.querySelector("#itemDeathDate");if("Person"==item.Type&&item.EndDate)try{var deathday=datetime.parseISO8601Date(item.EndDate,!0).toDateString();itemDeathDate.classList.remove("hide"),itemDeathDate.innerHTML=globalize.translate("DeathDateValue").replace("{0}",deathday)}catch(err){itemDeathDate.classList.add("hide")}var itemBirthLocation=page.querySelector("#itemBirthLocation");if("Person"==item.Type&&item.ProductionLocations&&item.ProductionLocations.length){var gmap=''+item.ProductionLocations[0]+"";itemBirthLocation.classList.remove("hide"),itemBirthLocation.innerHTML=globalize.translate("BirthPlaceValue").replace("{0}",gmap)}else itemBirthLocation.classList.add("hide")}),setPeopleHeader(page,item),page.dispatchEvent(new CustomEvent("displayingitem",{detail:{item:item,context:context},bubbles:!0})),Dashboard.hideLoadingMsg()}function logoImageUrl(item,apiClient,options){return options=options||{},options.type="Logo",item.ImageTags&&item.ImageTags.Logo?(options.tag=item.ImageTags.Logo,apiClient.getScaledImageUrl(item.Id,options)):item.ParentLogoImageTag?(options.tag=item.ParentLogoImageTag,apiClient.getScaledImageUrl(item.ParentLogoItemId,options)):null}function renderLogo(page,item,apiClient){var url=logoImageUrl(item,apiClient,{maxWidth:300}),detailLogo=page.querySelector(".detailLogo");url?(detailLogo.classList.remove("hide"),detailLogo.classList.add("lazy"),detailLogo.setAttribute("data-src",url),imageLoader.lazyImage(detailLogo)):detailLogo.classList.add("hide")}function showRecordingFields(page,item,user){if(!currentRecordingFields){var recordingFieldsElement=page.querySelector(".recordingFields");"Program"==item.Type&&user.Policy.EnableLiveTvManagement?require(["recordingFields"],function(recordingFields){currentRecordingFields=new recordingFields({parent:recordingFieldsElement,programId:item.Id,serverId:item.ServerId}),recordingFieldsElement.classList.remove("hide")}):(recordingFieldsElement.classList.add("hide"),recordingFieldsElement.innerHTML="")}}function renderLinks(linksElem,item){var links=[];if(item.HomePageUrl&&links.push(''+globalize.translate("ButtonWebsite")+""),item.ExternalUrls)for(var i=0,length=item.ExternalUrls.length;i'+url.Name+"")}if(links.length){var html=links.join('');linksElem.innerHTML=html,linksElem.classList.remove("hide")}else linksElem.classList.add("hide")}function renderImage(page,item,user){var container=page.querySelector(".detailImageContainer");LibraryBrowser.renderDetailImage(container,item,user.Policy.IsAdministrator&&"Photo"!=item.MediaType,null,imageLoader,indicators)}function refreshDetailImageUserData(elem,item){var detailImageProgressContainer=elem.querySelector(".detailImageProgressContainer");detailImageProgressContainer.innerHTML=indicators.getProgressBarHtml(item)}function refreshImage(page,item,user){refreshDetailImageUserData(page.querySelector(".detailImageContainer"),item)}function setPeopleHeader(page,item){"Audio"==item.MediaType||"MusicAlbum"==item.Type||"Book"==item.MediaType||"Photo"==item.MediaType?page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderPeople"):page.querySelector("#peopleHeader").innerHTML=globalize.translate("HeaderCastAndCrew")}function renderNextUp(page,item,user){var section=page.querySelector(".nextUpSection");return"Series"!=item.Type?void section.classList.add("hide"):void ApiClient.getNextUpEpisodes({SeriesId:item.Id,UserId:user.Id}).then(function(result){result.Items.length?section.classList.remove("hide"):section.classList.add("hide");var html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(!1),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,overlayText:!0,lazy:!0,overlayPlayButton:!0}),itemsContainer=section.querySelector(".nextUpItems");itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer)})}function setInitialCollapsibleState(page,item,context,user){page.querySelector(".collectionItems").innerHTML="","TvChannel"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderChannelGuide(page,item,user)):"Playlist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderPlaylistItems(page,item,user)):"Studio"==item.Type||"Person"==item.Type||"Genre"==item.Type||"MusicGenre"==item.Type||"GameGenre"==item.Type||"MusicArtist"==item.Type?(page.querySelector("#childrenCollapsible").classList.remove("hide"),renderItemsByName(page,item,user)):item.IsFolder||"Episode"==item.Type?("BoxSet"==item.Type&&page.querySelector("#childrenCollapsible").classList.add("hide"),renderChildren(page,item)):page.querySelector("#childrenCollapsible").classList.add("hide"),"Series"==item.Type&&renderSeriesSchedule(page,item,user),"Series"==item.Type?renderNextUp(page,item,user):page.querySelector(".nextUpSection").classList.add("hide"),item.MediaSources&&item.MediaSources.length&&renderMediaSources(page,user,item),renderScenes(page,item),item.SpecialFeatureCount&&0!=item.SpecialFeatureCount&&"Series"!=item.Type?(page.querySelector("#specialsCollapsible").classList.remove("hide"),renderSpecials(page,item,user,6)):page.querySelector("#specialsCollapsible").classList.add("hide"),item.People&&item.People.length?(page.querySelector("#castCollapsible").classList.remove("hide"),renderCast(page,item,context,enableScrollX()?null:12)):page.querySelector("#castCollapsible").classList.add("hide"),item.PartCount&&item.PartCount>1?(page.querySelector("#additionalPartsCollapsible").classList.remove("hide"),renderAdditionalParts(page,item,user)):page.querySelector("#additionalPartsCollapsible").classList.add("hide"),page.querySelector("#themeSongsCollapsible").classList.add("hide"),page.querySelector("#themeVideosCollapsible").classList.add("hide"),"MusicAlbum"==item.Type?renderMusicVideos(page,item,user):page.querySelector("#musicVideosCollapsible").classList.add("hide"),renderThemeMedia(page,item,user),enableScrollX()?renderCriticReviews(page,item):renderCriticReviews(page,item,1)}function renderOverview(elems,item){for(var i=0,length=elems.length;i'+text+"
":'
'+text+"
"}).join("");return view.querySelector(".mediaInfoIcons").innerHTML=html,html}function renderPhotoInfo(page,item){var html="",attributes=[];if(item.CameraMake&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraMake"),item.CameraMake)),item.CameraModel&&attributes.push(createAttribute(globalize.translate("MediaInfoCameraModel"),item.CameraModel)),item.Altitude&&attributes.push(createAttribute(globalize.translate("MediaInfoAltitude"),item.Altitude.toFixed(1))),item.Aperture&&attributes.push(createAttribute(globalize.translate("MediaInfoAperture"),"F"+item.Aperture.toFixed(1))),item.ExposureTime){var val=1/item.ExposureTime;attributes.push(createAttribute(globalize.translate("MediaInfoExposureTime"),"1/"+val+" s"))}item.FocalLength&&attributes.push(createAttribute(globalize.translate("MediaInfoFocalLength"),item.FocalLength.toFixed(1)+" mm")),item.ImageOrientation,item.IsoSpeedRating&&attributes.push(createAttribute(globalize.translate("MediaInfoIsoSpeedRating"),item.IsoSpeedRating)),item.Latitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLatitude"),item.Latitude.toFixed(1))),item.Longitude&&attributes.push(createAttribute(globalize.translate("MediaInfoLongitude"),item.Longitude.toFixed(1))),item.ShutterSpeed&&attributes.push(createAttribute(globalize.translate("MediaInfoShutterSpeed"),item.ShutterSpeed)),item.Software&&attributes.push(createAttribute(globalize.translate("MediaInfoSoftware"),item.Software)),html+=attributes.join("
"),page.querySelector(".photoInfoContent").innerHTML=html}function getArtistLinksHtml(artists,context){for(var html=[],i=0,length=artists.length;i'+artist.Name+"")}return html=html.join(" / "),1==artists.length?globalize.translate("ValueArtist",html):artists.length>1?globalize.translate("ValueArtists",html):html}function enableScrollX(){return browserInfo.mobile&&screen.availWidth<=1e3}function getPortraitShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowPortrait":"portrait"}function getSquareShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowSquare":"square"}function getThumbShape(scrollX){return null==scrollX&&(scrollX=enableScrollX()),scrollX?"overflowBackdrop":"backdrop"}function renderMoreFromItems(page,item){var moreFromSection=page.querySelector("#moreFromSection");if(moreFromSection)return"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length?void ApiClient.getItems(Dashboard.getCurrentUserId(),{IncludeItemTypes:"MusicAlbum",ArtistIds:item.AlbumArtists[0].Id,Recursive:!0,ExcludeItemIds:item.Id}).then(function(result){if(!result.Items.length)return void moreFromSection.classList.add("hide");moreFromSection.classList.remove("hide"),moreFromSection.querySelector(".moreFromHeader").innerHTML=globalize.translate("MoreFromValue",item.AlbumArtists[0].Name);var html="";html+=enableScrollX()?'
':'
';var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!supportsImageAnalysis,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
";var similarContent=page.querySelector("#moreFromItems");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)}):void moreFromSection.classList.add("hide")}function renderSimilarItems(page,item,context){var similarCollapsible=page.querySelector("#similarCollapsible");if(similarCollapsible){if("Movie"!=item.Type&&"Trailer"!=item.Type&&"Series"!=item.Type&&"Program"!=item.Type&&"Recording"!=item.Type&&"Game"!=item.Type&&"MusicAlbum"!=item.Type&&"MusicArtist"!=item.Type&&"ChannelVideoItem"!=item.Type)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var shape="MusicAlbum"==item.Type||"MusicArtist"==item.Type?getSquareShape():getPortraitShape(),options={userId:Dashboard.getCurrentUserId(),limit:"MusicAlbum"==item.Type||"MusicArtist"==item.Type?8:10,fields:"PrimaryImageAspectRatio,UserData,CanDelete"};"MusicAlbum"==item.Type&&item.AlbumArtists&&item.AlbumArtists.length&&(options.ExcludeArtistIds=item.AlbumArtists[0].Id),enableScrollX()&&(options.limit=12),ApiClient.getSimilarItems(item.Id,options).then(function(result){if(!result.Items.length)return void similarCollapsible.classList.add("hide");similarCollapsible.classList.remove("hide");var html="";html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis&&("MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type);html+=cardBuilder.getCardsHtml({items:result.Items,shape:shape,showParentTitle:"MusicAlbum"==item.Type,centerText:!cardLayout,showTitle:"MusicAlbum"==item.Type||"Game"==item.Type||"MusicArtist"==item.Type,context:context,lazy:!0,showDetailsMenu:!0,coverImage:"MusicAlbum"==item.Type||"MusicArtist"==item.Type,overlayPlayButton:!0,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis}),html+="
";var similarContent=similarCollapsible.querySelector(".similarContent");similarContent.innerHTML=html,imageLoader.lazyChildren(similarContent)})}}function renderSeriesAirTime(page,item,isStatic){var seriesAirTime=page.querySelector("#seriesAirTime");if("Series"!=item.Type)return void seriesAirTime.classList.add("hide");var html="";if(item.AirDays&&item.AirDays.length&&(html+=7==item.AirDays.length?"daily":item.AirDays.map(function(a){return a+"s"}).join(",")),item.AirTime&&(html+=" at "+item.AirTime),item.Studios.length)if(isStatic)html+=" on "+item.Studios[0].Name;else{var context=inferContext(item),href=LibraryBrowser.getHref(item.Studios[0],context);html+=' on '+item.Studios[0].Name+""}html?(html=("Ended"==item.Status?"Aired ":"Airs ")+html,seriesAirTime.innerHTML=html,seriesAirTime.classList.remove("hide")):seriesAirTime.classList.add("hide")}function renderTags(page,item){var itemTags=page.querySelector(".itemTags");if(item.Tags&&item.Tags.length){for(var html="",i=0,length=item.Tags.length;i'+item.Tags[i]+"
";itemTags.innerHTML=html,itemTags.classList.remove("hide")}else itemTags.classList.add("hide")}function getEpisodesFunction(seriesId,query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getEpisodes(seriesId,query)}}function getAlbumSongsFunction(query){return query=Object.assign({},query),function(index,limit,fields){return query.StartIndex=index,query.Limit=limit,query.Fields=fields,ApiClient.getItems(Dashboard.getCurrentUserId(),query)}}function renderChildren(page,item){_childrenItemsFunction=null;var fields="ItemCounts,AudioInfo,PrimaryImageAspectRatio,BasicSyncInfo,CanDelete",query={ParentId:item.Id,Fields:fields};"BoxSet"!==item.Type&&(query.SortBy="SortName");var promise,userId=Dashboard.getCurrentUserId();"Series"==item.Type?promise=ApiClient.getSeasons(item.Id,{userId:userId,Fields:fields}):"Season"==item.Type?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.Id,userId:userId,Fields:fields})):"Episode"==item.Type&&item.SeriesId&&item.SeasonId?(promise=ApiClient.getEpisodes(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields}),_childrenItemsFunction=getEpisodesFunction(item.SeriesId,{seasonId:item.SeasonId,userId:userId,Fields:fields})):"MusicAlbum"==item.Type&&(_childrenItemsFunction=getAlbumSongsFunction(query)),promise=promise||ApiClient.getItems(Dashboard.getCurrentUserId(),query),promise.then(function(result){var html="",scrollX=!1,isList=!1,scrollClass="hiddenScrollX",childrenItemsContainer=page.querySelector(".childrenItemsContainer");if("MusicAlbum"==item.Type)html=listView.getListViewHtml({items:result.Items,smallIcon:!0,showIndex:!0,index:"disc",showIndexNumber:!0,playFromHere:!0,action:"playallfromhere",image:!1,artist:"auto",containerAlbumArtist:item.AlbumArtist,addToListButton:!0}),isList=!0;else if("Series"==item.Type)scrollX=enableScrollX(),html=cardBuilder.getCardsHtml({items:result.Items,shape:getPortraitShape(),showTitle:!0,centerText:!0,lazy:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX});else if("Season"==item.Type||"Episode"==item.Type){if("Episode"===item.Type&&childrenItemsContainer.classList.add("darkScroller"),scrollX="Episode"==item.Type,browser.touch||(scrollClass="smoothScrollX"),1==result.Items.length&&"Episode"===item.Type)return;html=cardBuilder.getCardsHtml({items:result.Items,shape:getThumbShape(scrollX),showTitle:!0,displayAsSpecial:"Season"==item.Type&&item.IndexNumber,playFromHere:!0,overlayText:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0,allowBottomPadding:!scrollX,includeParentInfoInTitle:!1})}else"GameSystem"==item.Type&&(html=cardBuilder.getCardsHtml({items:result.Items,shape:"auto",showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0}));if(page.querySelector("#childrenCollapsible").classList.remove("hide"),scrollX?(childrenItemsContainer.classList.add(scrollClass),childrenItemsContainer.classList.remove("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list")):(childrenItemsContainer.classList.remove("hiddenScrollX"),childrenItemsContainer.classList.remove("smoothScrollX"),isList?(childrenItemsContainer.classList.add("vertical-list"),childrenItemsContainer.classList.remove("vertical-wrap")):(childrenItemsContainer.classList.add("vertical-wrap"),childrenItemsContainer.classList.remove("vertical-list"))),childrenItemsContainer.innerHTML=html,imageLoader.lazyChildren(childrenItemsContainer),"BoxSet"==item.Type){var collectionItemTypes=[{name:globalize.translate("HeaderMovies"),type:"Movie"},{name:globalize.translate("HeaderSeries"),type:"Series"},{name:globalize.translate("HeaderAlbums"),type:"MusicAlbum"},{name:globalize.translate("HeaderGames"),type:"Game"},{name:globalize.translate("HeaderBooks"),type:"Book"}];renderCollectionItems(page,item,collectionItemTypes,result.Items)}else if("Episode"===item.Type){var card=childrenItemsContainer.querySelector('.card[data-id="'+item.Id+'"]');card&&scrollHelper.toStart(childrenItemsContainer,card.previousSibling||card,!0)}}),"Season"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderEpisodes"):"Episode"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("MoreFromValue",item.SeasonName):"Series"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderSeasons"):"MusicAlbum"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderTracks"):"GameSystem"==item.Type?page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderGames"):page.querySelector("#childrenTitle").innerHTML=globalize.translate("HeaderItems"),"MusicAlbum"==item.Type?page.querySelector(".childrenSectionHeader",page).classList.add("hide"):page.querySelector(".childrenSectionHeader",page).classList.remove("hide")}function renderItemsByName(page,item,user){require("scripts/itembynamedetailpage".split(","),function(){window.ItemsByName.renderItems(page,item)})}function renderPlaylistItems(page,item,user){require("scripts/playlistedit".split(","),function(){PlaylistViewer.render(page,item)})}function renderChannelGuide(page,item,user){require("scripts/livetvchannel,scripts/livetvcomponents,livetvcss".split(","),function(liveTvChannelPage){liveTvChannelPage.renderPrograms(page,item.Id)})}function renderSeriesSchedule(page,item,user){}function inferContext(item){return"Movie"==item.Type||"BoxSet"==item.Type?"movies":"Series"==item.Type||"Season"==item.Type||"Episode"==item.Type?"tvshows":"Game"==item.Type||"GameSystem"==item.Type?"games":"Game"==item.Type||"GameSystem"==item.Type?"games":"MusicArtist"==item.Type||"MusicAlbum"==item.Type?"music":null}function renderStudios(elem,item,isStatic){var context=inferContext(item);if(item.Studios&&item.Studios.length&&"Series"!=item.Type,1)elem.classList.add("hide");else{for(var html="",i=0,length=item.Studios.length;i0&&(html+="  /  "),isStatic)html+=item.Studios[i].Name;else{item.Studios[i].Type="Studio";var href=LibraryBrowser.getHref(item.Studios[i],context);html+=''+item.Studios[i].Name+""}var translationKey=item.Studios.length>1?"ValueStudios":"ValueStudio";html=globalize.translate(translationKey,html),elem.innerHTML=html,elem.classList.remove("hide")}}function renderGenres(elem,item,limit,isStatic){for(var context=inferContext(item),html="",genres=item.Genres||[],i=0,length=genres.length;i=limit);i++){i>0&&(html+='');var param="Audio"==item.Type||"MusicArtist"==item.Type||"MusicAlbum"==item.Type?"musicgenre":"genre";if("Game"==item.MediaType&&(param="gamegenre"),isStatic)html+=genres[i];else{var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;case"music":type="MusicAlbum";break;default:type="Movie"}var url="secondaryitems.html?type="+type+"&"+param+"="+ApiClient.encodeName(genres[i]);html+=''+genres[i]+""}}elem.innerHTML=html}function renderAwardSummary(elem,item){item.AwardSummary?(elem.classList.remove("hide"),elem.innerHTML=globalize.translate("ValueAwards",item.AwardSummary)):elem.classList.add("hide")}function renderCollectionItems(page,parentItem,types,items){page.querySelector(".collectionItems").innerHTML="";var i,length;for(i=0,length=types.length;i",html+="",html+='',html+="
",html+='
';var shape="MusicAlbum"==type.type?getSquareShape(!1):getPortraitShape(!1);html+=cardBuilder.getCardsHtml({items:items,shape:shape,showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0,overlayMoreButton:!0,showAddToCollection:!1,showRemoveFromCollection:!0,collectionId:parentItem.Id}),html+="
",html+="
";var collectionItems=page.querySelector(".collectionItems");collectionItems.insertAdjacentHTML("beforeend",html), +imageLoader.lazyChildren(collectionItems),collectionItems.querySelector(".btnAddToCollection").addEventListener("click",function(){require(["alert"],function(alert){alert({text:globalize.translate("AddItemToCollectionHelp"),html:globalize.translate("AddItemToCollectionHelp")+'

'+globalize.translate("ButtonLearnMore")+""})})})}function renderUserDataIcons(page,item){for(var userDataIcons=page.querySelectorAll(".userDataIcons"),i=0,length=userDataIcons.length;i',html+='
',null!=review.Score||null!=review.Likes&&(html+=review.Likes?"
":"
"),html+='
',html+='

'+review.Caption+"

";var vals=[];if(review.ReviewerName&&vals.push(review.ReviewerName),review.Publisher&&vals.push(review.Publisher),html+='
'+vals.join(", ")+".",review.Date)try{var date=datetime.toLocaleDateString(datetime.parseISO8601Date(review.Date,!0));html+=''+date+""}catch(error){}html+="
",review.Url&&(html+='"),html+="
",html+="
",html+=""}limit&&result.TotalRecordCount>limit&&(html+='

");var criticReviewsContent=page.querySelector("#criticReviewsContent");criticReviewsContent.innerHTML=html,enableScrollX()?criticReviewsContent.classList.add("hiddenScrollX"):criticReviewsContent.classList.remove("hiddenScrollX")}function renderThemeMedia(page,item){"SeriesTimer"!==item.Type&&"Timer"!==item.Type&&"Genre"!==item.Type&&"MusicGenre"!==item.Type&&"GameGenre"!==item.Type&&"Studio"!==item.Type&&"Person"!==item.Type&&ApiClient.getThemeMedia(Dashboard.getCurrentUserId(),item.Id,!0).then(function(result){var themeSongs=result.ThemeSongsResult.OwnerId==item.Id?result.ThemeSongsResult.Items:[],themeVideos=result.ThemeVideosResult.OwnerId==item.Id?result.ThemeVideosResult.Items:[];renderThemeSongs(page,themeSongs),renderThemeVideos(page,themeVideos)})}function renderThemeSongs(page,items){if(items.length){page.querySelector("#themeSongsCollapsible").classList.remove("hide");var html=listView.getListViewHtml({items:items});page.querySelector("#themeSongsContent").innerHTML=html}else page.querySelector("#themeSongsCollapsible").classList.add("hide")}function renderThemeVideos(page,items,user){if(items.length){page.querySelector("#themeVideosCollapsible").classList.remove("hide");var themeVideosContent=page.querySelector("#themeVideosContent");themeVideosContent.innerHTML=getVideosHtml(items,user),imageLoader.lazyChildren(themeVideosContent)}else page.querySelector("#themeVideosCollapsible").classList.add("hide")}function renderMusicVideos(page,item,user){ApiClient.getItems(user.Id,{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"MusicVideo",Recursive:!0,Fields:"DateCreated,CanDelete",Albums:item.Name}).then(function(result){if(result.Items.length){page.querySelector("#musicVideosCollapsible").classList.remove("hide");var musicVideosContent=page.querySelector(".musicVideosContent");musicVideosContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(musicVideosContent)}else page.querySelector("#musicVideosCollapsible").classList.add("hide")})}function renderAdditionalParts(page,item,user){ApiClient.getAdditionalVideoParts(user.Id,item.Id).then(function(result){if(result.Items.length){page.querySelector("#additionalPartsCollapsible").classList.remove("hide");var additionalPartsContent=page.querySelector("#additionalPartsContent");additionalPartsContent.innerHTML=getVideosHtml(result.Items,user),imageLoader.lazyChildren(additionalPartsContent)}else page.querySelector("#additionalPartsCollapsible").classList.add("hide")})}function renderScenes(page,item){var chapters=item.Chapters||[];if(chapters.length&&!chapters[0].ImageTag&&(chapters=[]),chapters.length){page.querySelector("#scenesCollapsible").classList.remove("hide");var scenesContent=page.querySelector("#scenesContent");enableScrollX()?scenesContent.classList.add("smoothScrollX"):scenesContent.classList.add("vertical-wrap"),require(["chaptercardbuilder"],function(chaptercardbuilder){chaptercardbuilder.buildChapterCards(item,chapters,{itemsContainer:scenesContent,coverImage:!0,width:400,backdropShape:getThumbShape(),squareShape:getSquareShape()})})}else page.querySelector("#scenesCollapsible").classList.add("hide")}function renderMediaSources(page,user,item){var html=item.MediaSources.map(function(v){return getMediaSourceHtml(user,item,v)}).join('
');item.MediaSources.length>1&&(html="
"+html);var mediaInfoContent=page.querySelector("#mediaInfoContent");mediaInfoContent.innerHTML=html}function getMediaSourceHtml(user,item,version){var html="";version.Name&&item.MediaSources.length>1&&(html+='
'+version.Name+"

");for(var i=0,length=version.MediaStreams.length;i';var displayType=globalize.translate("MediaInfoStreamType"+stream.Type);html+='

'+displayType+"

";var attributes=[];stream.Language&&"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoLanguage"),stream.Language)),stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoCodec"),stream.Codec.toUpperCase())),stream.CodecTag&&attributes.push(createAttribute(globalize.translate("MediaInfoCodecTag"),stream.CodecTag)),null!=stream.IsAVC&&attributes.push(createAttribute("AVC",stream.IsAVC?"Yes":"No")),stream.Profile&&attributes.push(createAttribute(globalize.translate("MediaInfoProfile"),stream.Profile)),stream.Level&&attributes.push(createAttribute(globalize.translate("MediaInfoLevel"),stream.Level)),(stream.Width||stream.Height)&&attributes.push(createAttribute(globalize.translate("MediaInfoResolution"),stream.Width+"x"+stream.Height)),stream.AspectRatio&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoAspectRatio"),stream.AspectRatio)),"Video"==stream.Type&&(null!=stream.IsAnamorphic&&attributes.push(createAttribute(globalize.translate("MediaInfoAnamorphic"),stream.IsAnamorphic?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoInterlaced"),stream.IsInterlaced?"Yes":"No"))),(stream.AverageFrameRate||stream.RealFrameRate)&&attributes.push(createAttribute(globalize.translate("MediaInfoFramerate"),stream.AverageFrameRate||stream.RealFrameRate)),stream.ChannelLayout&&attributes.push(createAttribute(globalize.translate("MediaInfoLayout"),stream.ChannelLayout)),stream.Channels&&attributes.push(createAttribute(globalize.translate("MediaInfoChannels"),stream.Channels+" ch")),stream.BitRate&&"mjpeg"!=stream.Codec&&attributes.push(createAttribute(globalize.translate("MediaInfoBitrate"),parseInt(stream.BitRate/1e3)+" kbps")),stream.SampleRate&&attributes.push(createAttribute(globalize.translate("MediaInfoSampleRate"),stream.SampleRate+" Hz")),stream.BitDepth&&attributes.push(createAttribute(globalize.translate("MediaInfoBitDepth"),stream.BitDepth+" bit")),stream.PixelFormat&&attributes.push(createAttribute(globalize.translate("MediaInfoPixelFormat"),stream.PixelFormat)),stream.RefFrames&&attributes.push(createAttribute(globalize.translate("MediaInfoRefFrames"),stream.RefFrames)),stream.NalLengthSize&&attributes.push(createAttribute("NAL",stream.NalLengthSize)),"Video"!=stream.Type&&attributes.push(createAttribute(globalize.translate("MediaInfoDefault"),stream.IsDefault?"Yes":"No")),"Subtitle"==stream.Type&&(attributes.push(createAttribute(globalize.translate("MediaInfoForced"),stream.IsForced?"Yes":"No")),attributes.push(createAttribute(globalize.translate("MediaInfoExternal"),stream.IsExternal?"Yes":"No"))),"Video"==stream.Type&&version.Timestamp&&attributes.push(createAttribute(globalize.translate("MediaInfoTimestamp"),version.Timestamp)),stream.DisplayTitle&&attributes.push(createAttribute("Title",stream.DisplayTitle)),html+=attributes.join("
"),html+=""}}if(version.Container&&(html+='
'+globalize.translate("MediaInfoContainer")+''+version.Container+"
"),version.Formats&&version.Formats.length,version.Path&&"Http"!=version.Protocol&&user&&user.Policy.IsAdministrator&&(html+='
'+globalize.translate("MediaInfoPath")+''+version.Path+"
"),version.Size){var size=(version.Size/1048576).toFixed(0);html+='
'+globalize.translate("MediaInfoSize")+''+size+" MB
"}return html}function createAttribute(label,value){return''+label+''+value+""}function getVideosHtml(items,user,limit,moreButtonClass){var html=cardBuilder.getCardsHtml({items:items,shape:"auto",showTitle:!0,action:"play",overlayText:!0,showRuntime:!0});return limit&&items.length>limit&&(html+='

"),html}function renderSpecials(page,item,user,limit){ApiClient.getSpecialFeatures(user.Id,item.Id).then(function(specials){var specialsContent=page.querySelector("#specialsContent");specialsContent.innerHTML=getVideosHtml(specials,user,limit,"moreSpecials"),imageLoader.lazyChildren(specialsContent)})}function renderCast(page,item,context,limit,isStatic){var people=item.People||[],castContent=page.querySelector("#castContent");enableScrollX()?(castContent.classList.add("smoothScrollX"),limit=32):castContent.classList.add("vertical-wrap");var limitExceeded=limit&&people.length>limit;limitExceeded&&(people=people.slice(0),people.length=Math.min(limit,people.length)),require(["peoplecardbuilder"],function(peoplecardbuilder){peoplecardbuilder.buildPeopleCards(people,{itemsContainer:castContent,coverImage:!0,serverId:item.ServerId,width:160,shape:getPortraitShape()})});var morePeopleButton=page.querySelector(".morePeople");morePeopleButton&&(limitExceeded&&!enableScrollX()?morePeopleButton.classList.remove("hide"):morePeopleButton.classList.add("hide"))}function play(startPosition){playbackManager.play({items:[currentItem],startPositionTicks:startPosition})}function splitVersions(page,params){require(["confirm"],function(confirm){confirm("Are you sure you wish to split the media sources into separate items?","Split Media Apart").then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Videos/"+params.id+"/AlternateSources")}).then(function(){Dashboard.hideLoadingMsg(),reload(page,params)})})})}function playTrailer(page){playbackManager.playTrailers(currentItem)}function showPlayMenu(item,target){require(["playMenu"],function(playMenu){playMenu.show({item:item,positionTo:target})})}function playCurrentItem(button,mode){var item=currentItem;return"Program"===item.Type?void ApiClient.getLiveTvChannel(item.ChannelId,Dashboard.getCurrentUserId()).then(function(channel){playbackManager.play({items:[channel]})}):void("playmenu"===mode?showPlayMenu(item,button):playbackManager.play({items:[item],startPositionTicks:item.UserData&&"resume"===mode?item.UserData.PlaybackPositionTicks:0}))}function itemDetailPage(){var self=this;self.play=play,self.setInitialCollapsibleState=setInitialCollapsibleState,self.renderDetails=renderDetails,self.renderCriticReviews=renderCriticReviews,self.renderCast=renderCast,self.renderScenes=renderScenes,self.renderMediaSources=renderMediaSources}function onPlayClick(){var mode=this.getAttribute("data-mode");playCurrentItem(this,mode)}function onInstantMixClick(){playbackManager.instantMix(currentItem)}function onShuffleClick(){playbackManager.shuffle(currentItem)}function onDeleteClick(){require(["deleteHelper"],function(deleteHelper){deleteHelper.deleteItem({item:currentItem,navigate:!0})})}function onCancelSeriesTimerClick(){require(["recordingHelper"],function(recordingHelper){recordingHelper.cancelSeriesTimerWithConfirmation(currentItem.Id,currentItem.ServerId).then(function(){Dashboard.navigate("livetv.html")})})}var currentItem,currentRecordingFields,_childrenItemsFunction=null;return window.ItemDetailPage=new itemDetailPage,function(view,params){function onPlayTrailerClick(){playTrailer(view)}function onMoreCommandsClick(){var button=this;itemContextMenu.show(getContextMenuOptions(currentItem,button)).then(function(result){result.deleted?Emby.Page.goHome():result.updated&&reload(view,params)})}function editImages(){return new Promise(function(resolve,reject){require(["imageEditor"],function(imageEditor){imageEditor.show({itemId:currentItem.Id,serverId:currentItem.ServerId}).then(resolve,reject)})})}function onWebSocketMessage(e,data){var msg=data;if("UserDataChanged"===msg.MessageType&¤tItem&&msg.Data.UserId==Dashboard.getCurrentUserId()){var key=currentItem.UserData.Key,userData=msg.Data.UserDataList.filter(function(u){return u.Key==key})[0];userData&&(currentItem.UserData=userData,Dashboard.getCurrentUser().then(function(user){refreshImage(view,currentItem,user)}))}}var i,length,elems=view.querySelectorAll(".btnPlay");for(i=0,length=elems.length;i'; - } - } else { - view.querySelector('.btnNewCollection').classList.add('hide'); - } - - var elem = view.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - var i, length; - var elems = view.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(view); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(view); - } - - elems = view.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = view.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - libraryBrowser.saveQueryValues(params.parentId, query); - - var name = item.Name; - - if (item.IndexNumber != null) { - name = item.IndexNumber + " - " + name; - } - if (item.ParentIndexNumber != null) { - name = item.ParentIndexNumber + "." + name; - } - - LibraryMenu.setTitle(name); - - view.dispatchEvent(new CustomEvent("displayingitem", { - detail: { - item: item - }, - bubbles: true - })); - - Dashboard.hideLoadingMsg(); - }); - } - - function showFilterMenu() { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery() - }); - - Events.on(filterDialog, 'filterchange', function () { - reloadItems(); - }); - - filterDialog.show(); - }); - } - - var alphaPickerElement = view.querySelector('.alphaPicker'); - alphaPickerElement.addEventListener('alphavaluechanged', function (e) { - var newValue = e.detail.value; - var query = getQuery(); - query.NameStartsWithOrGreater = newValue; - query.StartIndex = 0; - reloadItems(view); - }); - - self.alphaPicker = new alphaPicker({ - element: alphaPickerElement, - valueChangeEvent: 'click' - }); - - function updateFilterControls() { - - var query = getQuery(); - - self.alphaPicker.value(query.NameStartsWithOrGreater); - } - - var btnSelectView = view.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, getPageData().view, 'List,Poster,PosterCard,Thumb'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - var layout = e.detail.viewStyle; - getPageData().view = layout; - libraryBrowser.saveViewSetting(getSavedQueryKey(), layout); - onViewStyleChange(); - reloadItems(view); - }); - - onViewStyleChange(); - - view.querySelector('.btnFilter').addEventListener('click', function () { - showFilterMenu(); - }); - - // On callback make sure to set StartIndex = 0 - view.querySelector('.btnSort').addEventListener('click', function () { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'IsFolder,SortName' - }, - { - name: Globalize.translate('OptionCommunityRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionCriticRating'), - id: 'CriticRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionDatePlayed'), - id: 'DatePlayed,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SortName' - }, - { - name: Globalize.translate('OptionPlayCount'), - id: 'PlayCount,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'PremiereDate,SortName' - }, - { - name: Globalize.translate('OptionRuntime'), - id: 'Runtime,SortName' - }], - callback: function () { - reloadItems(view); - }, - query: getQuery() - }); - }); - - // The button is created dynamically - view.querySelector('.btnNewCollection').addEventListener('click', function () { - - require(['collectionEditor'], function (collectionEditor) { - - var serverId = ApiClient.serverInfo().Id; - new collectionEditor().show({ - items: [], - serverId: serverId - }); - - }); - }); - - view.addEventListener('viewbeforeshow', function (e) { - reloadItems(view); - updateFilterControls(); - }); - - view.addEventListener('viewdestroy', function (e) { - if (self.alphaPicker) { - self.alphaPicker.destroy(); - } - }); - }; -}); \ No newline at end of file +define(["libraryBrowser","alphaPicker","listView","cardBuilder","imageLoader","emby-itemscontainer"],function(libraryBrowser,alphaPicker,listView,cardBuilder,imageLoader){"use strict";return function(view,params){function getPageData(){var pageData=data;if(!pageData){pageData=data={query:{SortBy:"IsFolder,SortName",SortOrder:"Ascending",Fields:"DateCreated,PrimaryImageAspectRatio,MediaSourceCount",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:libraryBrowser.getDefaultPageSize()}},pageData.query.Filters="",pageData.query.NameStartsWithOrGreater="";var key=getSavedQueryKey();pageData.view=libraryBrowser.getSavedView(key)||"Poster",pageData.query.ParentId=params.parentId||null,libraryBrowser.loadSavedQueryValues(key,pageData.query)}return pageData}function getQuery(){return getPageData().query}function getSavedQueryKey(){return view.savedQueryKey||(view.savedQueryKey=libraryBrowser.getSavedQueryKey("itemsv1")),view.savedQueryKey}function onViewStyleChange(){var viewStyle=getPageData(view).view,itemsContainer=view.querySelector("#items");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap"),itemsContainer.classList.add("centered")),itemsContainer.innerHTML=""}function reloadItems(){Dashboard.showLoadingMsg();var query=getQuery(),userId=Dashboard.getCurrentUserId(),parentItemPromise=query.ParentId?ApiClient.getItem(userId,query.ParentId):ApiClient.getRootFolder(userId),itemsPromise=ApiClient.getItems(userId,query);Promise.all([parentItemPromise,itemsPromise]).then(function(responses){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(view)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(view)}var item=responses[0];currentItem=item;var result=responses[1];window.scrollTo(0,0);var viewStyle=getPageData(view).view,html="",pagingHtml=libraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,addLayoutButton:!1,currentLayout:viewStyle,sortButton:!1,filterButton:!1});updateFilterControls();var context=params.context,posterOptions={items:result.Items,shape:"auto",centerText:!0,lazy:!0,coverImage:"PhotoAlbum"==item.Type,context:"folders"};"PosterCard"==viewStyle?(posterOptions.showTitle=!0,posterOptions.showYear=!0,posterOptions.cardLayout=!0,posterOptions.centerText=!1,posterOptions.vibrant=!0,html=cardBuilder.getCardsHtml(posterOptions)):"List"==viewStyle?html=listView.getListViewHtml({items:result.Items,sortBy:query.SortBy}):"Thumb"==viewStyle?(posterOptions.preferThumb=!0,posterOptions.showTitle=!0,posterOptions.shape="backdrop",posterOptions.centerText=!0,posterOptions.overlayText=!1,posterOptions.overlayMoreButton=!0,html=cardBuilder.getCardsHtml(posterOptions)):(posterOptions.showTitle="photos"!=context||"auto",posterOptions.overlayText="photos"==context,posterOptions.overlayMoreButton=!0,html=cardBuilder.getCardsHtml(posterOptions)),"boxsets"==currentItem.CollectionType?(view.querySelector(".btnNewCollection").classList.remove("hide"),result.Items.length||(html='

'+Globalize.translate("MessageNoCollectionsAvailable")+"

")):view.querySelector(".btnNewCollection").classList.add("hide");var elem=view.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem);var i,length,elems=view.querySelectorAll(".paging");for(i=0,length=elems.length;i 0) { - tabs.selectedIndex(selected - 1); - } - } - }; - - require(['hammer-main'], function (hammertime) { - - hammertime.on('swipeleft', onSwipeLeft); - hammertime.on('swiperight', onSwipeRight); - - ownerpage.addEventListener('viewdestroy', function () { - hammertime.off('swipeleft', onSwipeLeft); - hammertime.off('swiperight', onSwipeRight); - }); - }); - }, - - configurePaperLibraryTabs: function (ownerpage, tabs, panels, animateTabs, enableSwipe) { - - if (!browser.safari && enableSwipe !== false) { - LibraryBrowser.configureSwipeTabs(ownerpage, tabs); - } - - ownerpage.addEventListener('viewbeforeshow', function () { - if (tabs.triggerBeforeTabChange && this.firstTabIndex == null) { - tabs.triggerBeforeTabChange(); - } - }); - - ownerpage.addEventListener('viewshow', function () { - if (this.firstTabIndex) { - tabs.selectedIndex(this.firstTabIndex); - this.firstTabIndex = null; - } else { - tabs.triggerTabChange(); - } - }); - - tabs.addEventListener('beforetabchange', function (e) { - - if (e.detail.previousIndex != null) { - panels[e.detail.previousIndex].classList.remove('is-active'); - } - - var newPanel = panels[e.detail.selectedTabIndex]; - - if (e.detail.previousIndex != null && e.detail.previousIndex != e.detail.selectedTabIndex) { - if (newPanel.animate && (animateTabs || []).indexOf(e.detail.selectedTabIndex) != -1) { - fadeInRight(newPanel); - } - } - - newPanel.classList.add('is-active'); - }); - }, - - showTab: function (url, index) { - - var afterNavigate = function () { - - document.removeEventListener('pageinit', afterNavigate); - if (window.location.href.toLowerCase().indexOf(url.toLowerCase()) != -1) { - this.firstTabIndex = index; - } - }; - - if (window.location.href.toLowerCase().indexOf(url.toLowerCase()) != -1) { - - require(['viewManager'], function (viewManager) { - afterNavigate.call(viewManager.currentView()); - }); - } else { - - pageClassOn('pageinit', 'page', afterNavigate); - Dashboard.navigate(url); - } - }, - - 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; - }, - - getHref: function (item, context, topParentId) { - - if (!item) { - throw new Error('item cannot be null'); - } - - if (item.url) { - return item.url; - } - - var url; - // Handle search hints - var id = item.Id || item.ItemId; - - if (item.Type == "SeriesTimer") { - //return "livetvseriestimer.html?id=" + id; - return "itemdetails.html?seriesTimerId=" + id; - } - - 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 'itemlist.html?topParentId=' + item.Id + '&parentId=' + item.Id; - } - - if (item.CollectionType == 'tvshows') { - return 'tv.html?topParentId=' + item.Id; - } - - if (item.CollectionType == 'music') { - return 'music.html?topParentId=' + item.Id; - } - - if (item.CollectionType == 'games') { - return id ? "itemlist.html?parentId=" + id : "#"; - //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; - } - } - else if (item.IsFolder) { - if (item.Type != "BoxSet" && item.Type != "Series") { - return id ? "itemlist.html?parentId=" + 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.IsFolder && item.SourceType == 'Channel') || 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") { - var type; - switch (context) { - case 'tvshows': - type = 'Series'; - break; - case 'games': - type = 'Game'; - break; - default: - type = 'Movie'; - break; - } - - url = "secondaryitems.html?type=" + type + "&genreId=" + id; - if (topParentId) { - url += "&parentId=" + topParentId; - } - return url; - } - if (item.Type == "MusicGenre") { - return "itemdetails.html?id=" + id; - } - if (item.Type == "GameGenre") { - - url = "secondaryitems.html?type=Game&genreId=" + id; - if (topParentId) { - url += "&parentId=" + topParentId; - } - return url; - } - if (item.Type == "Studio") { - - var type; - switch (context) { - case 'tvshows': - type = 'Series'; - break; - case 'games': - type = 'Game'; - break; - default: - type = 'Movie'; - break; - } - - url = "secondaryitems.html?type=" + type + "&studioId=" + id; - if (topParentId) { - url += "&parentId=" + topParentId; - } - return url; - } - 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; - }, - - getListItemInfo: function (elem) { - - var elemWithAttributes = elem; - - while (!elemWithAttributes.getAttribute('data-id')) { - elemWithAttributes = elemWithAttributes.parentNode; - } - - var itemId = elemWithAttributes.getAttribute('data-id'); - var index = elemWithAttributes.getAttribute('data-index'); - var mediaType = elemWithAttributes.getAttribute('data-mediatype'); - - return { - id: itemId, - index: index, - mediaType: mediaType, - context: elemWithAttributes.getAttribute('data-context') - }; - }, - - 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 = datetime.toLocaleDateString(date); - - if (date.toLowerCase().indexOf(day.toLowerCase()) == -1) { - return day + " " + date; - } - - return date; - }, - - renderName: function (item, nameElem, linkToElement, context) { - - require(['itemHelper'], function (itemHelper) { - var name = itemHelper.getDisplayName(item, { - includeParentInfo: false - }); - - if (linkToElement) { - nameElem.innerHTML = '' + name + ''; - } else { - nameElem.innerHTML = 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.IsSeries) { - html.push(item.Name); - } - - if (html.length) { - parentNameElem.classList.remove('hide'); - parentNameElem.innerHTML = html.join(' - '); - } else { - parentNameElem.classList.add('hide'); - } - }, - - showLayoutMenu: function (button, currentLayout, views) { - - var dispatchEvent = true; - - if (!views) { - - dispatchEvent = false; - // Add banner and list once all screens support them - 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, - selected: currentLayout == v - }; - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: button, - callback: function (id) { - - button.dispatchEvent(new CustomEvent('layoutchange', { - detail: { - viewStyle: id - }, - bubbles: true, - cancelable: false - })); - - if (!dispatchEvent) { - if (window.$) { - $(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 { - appSettings.set(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.filterButton || options.sortButton || options.addLayoutButton) { - - html += '
'; - - if (showControls) { - - html += ''; - html += ''; - } - - if (options.addLayoutButton) { - - html += ''; - } - - if (options.sortButton) { - - html += ''; - } - - if (options.filterButton) { - - html += ''; - } - - html += '
'; - - if (showControls && options.showLimit) { - - var id = "selectPageSize"; - - var pageSizes = options.pageSizes || [20, 50, 100, 200, 300, 400, 500]; - - 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) { - - require(['dialogHelper', 'emby-radio'], function (dialogHelper) { - - var dlg = dialogHelper.createDialog({ - removeOnClose: true, - modal: false, - entryAnimationDuration: 160, - exitAnimationDuration: 200 - }); - - dlg.classList.add('ui-body-a'); - dlg.classList.add('background-theme-a'); - dlg.classList.add('formDialog'); - - var html = ''; - - html += '
'; - - html += '

'; - html += Globalize.translate('HeaderSortBy'); - html += '

'; - - var i, length; - var isChecked; - - html += '
'; - for (i = 0, length = options.items.length; i < length; i++) { - - var option = options.items[i]; - - var radioValue = option.id.replace(',', '_'); - isChecked = (options.query.SortBy || '').replace(',', '_') == radioValue ? ' checked' : ''; - html += ''; - } - html += '
'; - - html += '

'; - html += Globalize.translate('HeaderSortOrder'); - html += '

'; - html += '
'; - isChecked = options.query.SortOrder == 'Ascending' ? ' checked' : ''; - html += ''; - isChecked = options.query.SortOrder == 'Descending' ? ' checked' : ''; - html += ''; - html += '
'; - html += '
'; - - dlg.innerHTML = html; - - dialogHelper.open(dlg); - - function onSortByChange() { - var newValue = this.value; - if (this.checked) { - var changed = options.query.SortBy != newValue; - - options.query.SortBy = newValue.replace('_', ','); - options.query.StartIndex = 0; - - if (options.callback && changed) { - options.callback(); - } - } - } - - var sortBys = dlg.querySelectorAll('.menuSortBy'); - for (i = 0, length = sortBys.length; i < length; i++) { - sortBys[i].addEventListener('change', onSortByChange); - } - - function onSortOrderChange() { - var newValue = this.value; - if (this.checked) { - var changed = options.query.SortOrder != newValue; - - options.query.SortOrder = newValue; - options.query.StartIndex = 0; - - if (options.callback && changed) { - options.callback(); - } - } - } - - var sortOrders = dlg.querySelectorAll('.menuSortOrder'); - for (i = 0, length = sortOrders.length; i < length; i++) { - sortOrders[i].addEventListener('change', onSortOrderChange); - } - }); - }, - - renderDetailImage: function (elem, item, editable, preferThumb, imageLoader, indicators) { - - if (item.Type === 'SeriesTimer') { - editable = false; - } - - var imageTags = item.ImageTags || {}; - - if (item.PrimaryImageTag) { - imageTags.Primary = item.PrimaryImageTag; - } - - var html = ''; - - var url; - var shape = 'portrait'; - - var imageHeight = 360; - var detectRatio = false; - - if (preferThumb && imageTags.Thumb) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Thumb", - maxHeight: imageHeight, - tag: item.ImageTags.Thumb - }); - shape = 'thumb'; - } - else if (imageTags.Primary) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Primary", - maxHeight: imageHeight, - tag: item.ImageTags.Primary - }); - detectRatio = true; - } - else if (item.BackdropImageTags && item.BackdropImageTags.length) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Backdrop", - maxHeight: imageHeight, - tag: item.BackdropImageTags[0] - }); - shape = 'thumb'; - } - else if (imageTags.Thumb) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Thumb", - maxHeight: imageHeight, - tag: item.ImageTags.Thumb - }); - shape = 'thumb'; - } - else if (imageTags.Disc) { - - url = ApiClient.getScaledImageUrl(item.Id, { - type: "Disc", - maxHeight: imageHeight, - tag: item.ImageTags.Disc - }); - shape = 'square'; - } - else if (item.AlbumId && item.AlbumPrimaryImageTag) { - - url = ApiClient.getScaledImageUrl(item.AlbumId, { - type: "Primary", - maxHeight: imageHeight, - tag: item.AlbumPrimaryImageTag - }); - shape = 'square'; - } - else if (item.SeriesId && item.SeriesPrimaryImageTag) { - - url = ApiClient.getScaledImageUrl(item.SeriesId, { - type: "Primary", - maxHeight: imageHeight, - tag: item.SeriesPrimaryImageTag - }); - } - else if (item.ParentPrimaryImageItemId && item.ParentPrimaryImageTag) { - - url = ApiClient.getScaledImageUrl(item.ParentPrimaryImageItemId, { - type: "Primary", - maxHeight: imageHeight, - tag: item.ParentPrimaryImageTag - }); - } - - html += '
'; - - if (editable) { - html += ""; - } - - if (detectRatio && item.PrimaryImageAspectRatio) { - - if (item.PrimaryImageAspectRatio >= 1.48) { - shape = 'thumb'; - } else if (item.PrimaryImageAspectRatio >= .85 && item.PrimaryImageAspectRatio <= 1.34) { - shape = 'square'; - } - } - - html += ""; - - if (editable) { - html += ""; - } - - var progressHtml = item.IsFolder || !item.UserData ? '' : indicators.getProgressBarHtml(item); - - html += '
'; - if (progressHtml) { - html += progressHtml; - } - html += "
"; - - html += "
"; - - elem.innerHTML = html; - - if (shape == 'thumb') { - elem.classList.add('thumbDetailImageContainer'); - elem.classList.remove('portraitDetailImageContainer'); - elem.classList.remove('squareDetailImageContainer'); - } - else if (shape == 'square') { - elem.classList.remove('thumbDetailImageContainer'); - elem.classList.remove('portraitDetailImageContainer'); - elem.classList.add('squareDetailImageContainer'); - } else { - elem.classList.remove('thumbDetailImageContainer'); - elem.classList.add('portraitDetailImageContainer'); - elem.classList.remove('squareDetailImageContainer'); - } - - if (url) { - var img = elem.querySelector('img'); - img.onload = function () { - if (img.src.indexOf('empty.png') == -1) { - img.classList.add('loaded'); - } - }; - imageLoader.lazyImage(img, url); - } - }, - - renderDetailPageBackdrop: function (page, item, imageLoader) { - - var screenWidth = screen.availWidth; - - var imgUrl; - var hasbackdrop = false; - - var itemBackdropElement = page.querySelector('#itemBackdrop'); - - if (item.BackdropImageTags && item.BackdropImageTags.length) { - - imgUrl = ApiClient.getScaledImageUrl(item.Id, { - type: "Backdrop", - index: 0, - maxWidth: screenWidth, - tag: item.BackdropImageTags[0] - }); - - itemBackdropElement.classList.remove('noBackdrop'); - imageLoader.lazyImage(itemBackdropElement, imgUrl, false); - hasbackdrop = true; - } - else if (item.ParentBackdropItemId && item.ParentBackdropImageTags && item.ParentBackdropImageTags.length) { - - imgUrl = ApiClient.getScaledImageUrl(item.ParentBackdropItemId, { - type: 'Backdrop', - index: 0, - tag: item.ParentBackdropImageTags[0], - maxWidth: screenWidth - }); - - itemBackdropElement.classList.remove('noBackdrop'); - imageLoader.lazyImage(itemBackdropElement, imgUrl, false); - hasbackdrop = true; - } - else { - - itemBackdropElement.classList.add('noBackdrop'); - itemBackdropElement.style.backgroundImage = ''; - } - - return hasbackdrop; - } - }; - - return libraryBrowser; - - })(window, document, screen); - - window.LibraryBrowser = libraryBrowser; - - return libraryBrowser; -}); \ No newline at end of file +define(["appSettings","dom","browser","datetime","scrollStyles"],function(appSettings,dom,browser,datetime){"use strict";function fadeInRight(elem){var pct=browser.mobile?"4%":"0.5%",keyframes=[{opacity:"0",transform:"translate3d("+pct+", 0, 0)",offset:0},{opacity:"1",transform:"none",offset:1}];elem.animate(keyframes,{duration:160,iterations:1,easing:"ease-out"})}var libraryBrowser=function(window,document,screen){var pageSizeKey="pagesize_v4",libraryBrowser={getDefaultPageSize:function(key,defaultValue){return 100},getSavedQueryKey:function(modifier){return window.location.href.split("#")[0]+(modifier||"")},loadSavedQueryValues:function(key,query){var values=appSettings.get(key+"_"+Dashboard.getCurrentUserId());return values?(values=JSON.parse(values),Object.assign(query,values)):query},saveQueryValues:function(key,query){var values={};query.SortBy&&(values.SortBy=query.SortBy),query.SortOrder&&(values.SortOrder=query.SortOrder);try{appSettings.set(key+"_"+Dashboard.getCurrentUserId(),JSON.stringify(values))}catch(e){}},saveViewSetting:function(key,value){try{appSettings.set(key+"_"+Dashboard.getCurrentUserId()+"_view",value)}catch(e){}},getSavedView:function(key){var val=appSettings.get(key+"_"+Dashboard.getCurrentUserId()+"_view");return val},getSavedViewSetting:function(key){return new Promise(function(resolve,reject){var val=LibraryBrowser.getSavedView(key);resolve(val)})},allowSwipe:function(target){function allowSwipeOn(elem){return!dom.parentWithTag(elem,"input")&&(!elem.classList||!elem.classList.contains("hiddenScrollX")&&!elem.classList.contains("smoothScrollX")&&!elem.classList.contains("animatedScrollX"))}for(var parent=target;null!=parent;){if(!allowSwipeOn(parent))return!1;parent=parent.parentNode}return!0},configureSwipeTabs:function(ownerpage,tabs){if(browser.touch){var pageCount=ownerpage.querySelectorAll(".pageTabContent").length,onSwipeLeft=function(e){if(LibraryBrowser.allowSwipe(e.target)&&ownerpage.contains(e.target)){var selected=parseInt(tabs.selectedIndex()||"0");selected0&&tabs.selectedIndex(selected-1)}};require(["hammer-main"],function(hammertime){hammertime.on("swipeleft",onSwipeLeft),hammertime.on("swiperight",onSwipeRight),ownerpage.addEventListener("viewdestroy",function(){hammertime.off("swipeleft",onSwipeLeft),hammertime.off("swiperight",onSwipeRight)})})}},configurePaperLibraryTabs:function(ownerpage,tabs,panels,animateTabs,enableSwipe){browser.safari||enableSwipe===!1||LibraryBrowser.configureSwipeTabs(ownerpage,tabs),ownerpage.addEventListener("viewbeforeshow",function(){tabs.triggerBeforeTabChange&&null==this.firstTabIndex&&tabs.triggerBeforeTabChange()}),ownerpage.addEventListener("viewshow",function(){this.firstTabIndex?(tabs.selectedIndex(this.firstTabIndex),this.firstTabIndex=null):tabs.triggerTabChange()}),tabs.addEventListener("beforetabchange",function(e){null!=e.detail.previousIndex&&panels[e.detail.previousIndex].classList.remove("is-active");var newPanel=panels[e.detail.selectedTabIndex];null!=e.detail.previousIndex&&e.detail.previousIndex!=e.detail.selectedTabIndex&&newPanel.animate&&(animateTabs||[]).indexOf(e.detail.selectedTabIndex)!=-1&&fadeInRight(newPanel),newPanel.classList.add("is-active")})},showTab:function(url,index){var afterNavigate=function(){document.removeEventListener("pageinit",afterNavigate),window.location.href.toLowerCase().indexOf(url.toLowerCase())!=-1&&(this.firstTabIndex=index)};window.location.href.toLowerCase().indexOf(url.toLowerCase())!=-1?require(["viewManager"],function(viewManager){afterNavigate.call(viewManager.currentView())}):(pageClassOn("pageinit","page",afterNavigate),Dashboard.navigate(url))},getArtistLinksHtml:function(artists,cssClass){for(var html=[],i=0,length=artists.length;i'+artist.Name+"")}return html=html.join(" / ")},getHref:function(item,context,topParentId){if(!item)throw new Error("item cannot be null");if(item.url)return item.url;var url,id=item.Id||item.ItemId;if("SeriesTimer"==item.Type)return"itemdetails.html?seriesTimerId="+id;if("livetv"==item.CollectionType)return"livetv.html";if("channels"==item.CollectionType)return"channels.html";if("folders"!=context){if("movies"==item.CollectionType)return"movies.html?topParentId="+item.Id;if("boxsets"==item.CollectionType)return"itemlist.html?topParentId="+item.Id+"&parentId="+item.Id;if("tvshows"==item.CollectionType)return"tv.html?topParentId="+item.Id;if("music"==item.CollectionType)return"music.html?topParentId="+item.Id;if("games"==item.CollectionType)return id?"itemlist.html?parentId="+id:"#";if("playlists"==item.CollectionType)return"playlists.html?topParentId="+item.Id;if("photos"==item.CollectionType)return"photos.html?topParentId="+item.Id}else if(item.IsFolder&&"BoxSet"!=item.Type&&"Series"!=item.Type)return id?"itemlist.html?parentId="+id:"#";if("CollectionFolder"==item.Type)return"itemlist.html?topParentId="+item.Id+"&parentId="+item.Id;if("PhotoAlbum"==item.Type)return"itemlist.html?context=photos&parentId="+id;if("Playlist"==item.Type)return"itemdetails.html?id="+id;if("TvChannel"==item.Type)return"itemdetails.html?id="+id;if("Channel"==item.Type)return"channelitems.html?id="+id;if(item.IsFolder&&"Channel"==item.SourceType||"ChannelFolderItem"==item.Type)return"channelitems.html?id="+item.ChannelId+"&folderId="+item.Id;if("Program"==item.Type)return"itemdetails.html?id="+id;if("BoxSet"==item.Type)return"itemdetails.html?id="+id;if("MusicAlbum"==item.Type)return"itemdetails.html?id="+id;if("GameSystem"==item.Type)return"itemdetails.html?id="+id;if("Genre"==item.Type){var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;default:type="Movie"}return url="secondaryitems.html?type="+type+"&genreId="+id,topParentId&&(url+="&parentId="+topParentId),url}if("MusicGenre"==item.Type)return"itemdetails.html?id="+id;if("GameGenre"==item.Type)return url="secondaryitems.html?type=Game&genreId="+id,topParentId&&(url+="&parentId="+topParentId),url;if("Studio"==item.Type){var type;switch(context){case"tvshows":type="Series";break;case"games":type="Game";break;default:type="Movie"}return url="secondaryitems.html?type="+type+"&studioId="+id,topParentId&&(url+="&parentId="+topParentId),url}if("Person"==item.Type)return"itemdetails.html?id="+id;if("Recording"==item.Type)return"itemdetails.html?id="+id;if("MusicArtist"==item.Type)return"itemdetails.html?id="+id;var contextSuffix=context?"&context="+context:"";return"Series"==item.Type||"Season"==item.Type||"Episode"==item.Type?"itemdetails.html?id="+id+contextSuffix:item.IsFolder?id?"itemlist.html?parentId="+id:"#":"itemdetails.html?id="+id},getListItemInfo:function(elem){for(var elemWithAttributes=elem;!elemWithAttributes.getAttribute("data-id");)elemWithAttributes=elemWithAttributes.parentNode;var itemId=elemWithAttributes.getAttribute("data-id"),index=elemWithAttributes.getAttribute("data-index"),mediaType=elemWithAttributes.getAttribute("data-mediatype");return{id:itemId,index:index,mediaType:mediaType,context:elemWithAttributes.getAttribute("data-context")}},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()];return date=datetime.toLocaleDateString(date),date.toLowerCase().indexOf(day.toLowerCase())==-1?day+" "+date:date},renderName:function(item,nameElem,linkToElement,context){require(["itemHelper"],function(itemHelper){var name=itemHelper.getDisplayName(item,{includeParentInfo:!1});linkToElement?nameElem.innerHTML=''+name+"":nameElem.innerHTML=name})},renderParentName:function(item,parentNameElem,context){var html=[],contextParam=context?"&context="+context:"";item.AlbumArtists?html.push(LibraryBrowser.getArtistLinksHtml(item.AlbumArtists,"detailPageParentLink")):item.ArtistItems&&item.ArtistItems.length&&"MusicVideo"==item.Type?html.push(LibraryBrowser.getArtistLinksHtml(item.ArtistItems,"detailPageParentLink")):item.SeriesName&&"Episode"==item.Type&&html.push(''+item.SeriesName+""),item.SeriesName&&"Season"==item.Type?html.push(''+item.SeriesName+""):null!=item.ParentIndexNumber&&"Episode"==item.Type?html.push(''+item.SeasonName+""):item.Album&&"Audio"==item.Type&&(item.AlbumId||item.ParentId)?html.push(''+item.Album+""):item.Album&&"MusicVideo"==item.Type&&item.AlbumId?html.push(''+item.Album+""):item.Album?html.push(item.Album):"Program"==item.Type&&item.IsSeries&&html.push(item.Name),html.length?(parentNameElem.classList.remove("hide"),parentNameElem.innerHTML=html.join(" - ")):parentNameElem.classList.add("hide")},showLayoutMenu:function(button,currentLayout,views){var dispatchEvent=!0;views||(dispatchEvent=!1,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,selected:currentLayout==v}});require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:button,callback:function(id){button.dispatchEvent(new CustomEvent("layoutchange",{detail:{viewStyle:id},bubbles:!0,cancelable:!1})),dispatchEvent||window.$&&$(button).trigger("layoutchange",[id])}})})},getQueryPagingHtml:function(options){var startIndex=options.startIndex,limit=options.limit,totalRecordCount=options.totalRecordCount;if(limit&&options.updatePageSizeSetting!==!1)try{appSettings.set(options.pageSizeKey||pageSizeKey,limit)}catch(e){}var html="",recordsEnd=Math.min(startIndex+limit,totalRecordCount),showControls=totalRecordCount>20||limit',showControls){html+='';var startAtDisplay=totalRecordCount?startIndex+1:0;html+=startAtDisplay+"-"+recordsEnd+" of "+totalRecordCount,html+=""}if((showControls||options.viewButton||options.filterButton||options.sortButton||options.addLayoutButton)&&(html+='
',showControls&&(html+='',html+=''),options.addLayoutButton&&(html+=''),options.sortButton&&(html+=''),options.filterButton&&(html+=''),html+="
",showControls&&options.showLimit)){var id="selectPageSize",pageSizes=options.pageSizes||[20,50,100,200,300,400,500],optionsHtml=pageSizes.map(function(val){return limit==val?'":'"}).join("");html+='
"}return html+=""},showSortMenu:function(options){require(["dialogHelper","emby-radio"],function(dialogHelper){function onSortByChange(){var newValue=this.value;if(this.checked){var changed=options.query.SortBy!=newValue;options.query.SortBy=newValue.replace("_",","),options.query.StartIndex=0,options.callback&&changed&&options.callback()}}function onSortOrderChange(){var newValue=this.value;if(this.checked){var changed=options.query.SortOrder!=newValue;options.query.SortOrder=newValue,options.query.StartIndex=0,options.callback&&changed&&options.callback()}}var dlg=dialogHelper.createDialog({removeOnClose:!0,modal:!1,entryAnimationDuration:160,exitAnimationDuration:200});dlg.classList.add("ui-body-a"),dlg.classList.add("background-theme-a"),dlg.classList.add("formDialog");var html="";html+='
',html+='

',html+=Globalize.translate("HeaderSortBy"),html+="

";var i,length,isChecked;for(html+="
",i=0,length=options.items.length;i"+option.name+""}html+="
",html+='

',html+=Globalize.translate("HeaderSortOrder"),html+="

",html+="
",isChecked="Ascending"==options.query.SortOrder?" checked":"",html+='",isChecked="Descending"==options.query.SortOrder?" checked":"",html+='",html+="
",html+="
",dlg.innerHTML=html,dialogHelper.open(dlg);var sortBys=dlg.querySelectorAll(".menuSortBy");for(i=0,length=sortBys.length;i',editable&&(html+=""),detectRatio&&item.PrimaryImageAspectRatio&&(item.PrimaryImageAspectRatio>=1.48?shape="thumb":item.PrimaryImageAspectRatio>=.85&&item.PrimaryImageAspectRatio<=1.34&&(shape="square")),html+="",editable&&(html+="");var progressHtml=item.IsFolder||!item.UserData?"":indicators.getProgressBarHtml(item);if(html+='
',progressHtml&&(html+=progressHtml),html+="
",html+="",elem.innerHTML=html,"thumb"==shape?(elem.classList.add("thumbDetailImageContainer"),elem.classList.remove("portraitDetailImageContainer"),elem.classList.remove("squareDetailImageContainer")):"square"==shape?(elem.classList.remove("thumbDetailImageContainer"),elem.classList.remove("portraitDetailImageContainer"),elem.classList.add("squareDetailImageContainer")):(elem.classList.remove("thumbDetailImageContainer"),elem.classList.add("portraitDetailImageContainer"),elem.classList.remove("squareDetailImageContainer")),url){var img=elem.querySelector("img");img.onload=function(){img.src.indexOf("empty.png")==-1&&img.classList.add("loaded")},imageLoader.lazyImage(img,url)}},renderDetailPageBackdrop:function(page,item,imageLoader){var imgUrl,screenWidth=screen.availWidth,hasbackdrop=!1,itemBackdropElement=page.querySelector("#itemBackdrop");return item.BackdropImageTags&&item.BackdropImageTags.length?(imgUrl=ApiClient.getScaledImageUrl(item.Id,{type:"Backdrop",index:0,maxWidth:screenWidth,tag:item.BackdropImageTags[0]}),itemBackdropElement.classList.remove("noBackdrop"),imageLoader.lazyImage(itemBackdropElement,imgUrl,!1),hasbackdrop=!0):item.ParentBackdropItemId&&item.ParentBackdropImageTags&&item.ParentBackdropImageTags.length?(imgUrl=ApiClient.getScaledImageUrl(item.ParentBackdropItemId,{type:"Backdrop",index:0,tag:item.ParentBackdropImageTags[0],maxWidth:screenWidth}),itemBackdropElement.classList.remove("noBackdrop"),imageLoader.lazyImage(itemBackdropElement,imgUrl,!1),hasbackdrop=!0):(itemBackdropElement.classList.add("noBackdrop"),itemBackdropElement.style.backgroundImage=""),hasbackdrop}};return libraryBrowser}(window,document,screen);return window.LibraryBrowser=libraryBrowser,libraryBrowser}); \ No newline at end of file diff --git a/dashboard-ui/scripts/librarymenu.js b/dashboard-ui/scripts/librarymenu.js index e91a2511ca..f00af2c59d 100644 --- a/dashboard-ui/scripts/librarymenu.js +++ b/dashboard-ui/scripts/librarymenu.js @@ -1,1076 +1 @@ -define(['layoutManager', 'viewManager', 'libraryBrowser', 'embyRouter', 'playbackManager', 'paper-icon-button-light', 'material-icons', 'scrollStyles'], function (layoutManager, viewManager, libraryBrowser, embyRouter, playbackManager) { - 'use strict'; - - var enableBottomTabs = AppInfo.isNativeApp; - var enableLibraryNavDrawer = !enableBottomTabs; - - var navDrawerElement; - var navDrawerScrollContainer; - var navDrawerInstance; - - var mainDrawerButton; - - function renderHeader() { - - var html = ''; - - html += '
'; - var backIcon = browserInfo.safari ? 'chevron_left' : ''; - - html += ''; - - html += ''; - html += ''; - - html += '

' + Globalize.translate('ButtonHome') + '

'; - - html += '
'; - - html += ''; - html += ''; - - html += ''; - - html += ''; - - html += ''; - - html += ''; - - if (!browserInfo.mobile) { - html += ''; - } - - html += '
'; - html += '
'; - - html += '
'; - html += '
'; - - var viewMenuBar = document.createElement('div'); - viewMenuBar.classList.add('viewMenuBar'); - viewMenuBar.innerHTML = html; - - document.querySelector('.skinHeader').appendChild(viewMenuBar); - - lazyLoadViewMenuBarImages(); - - bindMenuEvents(); - } - - function lazyLoadViewMenuBarImages() { - require(['imageLoader'], function (imageLoader) { - imageLoader.lazyChildren(document.querySelector('.viewMenuBar')); - }); - } - - function onBackClick() { - - embyRouter.back(); - } - - function updateUserInHeader(user) { - - var header = document.querySelector('.viewMenuBar'); - if (!header) { - return; - } - - var headerUserButton = header.querySelector('.headerUserButton'); - var hasImage; - - if (user && user.name) { - if (user.imageUrl) { - - var userButtonHeight = 26; - - var url = user.imageUrl; - - if (user.supportsImageParams) { - url += "&height=" + Math.round((userButtonHeight * Math.max(window.devicePixelRatio || 1, 2))); - } - - if (headerUserButton) { - updateHeaderUserButton(headerUserButton, url); - hasImage = true; - } - } - } - - if (headerUserButton && !hasImage) { - - updateHeaderUserButton(headerUserButton, null); - } - if (user) { - updateLocalUser(user.localUser); - } - - requiresUserRefresh = false; - } - - function updateHeaderUserButton(headerUserButton, src) { - - if (src) { - headerUserButton.classList.add('headerUserButtonRound'); - headerUserButton.classList.remove('autoSize'); - headerUserButton.innerHTML = ''; - } else { - headerUserButton.classList.remove('headerUserButtonRound'); - headerUserButton.classList.add('autoSize'); - headerUserButton.innerHTML = 'person'; - } - } - - function updateLocalUser(user) { - - var header = document.querySelector('.viewMenuBar'); - - var headerSearchButton = header.querySelector('.headerSearchButton'); - var btnCast = header.querySelector('.btnCast'); - var dashboardEntryHeaderButton = header.querySelector('.dashboardEntryHeaderButton'); - - if (user) { - btnCast.classList.remove('hide'); - - if (headerSearchButton) { - headerSearchButton.classList.remove('hide'); - } - - if (dashboardEntryHeaderButton) { - if (user.Policy.IsAdministrator) { - dashboardEntryHeaderButton.classList.remove('hide'); - } else { - dashboardEntryHeaderButton.classList.add('hide'); - } - } - - require(['apphost'], function (apphost) { - if (apphost.supports('voiceinput')) { - header.querySelector('.headerVoiceButton').classList.add('hide'); - } else { - header.querySelector('.headerVoiceButton').classList.add('hide'); - } - }); - - } else { - btnCast.classList.add('hide'); - header.querySelector('.headerVoiceButton').classList.add('hide'); - if (headerSearchButton) { - headerSearchButton.classList.add('hide'); - } - - if (dashboardEntryHeaderButton) { - dashboardEntryHeaderButton.classList.add('hide'); - } - } - } - - function showVoice() { - require(['voiceDialog'], function (voiceDialog) { - voiceDialog.showDialog(); - }); - } - - function showSearch() { - Dashboard.navigate('search.html'); - } - - function onHeaderUserButtonClick(e) { - Dashboard.showUserFlyout(e.target); - } - - function onHeaderAppsButtonClick() { - - Dashboard.navigate('home.html'); - } - - function bindMenuEvents() { - - mainDrawerButton = document.querySelector('.mainDrawerButton'); - - if (mainDrawerButton) { - mainDrawerButton.addEventListener('click', toggleMainDrawer); - } - - var headerBackButton = document.querySelector('.headerBackButton'); - if (headerBackButton) { - headerBackButton.addEventListener('click', onBackClick); - } - - var headerVoiceButton = document.querySelector('.headerVoiceButton'); - if (headerVoiceButton) { - headerVoiceButton.addEventListener('click', showVoice); - } - - var headerSearchButton = document.querySelector('.headerSearchButton'); - if (headerSearchButton) { - headerSearchButton.addEventListener('click', showSearch); - } - - var headerUserButton = document.querySelector('.headerUserButton'); - if (headerUserButton) { - headerUserButton.addEventListener('click', onHeaderUserButtonClick); - } - - var headerAppsButton = document.querySelector('.headerAppsButton'); - if (headerAppsButton) { - headerAppsButton.addEventListener('click', onHeaderAppsButtonClick); - } - - var viewMenuBar = document.querySelector(".viewMenuBar"); - initHeadRoom(viewMenuBar); - - viewMenuBar.querySelector('.btnNotifications').addEventListener('click', function () { - Dashboard.navigate('notificationlist.html'); - }); - - var btnCast = document.querySelector('.headerButton-btnCast'); - - if (btnCast) { - btnCast.addEventListener('click', onCastButtonClicked); - } - } - - function onCastButtonClicked() { - - var btn = this; - - require(['playerSelectionMenu'], function (playerSelectionMenu) { - playerSelectionMenu.show(btn); - }); - } - - function getItemHref(item, context) { - - return libraryBrowser.getHref(item, context); - } - - var requiresUserRefresh = true; - var lastOpenTime = new Date().getTime(); - - function toggleMainDrawer() { - - if (navDrawerInstance.isVisible) { - closeMainDrawer(); - } else { - openMainDrawer(); - } - } - - function openMainDrawer() { - - navDrawerInstance.open(); - lastOpenTime = new Date().getTime(); - } - - function onMainDrawerOpened() { - - if (browserInfo.mobile) { - document.body.classList.add('bodyWithPopupOpen'); - } - } - function closeMainDrawer() { - - navDrawerInstance.close(); - } - function onMainDrawerSelect(e) { - - if (!navDrawerInstance.isVisible) { - document.body.classList.remove('bodyWithPopupOpen'); - } else { - onMainDrawerOpened(); - } - } - - function refreshLibraryInfoInDrawer(user, drawer) { - - var html = ''; - - html += '
'; - - var homeHref = window.ApiClient ? 'home.html' : 'selectserver.html?showuser=1'; - - html += '' + Globalize.translate('ButtonHome') + ''; - - html += '' + Globalize.translate('ButtonRemote') + ''; - - html += '
'; - - html += '
'; - html += '
'; - - var localUser = user.localUser; - if (localUser && localUser.Policy.IsAdministrator) { - - html += '
'; - html += '
'; - - html += '
'; - html += Globalize.translate('HeaderAdmin'); - html += '
'; - - html += '' + Globalize.translate('ButtonManageServer') + ''; - html += '' + Globalize.translate('MetadataManager') + ''; - - if (!browserInfo.mobile) { - html += '' + Globalize.translate('ButtonReports') + ''; - } - html += '
'; - } - - html += '
'; - - html += '
'; - - if (user.localUser && (AppInfo.isNativeApp && browserInfo.android)) { - html += '' + Globalize.translate('ButtonSettings') + ''; - } - - html += '' + Globalize.translate('ManageOfflineDownloads') + ''; - - html += '' + Globalize.translate('SyncToOtherDevices') + ''; - - if (Dashboard.isConnectMode()) { - html += '' + Globalize.translate('ButtonSelectServer') + ''; - } - - if (user.localUser) { - html += '' + Globalize.translate('ButtonSignOut') + ''; - } - - html += '
'; - - navDrawerScrollContainer.innerHTML = html; - - var lnkManageServer = navDrawerScrollContainer.querySelector('.lnkManageServer'); - if (lnkManageServer) { - lnkManageServer.addEventListener('click', onManageServerClicked); - } - } - - function refreshDashboardInfoInDrawer(page, user) { - - loadNavDrawer().then(function () { - if (!navDrawerScrollContainer.querySelector('.adminDrawerLogo')) { - createDashboardMenu(page); - } else { - updateDashboardMenuSelectedItem(); - } - }); - } - - function updateDashboardMenuSelectedItem() { - - var links = navDrawerScrollContainer.querySelectorAll('.sidebarLink'); - - for (var i = 0, length = links.length; i < length; i++) { - var link = links[i]; - - var selected = false; - - var pageIds = link.getAttribute('data-pageids'); - if (pageIds) { - selected = pageIds.split(',').indexOf(viewManager.currentView().id) != -1 - } - - if (selected) { - link.classList.add('selectedSidebarLink'); - - var title = ''; - - link = link.querySelector('span') || link; - var secondaryTitle = (link.innerText || link.textContent).trim(); - title += secondaryTitle; - - LibraryMenu.setTitle(title); - - } else { - link.classList.remove('selectedSidebarLink'); - } - } - } - - function createDashboardMenu() { - var html = ''; - - html += ''; - - html += Dashboard.getToolsMenuHtml(); - - html = html.split('href=').join('onclick="return LibraryMenu.onLinkClicked(event, this);" href='); - - navDrawerScrollContainer.innerHTML = html; - - updateDashboardMenuSelectedItem(); - } - - function onSidebarLinkClick() { - var section = this.getElementsByClassName('sectionName')[0]; - var text = section ? section.innerHTML : this.innerHTML; - - LibraryMenu.setTitle(text); - } - - function getUserViews(apiClient, userId) { - - return apiClient.getUserViews({}, userId).then(function (result) { - - var items = result.Items; - - var list = []; - - for (var i = 0, length = items.length; i < length; i++) { - - var view = items[i]; - - list.push(view); - - if (view.CollectionType == 'livetv') { - - view.ImageTags = {}; - view.icon = 'live_tv'; - view.onclick = "LibraryBrowser.showTab('livetv.html', 0);"; - - var guideView = Object.assign({}, view); - guideView.Name = Globalize.translate('ButtonGuide'); - guideView.ImageTags = {}; - guideView.icon = 'dvr'; - guideView.url = 'livetv.html?tab=1'; - guideView.onclick = "LibraryBrowser.showTab('livetv.html', 1);"; - list.push(guideView); - } - } - - return list; - }); - } - - function showBySelector(selector, show) { - var elem = document.querySelector(selector); - - if (elem) { - if (show) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - } - } - - function updateLibraryMenu(user) { - - if (!user) { - - showBySelector('.lnkManageOffline', false); - showBySelector('.lnkSyncToOtherDevices', false); - showBySelector('.userMenuOptions', false); - return; - } - - if (user.Policy.EnableSync) { - showBySelector('.lnkSyncToOtherDevices', true); - } else { - showBySelector('.lnkSyncToOtherDevices', false); - } - - require(['apphost'], function (appHost) { - if (user.Policy.EnableSync && appHost.supports('sync')) { - showBySelector('.lnkManageOffline', true); - } else { - showBySelector('.lnkManageOffline', false); - } - }); - - var userId = Dashboard.getCurrentUserId(); - - var apiClient = window.ApiClient; - - var libraryMenuOptions = document.querySelector('.libraryMenuOptions'); - - if (!libraryMenuOptions) { - return; - } - - getUserViews(apiClient, userId).then(function (result) { - - var items = result; - - var html = ''; - html += '
'; - html += Globalize.translate('HeaderMedia'); - html += '
'; - - html += items.map(function (i) { - - var icon = 'folder'; - var color = 'inherit'; - var itemId = i.Id; - - if (i.CollectionType == "channels") { - itemId = "channels"; - } - else if (i.CollectionType == "livetv") { - itemId = "livetv"; - } - - if (i.CollectionType == "photos") { - icon = 'photo_library'; - color = "#009688"; - } - else if (i.CollectionType == "music" || i.CollectionType == "musicvideos") { - icon = 'library_music'; - color = '#FB8521'; - } - else if (i.CollectionType == "books") { - icon = 'library_books'; - color = "#1AA1E1"; - } - else if (i.CollectionType == "playlists") { - icon = 'view_list'; - color = "#795548"; - } - else if (i.CollectionType == "games") { - icon = 'games'; - color = "#F44336"; - } - else if (i.CollectionType == "movies") { - icon = 'video_library'; - color = '#CE5043'; - } - else if (i.CollectionType == "channels" || i.Type == 'Channel') { - icon = 'videocam'; - color = '#E91E63'; - } - else if (i.CollectionType == "tvshows") { - icon = 'tv'; - color = "#4CAF50"; - } - else if (i.CollectionType == "livetv") { - icon = 'live_tv'; - color = "#293AAE"; - } - - icon = i.icon || icon; - - var onclick = i.onclick ? ' function(){' + i.onclick + '}' : 'null'; - return '' + i.Name + ''; - - }).join(''); - - libraryMenuOptions.innerHTML = html; - var elem = libraryMenuOptions; - - var sidebarLinks = elem.querySelectorAll('.sidebarLink'); - for (var i = 0, length = sidebarLinks.length; i < length; i++) { - sidebarLinks[i].removeEventListener('click', onSidebarLinkClick); - sidebarLinks[i].addEventListener('click', onSidebarLinkClick); - } - }); - } - - function onManageServerClicked() { - - closeMainDrawer(); - - Dashboard.navigate('dashboard.html'); - } - - function getTopParentId() { - - return getParameterByName('topParentId') || null; - } - - function getNavigateDelay() { - // On mobile devices don't navigate until after the closing animation has completed or it may stutter - return browserInfo.mobile ? 320 : 200;; - } - - window.LibraryMenu = { - getTopParentId: getTopParentId, - - onLinkClicked: function (event, link, action) { - - if (event.which != 1) { - return true; - } - - // There doesn't seem to be a way to detect if the drawer is in the process of opening, so try to handle that here - if ((new Date().getTime() - lastOpenTime) > 200) { - - setTimeout(function () { - closeMainDrawer(); - - - setTimeout(function () { - if (action) { - action(); - } else { - Dashboard.navigate(link.href); - } - }, getNavigateDelay()); - - }, 50); - } - - event.stopPropagation(); - event.preventDefault(); - return false; - }, - - onLogoutClicked: function () { - // There doesn't seem to be a way to detect if the drawer is in the process of opening, so try to handle that here - if ((new Date().getTime() - lastOpenTime) > 200) { - - closeMainDrawer(); - - setTimeout(function () { - Dashboard.logout(); - }, getNavigateDelay()); - } - - return false; - }, - - onHardwareMenuButtonClick: function () { - toggleMainDrawer(); - }, - - onSettingsClicked: function (event) { - - if (event.which != 1) { - return true; - } - - // There doesn't seem to be a way to detect if the drawer is in the process of opening, so try to handle that here - Dashboard.navigate('dashboard.html'); - return false; - }, - - setTabs: function (type, selectedIndex, builder) { - - var viewMenuBarTabs; - - if (!type) { - if (LibraryMenu.tabType) { - - document.body.classList.remove('withTallToolbar'); - viewMenuBarTabs = document.querySelector('.viewMenuBarTabs'); - viewMenuBarTabs.innerHTML = ''; - viewMenuBarTabs.classList.add('hide'); - LibraryMenu.tabType = null; - } - return; - } - - viewMenuBarTabs = document.querySelector('.viewMenuBarTabs'); - - if (!LibraryMenu.tabType) { - viewMenuBarTabs.classList.remove('hide'); - } - - require(['emby-tabs', 'emby-button'], function () { - if (LibraryMenu.tabType != type) { - - var index = 0; - - viewMenuBarTabs.innerHTML = '
' + builder().map(function (t) { - - var tabClass = selectedIndex == index ? 'emby-tab-button emby-tab-button-active' : 'emby-tab-button'; - - var tabHtml = ''; - index++; - return tabHtml; - - }).join('') + '
'; - - document.body.classList.add('withTallToolbar'); - LibraryMenu.tabType = type; - return; - } - - viewMenuBarTabs.querySelector('[is="emby-tabs"]').selectedIndex(selectedIndex); - - LibraryMenu.tabType = type; - }); - }, - - setTitle: function (title) { - - var html = title; - - var page = viewManager.currentView(); - if (page) { - var helpUrl = page.getAttribute('data-helpurl'); - - if (helpUrl) { - html += ''; - } - } - - var libraryMenuButtonText = document.querySelector('.libraryMenuButtonText'); - if (libraryMenuButtonText) { - libraryMenuButtonText.innerHTML = html; - } - - document.title = title || 'Emby'; - }, - - setTransparentMenu: function (transparent) { - - var viewMenuBar = document.querySelector('.viewMenuBar'); - - if (viewMenuBar) { - if (transparent) { - viewMenuBar.classList.add('semiTransparent'); - } else { - viewMenuBar.classList.remove('semiTransparent'); - } - } - } - }; - - function updateCastIcon() { - - var context = document; - - var btnCast = context.querySelector('.btnCast'); - - if (!btnCast) { - return; - } - - var info = playbackManager.getPlayerInfo(); - - if (info && !info.isLocalPlayer) { - - btnCast.querySelector('i').icon = 'cast_connected'; - btnCast.classList.add('btnActiveCast'); - context.querySelector('.headerSelectedPlayer').innerHTML = info.deviceName || info.name; - - } else { - btnCast.querySelector('i').innerHTML = 'cast'; - btnCast.classList.remove('btnActiveCast'); - - context.querySelector('.headerSelectedPlayer').innerHTML = ''; - } - } - - function updateLibraryNavLinks(page) { - - var isLiveTvPage = page.classList.contains('liveTvPage'); - var isChannelsPage = page.classList.contains('channelsPage'); - var isEditorPage = page.classList.contains('metadataEditorPage'); - var isReportsPage = page.classList.contains('reportsPage'); - var isMySyncPage = page.classList.contains('mySyncPage'); - - var id = isLiveTvPage || isChannelsPage || isEditorPage || isReportsPage || isMySyncPage || page.classList.contains('allLibraryPage') ? - '' : - getTopParentId() || ''; - - var i, length; - var elems = document.getElementsByClassName('lnkMediaFolder'); - - for (i = 0, length = elems.length; i < length; i++) { - - var lnkMediaFolder = elems[i]; - var itemId = lnkMediaFolder.getAttribute('data-itemid'); - - if (isChannelsPage && itemId == 'channels') { - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (isLiveTvPage && itemId == 'livetv') { - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (isEditorPage && itemId == 'editor') { - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (isReportsPage && itemId == 'reports') { - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (isMySyncPage && itemId == 'manageoffline' && window.location.href.toString().indexOf('mode=offline') != -1) { - - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (isMySyncPage && itemId == 'syncotherdevices' && window.location.href.toString().indexOf('mode=offline') == -1) { - - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else if (id && itemId == id) { - lnkMediaFolder.classList.add('selectedMediaFolder'); - } - else { - lnkMediaFolder.classList.remove('selectedMediaFolder'); - } - } - } - - function onWebSocketMessage(e, data) { - - var msg = data; - - if (msg.MessageType === "UserConfigurationUpdated") { - - if (msg.Data.Id == Dashboard.getCurrentUserId()) { - - // refresh library menu - } - } - } - - function updateViewMenuBar(page) { - - var viewMenuBar = document.querySelector('.viewMenuBar'); - - if (viewMenuBar) { - if (page.classList.contains('standalonePage')) { - viewMenuBar.classList.add('hide'); - } else { - viewMenuBar.classList.remove('hide'); - } - - if (page.classList.contains('type-interior') && !layoutManager.mobile) { - viewMenuBar.classList.add('headroomDisabled'); - } else { - viewMenuBar.classList.remove('headroomDisabled'); - } - } - - if (requiresUserRefresh) { - ConnectionManager.user(window.ApiClient).then(updateUserInHeader); - } - } - - pageClassOn('pagebeforeshow', 'page', function (e) { - - var page = this; - - if (!page.classList.contains('withTabs')) { - LibraryMenu.setTabs(null); - - if (page.classList.contains('pageWithAbsoluteTabs')) { - document.body.classList.add('withTallToolbar'); - } else { - document.body.classList.remove('withTallToolbar'); - } - } - }); - - pageClassOn('pageshow', 'page', function (e) { - - var page = this; - - var isDashboardPage = page.classList.contains('type-interior'); - - if (isDashboardPage) { - if (mainDrawerButton) { - mainDrawerButton.classList.remove('hide'); - } - refreshDashboardInfoInDrawer(page); - } else { - - if (mainDrawerButton) { - if (enableLibraryNavDrawer) { - mainDrawerButton.classList.remove('hide'); - } else { - mainDrawerButton.classList.add('hide'); - } - } - - if ((navDrawerElement && navDrawerElement.classList.contains('adminDrawer')) || (!navDrawerElement && enableLibraryNavDrawer)) { - refreshLibraryDrawer(); - } - } - - setDrawerClass(page); - - updateViewMenuBar(page); - - if (!e.detail.isRestored) { - // Scroll back up so in case vertical scroll was messed with - window.scrollTo(0, 0); - } - - updateTitle(page); - updateBackButton(page); - - if (page.classList.contains('libraryPage')) { - - document.body.classList.add('libraryDocument'); - document.body.classList.remove('dashboardDocument'); - document.body.classList.remove('hideMainDrawer'); - } - else if (isDashboardPage) { - - document.body.classList.remove('libraryDocument'); - document.body.classList.add('dashboardDocument'); - document.body.classList.remove('hideMainDrawer'); - - } else { - - document.body.classList.remove('libraryDocument'); - document.body.classList.remove('dashboardDocument'); - document.body.classList.add('hideMainDrawer'); - } - - updateLibraryNavLinks(page); - }); - - function updateTitle(page) { - - var title = page.getAttribute('data-title'); - - if (title) { - LibraryMenu.setTitle(title); - } - } - - function updateBackButton(page) { - - var backButton = document.querySelector('.headerBackButton'); - - if (backButton) { - if (page.getAttribute('data-backbutton') == 'true' && embyRouter.canGoBack()) { - backButton.classList.remove('hide'); - } else { - backButton.classList.add('hide'); - } - } - } - - function initHeadRoom(elem) { - - require(["headroom-window"], function (headroom) { - - headroom.add(elem); - }); - } - - function initializeApiClient(apiClient) { - - Events.off(apiClient, 'websocketmessage', onWebSocketMessage); - - Events.on(apiClient, 'websocketmessage', onWebSocketMessage); - } - - if (window.ApiClient) { - initializeApiClient(window.ApiClient); - } - - function setDrawerClass(page) { - - var admin = false; - - if (!page) { - page = viewManager.currentView(); - } - - if (page && page.classList.contains('type-interior')) { - admin = true; - } - - var enableNavDrawer = admin || enableLibraryNavDrawer; - if (enableNavDrawer) { - loadNavDrawer().then(function () { - if (admin) { - navDrawerElement.classList.add('adminDrawer'); - navDrawerElement.classList.remove('darkDrawer'); - } else { - navDrawerElement.classList.add('darkDrawer'); - navDrawerElement.classList.remove('adminDrawer'); - } - }); - } - } - - function refreshLibraryDrawer(user) { - - if (!enableLibraryNavDrawer) { - return; - } - - loadNavDrawer().then(function () { - var promise = user ? Promise.resolve(user) : ConnectionManager.user(window.ApiClient); - - promise.then(function (user) { - refreshLibraryInfoInDrawer(user); - - updateLibraryMenu(user.localUser); - }); - }); - } - - function getNavDrawerOptions() { - - var drawerWidth = screen.availWidth - 50; - // At least 240 - drawerWidth = Math.max(drawerWidth, 240); - // But not exceeding 280 - drawerWidth = Math.min(drawerWidth, 260); - - var disableEdgeSwipe = false; - - if (browserInfo.safari) { - disableEdgeSwipe = true; - } - - // Default is 600px - //drawer.responsiveWidth = '640px'; - - return { - target: navDrawerElement, - onChange: onMainDrawerSelect, - width: drawerWidth, - disableEdgeSwipe: disableEdgeSwipe - }; - } - - function loadNavDrawer() { - - if (navDrawerInstance) { - return Promise.resolve(navDrawerInstance); - } - - return new Promise(function (resolve, reject) { - - navDrawerElement = document.querySelector('.mainDrawer'); - navDrawerScrollContainer = navDrawerElement.querySelector('.scrollContainer'); - - require(['navdrawer'], function (navdrawer) { - navDrawerInstance = new navdrawer(getNavDrawerOptions()); - navDrawerElement.classList.remove('hide'); - resolve(navDrawerInstance); - }); - }); - } - - renderHeader(); - - Events.on(ConnectionManager, 'apiclientcreated', function (e, apiClient) { - initializeApiClient(apiClient); - }); - - Events.on(ConnectionManager, 'localusersignedin', function (e, user) { - setDrawerClass(); - ConnectionManager.user(ConnectionManager.getApiClient(user.ServerId)).then(function (user) { - refreshLibraryDrawer(user); - updateUserInHeader(user); - }); - }); - - Events.on(ConnectionManager, 'localusersignedout', updateUserInHeader); - Events.on(playbackManager, 'playerchange', updateCastIcon); - - setDrawerClass(); - - if (enableBottomTabs) { - require(['appfooter-shared', 'dockedtabs'], function (footer, dockedtabs) { - new dockedtabs({ - appFooter: footer - }); - }); - } - - return LibraryMenu; -}); \ No newline at end of file +define(["layoutManager","viewManager","libraryBrowser","embyRouter","playbackManager","paper-icon-button-light","material-icons","scrollStyles"],function(layoutManager,viewManager,libraryBrowser,embyRouter,playbackManager){"use strict";function renderHeader(){var html="";html+='
';var backIcon=browserInfo.safari?"chevron_left":"";html+='",html+='',html+='',html+='

'+Globalize.translate("ButtonHome")+"

",html+='
',html+='',html+='',html+='',html+='',html+='',html+='',browserInfo.mobile||(html+=''),html+="
",html+="
",html+='
',html+="
";var viewMenuBar=document.createElement("div");viewMenuBar.classList.add("viewMenuBar"),viewMenuBar.innerHTML=html,document.querySelector(".skinHeader").appendChild(viewMenuBar),lazyLoadViewMenuBarImages(),bindMenuEvents()}function lazyLoadViewMenuBarImages(){require(["imageLoader"],function(imageLoader){imageLoader.lazyChildren(document.querySelector(".viewMenuBar"))})}function onBackClick(){embyRouter.back()}function updateUserInHeader(user){var header=document.querySelector(".viewMenuBar");if(header){var hasImage,headerUserButton=header.querySelector(".headerUserButton");if(user&&user.name&&user.imageUrl){var userButtonHeight=26,url=user.imageUrl;user.supportsImageParams&&(url+="&height="+Math.round(userButtonHeight*Math.max(window.devicePixelRatio||1,2))),headerUserButton&&(updateHeaderUserButton(headerUserButton,url),hasImage=!0)}headerUserButton&&!hasImage&&updateHeaderUserButton(headerUserButton,null),user&&updateLocalUser(user.localUser),requiresUserRefresh=!1}}function updateHeaderUserButton(headerUserButton,src){src?(headerUserButton.classList.add("headerUserButtonRound"),headerUserButton.classList.remove("autoSize"),headerUserButton.innerHTML=''):(headerUserButton.classList.remove("headerUserButtonRound"),headerUserButton.classList.add("autoSize"),headerUserButton.innerHTML='person')}function updateLocalUser(user){var header=document.querySelector(".viewMenuBar"),headerSearchButton=header.querySelector(".headerSearchButton"),btnCast=header.querySelector(".btnCast"),dashboardEntryHeaderButton=header.querySelector(".dashboardEntryHeaderButton");user?(btnCast.classList.remove("hide"),headerSearchButton&&headerSearchButton.classList.remove("hide"),dashboardEntryHeaderButton&&(user.Policy.IsAdministrator?dashboardEntryHeaderButton.classList.remove("hide"):dashboardEntryHeaderButton.classList.add("hide")),require(["apphost"],function(apphost){apphost.supports("voiceinput")?header.querySelector(".headerVoiceButton").classList.add("hide"):header.querySelector(".headerVoiceButton").classList.add("hide")})):(btnCast.classList.add("hide"),header.querySelector(".headerVoiceButton").classList.add("hide"),headerSearchButton&&headerSearchButton.classList.add("hide"),dashboardEntryHeaderButton&&dashboardEntryHeaderButton.classList.add("hide"))}function showVoice(){require(["voiceDialog"],function(voiceDialog){voiceDialog.showDialog()})}function showSearch(){Dashboard.navigate("search.html")}function onHeaderUserButtonClick(e){Dashboard.showUserFlyout(e.target)}function onHeaderAppsButtonClick(){Dashboard.navigate("home.html")}function bindMenuEvents(){mainDrawerButton=document.querySelector(".mainDrawerButton"),mainDrawerButton&&mainDrawerButton.addEventListener("click",toggleMainDrawer);var headerBackButton=document.querySelector(".headerBackButton");headerBackButton&&headerBackButton.addEventListener("click",onBackClick);var headerVoiceButton=document.querySelector(".headerVoiceButton");headerVoiceButton&&headerVoiceButton.addEventListener("click",showVoice);var headerSearchButton=document.querySelector(".headerSearchButton");headerSearchButton&&headerSearchButton.addEventListener("click",showSearch);var headerUserButton=document.querySelector(".headerUserButton");headerUserButton&&headerUserButton.addEventListener("click",onHeaderUserButtonClick);var headerAppsButton=document.querySelector(".headerAppsButton");headerAppsButton&&headerAppsButton.addEventListener("click",onHeaderAppsButtonClick);var viewMenuBar=document.querySelector(".viewMenuBar");initHeadRoom(viewMenuBar),viewMenuBar.querySelector(".btnNotifications").addEventListener("click",function(){Dashboard.navigate("notificationlist.html")});var btnCast=document.querySelector(".headerButton-btnCast");btnCast&&btnCast.addEventListener("click",onCastButtonClicked)}function onCastButtonClicked(){var btn=this;require(["playerSelectionMenu"],function(playerSelectionMenu){playerSelectionMenu.show(btn)})}function getItemHref(item,context){return libraryBrowser.getHref(item,context)}function toggleMainDrawer(){navDrawerInstance.isVisible?closeMainDrawer():openMainDrawer()}function openMainDrawer(){navDrawerInstance.open(),lastOpenTime=(new Date).getTime()}function onMainDrawerOpened(){browserInfo.mobile&&document.body.classList.add("bodyWithPopupOpen")}function closeMainDrawer(){navDrawerInstance.close()}function onMainDrawerSelect(e){navDrawerInstance.isVisible?onMainDrawerOpened():document.body.classList.remove("bodyWithPopupOpen")}function refreshLibraryInfoInDrawer(user,drawer){var html="";html+='
';var homeHref=window.ApiClient?"home.html":"selectserver.html?showuser=1";html+=''+Globalize.translate("ButtonHome")+"",html+=''+Globalize.translate("ButtonRemote")+"",html+='
',html+='
',html+="
";var localUser=user.localUser;localUser&&localUser.Policy.IsAdministrator&&(html+='
',html+='
',html+='
',html+=Globalize.translate("HeaderAdmin"),html+="
",html+=''+Globalize.translate("ButtonManageServer")+"",html+=''+Globalize.translate("MetadataManager")+"",browserInfo.mobile||(html+=''+Globalize.translate("ButtonReports")+""),html+="
"),html+='
',html+='
',user.localUser&&AppInfo.isNativeApp&&browserInfo.android&&(html+=''+Globalize.translate("ButtonSettings")+""),html+=''+Globalize.translate("ManageOfflineDownloads")+"",html+=''+Globalize.translate("SyncToOtherDevices")+"",Dashboard.isConnectMode()&&(html+=''+Globalize.translate("ButtonSelectServer")+""),user.localUser&&(html+=''+Globalize.translate("ButtonSignOut")+""),html+="
",navDrawerScrollContainer.innerHTML=html;var lnkManageServer=navDrawerScrollContainer.querySelector(".lnkManageServer");lnkManageServer&&lnkManageServer.addEventListener("click",onManageServerClicked)}function refreshDashboardInfoInDrawer(page,user){loadNavDrawer().then(function(){navDrawerScrollContainer.querySelector(".adminDrawerLogo")?updateDashboardMenuSelectedItem():createDashboardMenu(page)})}function updateDashboardMenuSelectedItem(){for(var links=navDrawerScrollContainer.querySelectorAll(".sidebarLink"),i=0,length=links.length;i',html+=Globalize.translate("HeaderMedia"),html+="",html+=items.map(function(i){var icon="folder",color="inherit",itemId=i.Id;"channels"==i.CollectionType?itemId="channels":"livetv"==i.CollectionType&&(itemId="livetv"),"photos"==i.CollectionType?(icon="photo_library",color="#009688"):"music"==i.CollectionType||"musicvideos"==i.CollectionType?(icon="library_music",color="#FB8521"):"books"==i.CollectionType?(icon="library_books",color="#1AA1E1"):"playlists"==i.CollectionType?(icon="view_list",color="#795548"):"games"==i.CollectionType?(icon="games",color="#F44336"):"movies"==i.CollectionType?(icon="video_library",color="#CE5043"):"channels"==i.CollectionType||"Channel"==i.Type?(icon="videocam",color="#E91E63"):"tvshows"==i.CollectionType?(icon="tv",color="#4CAF50"):"livetv"==i.CollectionType&&(icon="live_tv",color="#293AAE"),icon=i.icon||icon;var onclick=i.onclick?" function(){"+i.onclick+"}":"null";return''+i.Name+""}).join(""),libraryMenuOptions.innerHTML=html;for(var elem=libraryMenuOptions,sidebarLinks=elem.querySelectorAll(".sidebarLink"),i=0,length=sidebarLinks.length;i200&&setTimeout(function(){closeMainDrawer(),setTimeout(function(){action?action():Dashboard.navigate(link.href)},getNavigateDelay())},50),event.stopPropagation(),event.preventDefault(),!1)},onLogoutClicked:function(){return(new Date).getTime()-lastOpenTime>200&&(closeMainDrawer(),setTimeout(function(){Dashboard.logout()},getNavigateDelay())),!1},onHardwareMenuButtonClick:function(){toggleMainDrawer()},onSettingsClicked:function(event){return 1!=event.which||(Dashboard.navigate("dashboard.html"),!1)},setTabs:function(type,selectedIndex,builder){var viewMenuBarTabs;return type?(viewMenuBarTabs=document.querySelector(".viewMenuBarTabs"),LibraryMenu.tabType||viewMenuBarTabs.classList.remove("hide"),void require(["emby-tabs","emby-button"],function(){if(LibraryMenu.tabType!=type){var index=0;return viewMenuBarTabs.innerHTML='
'+builder().map(function(t){var tabClass=selectedIndex==index?"emby-tab-button emby-tab-button-active":"emby-tab-button",tabHtml='";return index++,tabHtml}).join("")+"
",document.body.classList.add("withTallToolbar"),void(LibraryMenu.tabType=type)}viewMenuBarTabs.querySelector('[is="emby-tabs"]').selectedIndex(selectedIndex),LibraryMenu.tabType=type})):void(LibraryMenu.tabType&&(document.body.classList.remove("withTallToolbar"),viewMenuBarTabs=document.querySelector(".viewMenuBarTabs"),viewMenuBarTabs.innerHTML="",viewMenuBarTabs.classList.add("hide"),LibraryMenu.tabType=null))},setTitle:function(title){var html=title,page=viewManager.currentView();if(page){var helpUrl=page.getAttribute("data-helpurl");helpUrl&&(html+='")}var libraryMenuButtonText=document.querySelector(".libraryMenuButtonText");libraryMenuButtonText&&(libraryMenuButtonText.innerHTML=html),document.title=title||"Emby"},setTransparentMenu:function(transparent){var viewMenuBar=document.querySelector(".viewMenuBar");viewMenuBar&&(transparent?viewMenuBar.classList.add("semiTransparent"):viewMenuBar.classList.remove("semiTransparent"))}},pageClassOn("pagebeforeshow","page",function(e){var page=this;page.classList.contains("withTabs")||(LibraryMenu.setTabs(null),page.classList.contains("pageWithAbsoluteTabs")?document.body.classList.add("withTallToolbar"):document.body.classList.remove("withTallToolbar"))}),pageClassOn("pageshow","page",function(e){var page=this,isDashboardPage=page.classList.contains("type-interior");isDashboardPage?(mainDrawerButton&&mainDrawerButton.classList.remove("hide"),refreshDashboardInfoInDrawer(page)):(mainDrawerButton&&(enableLibraryNavDrawer?mainDrawerButton.classList.remove("hide"):mainDrawerButton.classList.add("hide")),(navDrawerElement&&navDrawerElement.classList.contains("adminDrawer")||!navDrawerElement&&enableLibraryNavDrawer)&&refreshLibraryDrawer()),setDrawerClass(page),updateViewMenuBar(page),e.detail.isRestored||window.scrollTo(0,0),updateTitle(page),updateBackButton(page),page.classList.contains("libraryPage")?(document.body.classList.add("libraryDocument"),document.body.classList.remove("dashboardDocument"),document.body.classList.remove("hideMainDrawer")):isDashboardPage?(document.body.classList.remove("libraryDocument"),document.body.classList.add("dashboardDocument"),document.body.classList.remove("hideMainDrawer")):(document.body.classList.remove("libraryDocument"),document.body.classList.remove("dashboardDocument"),document.body.classList.add("hideMainDrawer")),updateLibraryNavLinks(page)}),window.ApiClient&&initializeApiClient(window.ApiClient),renderHeader(),Events.on(ConnectionManager,"apiclientcreated",function(e,apiClient){initializeApiClient(apiClient)}),Events.on(ConnectionManager,"localusersignedin",function(e,user){setDrawerClass(),ConnectionManager.user(ConnectionManager.getApiClient(user.ServerId)).then(function(user){refreshLibraryDrawer(user),updateUserInHeader(user)})}),Events.on(ConnectionManager,"localusersignedout",updateUserInHeader),Events.on(playbackManager,"playerchange",updateCastIcon),setDrawerClass(),enableBottomTabs&&require(["appfooter-shared","dockedtabs"],function(footer,dockedtabs){new dockedtabs({appFooter:footer})}),LibraryMenu}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvchannel.js b/dashboard-ui/scripts/livetvchannel.js index 507f0233bc..95781e273d 100644 --- a/dashboard-ui/scripts/livetvchannel.js +++ b/dashboard-ui/scripts/livetvchannel.js @@ -1,73 +1 @@ -define(['datetime', 'listView'], function (datetime, listView) { - 'use strict'; - - function isSameDay(date1, date2) { - - return date1.toDateString() === date2.toDateString(); - } - - function renderPrograms(page, result) { - - var html = ''; - var currentItems = []; - var currentStartDate = null; - - for (var i = 0, length = result.Items.length; i < length; i++) { - - var item = result.Items[i]; - - var itemStartDate = datetime.parseISO8601Date(item.StartDate); - - if (!currentStartDate || !isSameDay(currentStartDate, itemStartDate)) { - - if (currentItems.length) { - - html += '

' + datetime.toLocaleDateString(currentStartDate, { weekday: 'long', month: 'long', day: 'numeric' }) + '

'; - - html += '
' + listView.getListViewHtml({ - items: currentItems, - enableUserDataButtons: false, - showParentTitle: true, - image: false, - showProgramTime: true, - mediaInfo: false, - parentTitleWithTitle: true - - }) + '
'; - } - - currentStartDate = itemStartDate; - currentItems = []; - } - - currentItems.push(item); - } - - page.querySelector('#childrenContent').innerHTML = html; - } - - function loadPrograms(page, channelId) { - - ApiClient.getLiveTvPrograms({ - - ChannelIds: channelId, - UserId: Dashboard.getCurrentUserId(), - HasAired: false, - SortBy: "StartDate", - EnableTotalRecordCount: false, - EnableImages: false, - ImageTypeLimit: 0, - EnableUserData: false - - }).then(function (result) { - - renderPrograms(page, result); - Dashboard.hideLoadingMsg(); - }); - } - - return { - renderPrograms: loadPrograms - }; - -}); \ No newline at end of file +define(["datetime","listView"],function(datetime,listView){"use strict";function isSameDay(date1,date2){return date1.toDateString()===date2.toDateString()}function renderPrograms(page,result){for(var html="",currentItems=[],currentStartDate=null,i=0,length=result.Items.length;i"+datetime.toLocaleDateString(currentStartDate,{weekday:"long",month:"long",day:"numeric"})+"",html+='
'+listView.getListViewHtml({items:currentItems,enableUserDataButtons:!1,showParentTitle:!0,image:!1,showProgramTime:!0,mediaInfo:!1,parentTitleWithTitle:!0})+"
"),currentStartDate=itemStartDate,currentItems=[]),currentItems.push(item)}page.querySelector("#childrenContent").innerHTML=html}function loadPrograms(page,channelId){ApiClient.getLiveTvPrograms({ChannelIds:channelId,UserId:Dashboard.getCurrentUserId(),HasAired:!1,SortBy:"StartDate",EnableTotalRecordCount:!1,EnableImages:!1,ImageTypeLimit:0,EnableUserData:!1}).then(function(result){renderPrograms(page,result),Dashboard.hideLoadingMsg()})}return{renderPrograms:loadPrograms}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvchannels.js b/dashboard-ui/scripts/livetvchannels.js index cf73495acb..f07a81b620 100644 --- a/dashboard-ui/scripts/livetvchannels.js +++ b/dashboard-ui/scripts/livetvchannels.js @@ -1,141 +1 @@ -define(['cardBuilder', 'imageLoader', 'emby-itemscontainer'], function (cardBuilder, imageLoader) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - StartIndex: 0, - Limit: LibraryBrowser.getDefaultPageSize(), - Fields: "PrimaryImageAspectRatio" - } - }; - - LibraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = LibraryBrowser.getSavedQueryKey('channels'); - } - return context.savedQueryKey; - } - - function getChannelsHtml(channels) { - - return cardBuilder.getCardsHtml({ - items: channels, - shape: "square", - showTitle: true, - lazy: true, - cardLayout: true, - showDetailsMenu: true, - showCurrentProgram: true - }); - } - - function renderChannels(context, result) { - - var query = getQuery(context); - - context.querySelector('.paging').innerHTML = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - filterButton: false - }); - - var html = getChannelsHtml(result.Items); - - var elem = context.querySelector('#items'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - var i, length; - var elems; - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(context); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(context); - } - - elems = context.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = context.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - LibraryBrowser.saveQueryValues(getSavedQueryKey(context), query); - } - - function showFilterMenu(context) { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(context), - mode: 'livetvchannels' - }); - - Events.on(filterDialog, 'filterchange', function () { - reloadItems(context); - }); - - filterDialog.show(); - }); - } - - function reloadItems(context) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(context); - - query.UserId = Dashboard.getCurrentUserId(); - - ApiClient.getLiveTvChannels(query).then(function (result) { - - renderChannels(context, result); - - Dashboard.hideLoadingMsg(); - }); - } - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - showFilterMenu(tabContent); - }); - - self.renderTab = function () { - - reloadItems(tabContent); - }; - }; - -}); \ No newline at end of file +define(["cardBuilder","imageLoader","emby-itemscontainer"],function(cardBuilder,imageLoader){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{StartIndex:0,Limit:LibraryBrowser.getDefaultPageSize(),Fields:"PrimaryImageAspectRatio"}},LibraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=LibraryBrowser.getSavedQueryKey("channels")),context.savedQueryKey}function getChannelsHtml(channels){return cardBuilder.getCardsHtml({items:channels,shape:"square",showTitle:!0,lazy:!0,cardLayout:!0,showDetailsMenu:!0,showCurrentProgram:!0})}function renderChannels(context,result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(context)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(context)}var query=getQuery(context);context.querySelector(".paging").innerHTML=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,filterButton:!1});var html=getChannelsHtml(result.Items),elem=context.querySelector("#items");elem.innerHTML=html,imageLoader.lazyChildren(elem);var i,length,elems;for(elems=context.querySelectorAll(".btnNextPage"),i=0,length=elems.length;i'; - } - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = appHost.preferVisualCards || supportsImageAnalysis; - - html += cardBuilder.getCardsHtml({ - items: group.items, - shape: getBackdropShape(), - showParentTitleOrTitle: true, - showAirTime: true, - showAirEndTime: true, - showChannelName: true, - cardLayout: cardLayout, - centerText: !cardLayout, - vibrant: supportsImageAnalysis, - action: 'edit', - cardFooterAside: 'none', - preferThumb: true, - coverImage: true, - overlayText: false - - }); - html += '
'; - - if (group.name) { - html += '
'; - } - } - - return Promise.resolve(html); - } - - window.LiveTvHelpers = { - - getTimersHtml: getTimersHtml - - }; -}); \ No newline at end of file +define(["datetime","cardBuilder","apphost"],function(datetime,cardBuilder,appHost){"use strict";function enableScrollX(){return browserInfo.mobile}function getBackdropShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function getTimersHtml(timers,options){options=options||{};var i,length,items=timers.map(function(t){return t.Type="Timer",t}),groups=[],currentGroupName="",currentGroup=[];for(i=0,length=items.length;i',html+='

'+group.name+"

"),html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=appHost.preferVisualCards||supportsImageAnalysis;html+=cardBuilder.getCardsHtml({items:group.items,shape:getBackdropShape(),showParentTitleOrTitle:!0,showAirTime:!0,showAirEndTime:!0,showChannelName:!0,cardLayout:cardLayout,centerText:!cardLayout,vibrant:supportsImageAnalysis,action:"edit",cardFooterAside:"none",preferThumb:!0,coverImage:!0,overlayText:!1}),html+="
",group.name&&(html+="
")}return Promise.resolve(html)}window.LiveTvHelpers={getTimersHtml:getTimersHtml}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvguide.js b/dashboard-ui/scripts/livetvguide.js index 42cb4b9acd..0392537a39 100644 --- a/dashboard-ui/scripts/livetvguide.js +++ b/dashboard-ui/scripts/livetvguide.js @@ -1,26 +1 @@ -define(['tvguide'], function (tvguide) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var guideInstance; - self.renderTab = function () { - if (!guideInstance) { - guideInstance = new tvguide({ - element: tabContent - }); - } - }; - self.onShow = function () { - if (guideInstance) { - guideInstance.resume(); - } - }; - self.onHide = function () { - if (guideInstance) { - guideInstance.pause(); - } - }; - }; -}); \ No newline at end of file +define(["tvguide"],function(tvguide){"use strict";return function(view,params,tabContent){var guideInstance,self=this;self.renderTab=function(){guideInstance||(guideInstance=new tvguide({element:tabContent}))},self.onShow=function(){guideInstance&&guideInstance.resume()},self.onHide=function(){guideInstance&&guideInstance.pause()}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvguideprovider.js b/dashboard-ui/scripts/livetvguideprovider.js index 8510f983e0..b5179e4724 100644 --- a/dashboard-ui/scripts/livetvguideprovider.js +++ b/dashboard-ui/scripts/livetvguideprovider.js @@ -1,51 +1 @@ -define(['events'], function (events) { - 'use strict'; - - function onListingsSubmitted() { - - Dashboard.navigate('livetvstatus.html'); - } - - function init(page, type, providerId) { - - var url = 'components/tvproviders/' + type + '.js'; - - require([url], function (factory) { - - var instance = new factory(page, providerId, { - }); - - events.on(instance, 'submitted', onListingsSubmitted); - - instance.init(); - }); - } - - function loadTemplate(page, type, providerId) { - - var xhr = new XMLHttpRequest(); - xhr.open('GET', 'components/tvproviders/' + type + '.template.html', true); - - xhr.onload = function (e) { - - var html = this.response; - var elem = page.querySelector('.providerTemplate'); - elem.innerHTML = Globalize.translateDocument(html); - - init(page, type, providerId); - } - - xhr.send(); - } - - pageIdOn('pageshow', "liveTvGuideProviderPage", function () { - - Dashboard.showLoadingMsg(); - - var providerId = getParameterByName('id'); - var type = getParameterByName('type'); - var page = this; - loadTemplate(page, type, providerId); - }); - -}); +define(["events"],function(events){"use strict";function onListingsSubmitted(){Dashboard.navigate("livetvstatus.html")}function init(page,type,providerId){var url="components/tvproviders/"+type+".js";require([url],function(factory){var instance=new factory(page,providerId,{});events.on(instance,"submitted",onListingsSubmitted),instance.init()})}function loadTemplate(page,type,providerId){var xhr=new XMLHttpRequest;xhr.open("GET","components/tvproviders/"+type+".template.html",!0),xhr.onload=function(e){var html=this.response,elem=page.querySelector(".providerTemplate");elem.innerHTML=Globalize.translateDocument(html),init(page,type,providerId)},xhr.send()}pageIdOn("pageshow","liveTvGuideProviderPage",function(){Dashboard.showLoadingMsg();var providerId=getParameterByName("id"),type=getParameterByName("type"),page=this;loadTemplate(page,type,providerId)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvitems.js b/dashboard-ui/scripts/livetvitems.js index 10ed04eaa5..f01b4a9b6d 100644 --- a/dashboard-ui/scripts/livetvitems.js +++ b/dashboard-ui/scripts/livetvitems.js @@ -1,187 +1 @@ -define(['cardBuilder', 'apphost', 'imageLoader', 'libraryBrowser', 'emby-itemscontainer'], function (cardBuilder, appHost, imageLoader, libraryBrowser) { - 'use strict'; - - return function (view, params) { - - // The base query options - var query = { - UserId: Dashboard.getCurrentUserId(), - StartIndex: 0, - Fields: "ChannelInfo", - Limit: libraryBrowser.getDefaultPageSize() - }; - - if (params.type == 'Recordings') { - query.IsInProgress = false; - - if (params.groupid) { - query.GroupId = params.groupid; - } - - } else if (params.type == 'RecordingSeries') { - query.SortOrder = 'SortName'; - query.SortOrder = 'Ascending'; - } else { - query.HasAired = false; - query.SortBy = 'StartDate,SortName'; - query.SortOrder = 'Ascending'; - } - - function getSavedQueryKey() { - return libraryBrowser.getSavedQueryKey(); - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var promise = params.type == 'Recordings' ? - ApiClient.getLiveTvRecordings(query) : - params.type == 'RecordingSeries' ? - ApiClient.getLiveTvRecordingSeries(query) : - params.IsAiring == 'true' ? - ApiClient.getLiveTvRecommendedPrograms(query) : - ApiClient.getLiveTvPrograms(query); - - promise.then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - var pagingHtml = libraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false - }); - - page.querySelector('.listTopPaging').innerHTML = pagingHtml; - - var supportsImageAnalysis = appHost.supports('imageanalysis') && (params.type == 'Recordings' || params.type == 'RecordingSeries'); - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: query.IsMovie || params.type == 'RecordingSeries' ? 'portrait' : "backdrop", - preferThumb: !query.IsMovie && params.type != 'RecordingSeries', - inheritThumb: params.type == 'Recordings', - context: 'livetv', - centerText: !supportsImageAnalysis, - lazy: true, - overlayText: false, - showParentTitleOrTitle: true, - showTitle: false, - showParentTitle: query.IsSeries !== false && !query.IsMovie, - showAirTime: params.type != 'Recordings' && params.type != 'RecordingSeries', - showAirDateTime: params.type != 'Recordings' && params.type != 'RecordingSeries', - showChannelName: params.type != 'Recordings' && params.type != 'RecordingSeries', - overlayMoreButton: !supportsImageAnalysis, - showYear: query.IsMovie && params.type == 'Recordings', - showSeriesYear: params.type === 'RecordingSeries', - coverImage: true, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - }); - - var elem = page.querySelector('.itemsContainer'); - elem.innerHTML = html + pagingHtml; - imageLoader.lazyChildren(elem); - - var i, length; - var elems; - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(page); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(page); - } - - elems = page.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = page.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - libraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - view.addEventListener('viewbeforeshow', function () { - - query.ParentId = LibraryMenu.getTopParentId(); - - var page = this; - - if (params.IsMovie == 'true') { - query.IsMovie = true; - } - else if (params.IsMovie == 'false') { - query.IsMovie = false; - } - if (params.IsSports == 'true') { - query.IsSports = true; - } - else if (params.IsSports == 'false') { - query.IsSports = false; - } - if (params.IsKids == 'true') { - query.IsKids = true; - } - else if (params.IsKids == 'false') { - query.IsKids = false; - } - if (params.IsAiring == 'true') { - query.IsAiring = true; - } - else if (params.IsAiring == 'false') { - query.IsAiring = false; - } - - if (params.type == 'Recordings') { - - if (params.IsMovie == 'true') { - LibraryMenu.setTitle(Globalize.translate('TabMovies')); - } else if (params.IsSports == 'true') { - LibraryMenu.setTitle(Globalize.translate('Sports')); - } else if (params.IsKids == 'true') { - LibraryMenu.setTitle(Globalize.translate('HeaderForKids')); - } else { - LibraryMenu.setTitle(Globalize.translate('TabRecordings')); - } - - } else if (params.type == 'RecordingSeries') { - - LibraryMenu.setTitle(Globalize.translate('TabSeries')); - } else { - - if (params.IsMovie == 'true') { - LibraryMenu.setTitle(Globalize.translate('HeaderUpcomingMovies')); - } else if (params.IsSports == 'true') { - LibraryMenu.setTitle(Globalize.translate('HeaderUpcomingSports')); - } else if (params.IsKids == 'true') { - LibraryMenu.setTitle(Globalize.translate('HeaderUpcomingForKids')); - } else if (params.IsAiring == 'true') { - LibraryMenu.setTitle(Globalize.translate('HeaderWhatsOnTV')); - } else { - LibraryMenu.setTitle(Globalize.translate('HeaderUpcomingPrograms')); - } - } - - var viewkey = getSavedQueryKey(); - - libraryBrowser.loadSavedQueryValues(viewkey, query); - - reloadItems(page); - }); - }; -}); \ No newline at end of file +define(["cardBuilder","apphost","imageLoader","libraryBrowser","emby-itemscontainer"],function(cardBuilder,appHost,imageLoader,libraryBrowser){"use strict";return function(view,params){function getSavedQueryKey(){return libraryBrowser.getSavedQueryKey()}function reloadItems(page){Dashboard.showLoadingMsg();var promise="Recordings"==params.type?ApiClient.getLiveTvRecordings(query):"RecordingSeries"==params.type?ApiClient.getLiveTvRecordingSeries(query):"true"==params.IsAiring?ApiClient.getLiveTvRecommendedPrograms(query):ApiClient.getLiveTvPrograms(query);promise.then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(page)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(page)}window.scrollTo(0,0);var html="",pagingHtml=libraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1});page.querySelector(".listTopPaging").innerHTML=pagingHtml;var supportsImageAnalysis=appHost.supports("imageanalysis")&&("Recordings"==params.type||"RecordingSeries"==params.type);html=cardBuilder.getCardsHtml({items:result.Items,shape:query.IsMovie||"RecordingSeries"==params.type?"portrait":"backdrop",preferThumb:!query.IsMovie&&"RecordingSeries"!=params.type,inheritThumb:"Recordings"==params.type,context:"livetv",centerText:!supportsImageAnalysis,lazy:!0,overlayText:!1,showParentTitleOrTitle:!0,showTitle:!1,showParentTitle:query.IsSeries!==!1&&!query.IsMovie,showAirTime:"Recordings"!=params.type&&"RecordingSeries"!=params.type,showAirDateTime:"Recordings"!=params.type&&"RecordingSeries"!=params.type,showChannelName:"Recordings"!=params.type&&"RecordingSeries"!=params.type,overlayMoreButton:!supportsImageAnalysis,showYear:query.IsMovie&&"Recordings"==params.type,showSeriesYear:"RecordingSeries"===params.type,coverImage:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis});var elem=page.querySelector(".itemsContainer");elem.innerHTML=html+pagingHtml,imageLoader.lazyChildren(elem);var i,length,elems;for(elems=page.querySelectorAll(".btnNextPage"),i=0,length=elems.length;i'; - - html += '
'; - html += group.Name; - html += '
'; - - html += '
'; - if (group.RecordingCount == 1) { - html += Globalize.translate('ValueItemCount', group.RecordingCount); - } else { - html += Globalize.translate('ValueItemCountPlural', group.RecordingCount); - } - html += '
'; - - html += ''; - html += ''; - html += ''; - - return html; - } - - function renderRecordingGroups(context, groups) { - - if (groups.length) { - context.querySelector('#recordingGroups').classList.remove('hide'); - } else { - context.querySelector('#recordingGroups').classList.add('hide'); - } - - var html = ''; - - html += '
'; - - for (var i = 0, length = groups.length; i < length; i++) { - - html += getRecordingGroupHtml(groups[i]); - } - - html += '
'; - - context.querySelector('#recordingGroupItems').innerHTML = html; - - Dashboard.hideLoadingMsg(); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function renderRecordings(elem, recordings, cardOptions) { - - if (recordings.length) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - - var recordingItems = elem.querySelector('.recordingItems'); - - if (enableScrollX()) { - recordingItems.classList.add('hiddenScrollX'); - recordingItems.classList.remove('vertical-wrap'); - } else { - recordingItems.classList.remove('hiddenScrollX'); - recordingItems.classList.add('vertical-wrap'); - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = appHost.preferVisualCards || supportsImageAnalysis; - - recordingItems.innerHTML = cardBuilder.getCardsHtml(Object.assign({ - items: recordings, - shape: (enableScrollX() ? 'autooverflow' : 'auto'), - showTitle: true, - showParentTitle: true, - coverImage: true, - lazy: true, - cardLayout: cardLayout, - centerText: !cardLayout, - vibrant: supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - preferThumb: 'auto', - overlayText: false - - }, cardOptions || {})); - - imageLoader.lazyChildren(recordingItems); - } - - function getBackdropShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function renderActiveRecordings(context, promise) { - - promise.then(function (result) { - - // The IsActive param is new, so handle older servers that don't support it - if (result.Items.length && result.Items[0].Status != 'InProgress') { - result.Items = []; - } - - renderRecordings(context.querySelector('#activeRecordings'), result.Items, { - shape: getBackdropShape(), - showParentTitle: false, - showTitle: true, - showAirTime: true, - showAirEndTime: true, - showChannelName: true, - cardLayout: true, - vibrant: true, - preferThumb: true, - coverImage: true - }); - }); - } - - function renderLatestRecordings(context, promise) { - - promise.then(function (result) { - - renderRecordings(context.querySelector('#latestRecordings'), result.Items, { - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showYear: true, - lines: 2 - }); - - Dashboard.hideLoadingMsg(); - }); - } - - function renderMovieRecordings(context, promise) { - - promise.then(function (result) { - - renderRecordings(context.querySelector('#movieRecordings'), result.Items, { - showYear: true, - showParentTitle: false - }); - }); - } - - function renderEpisodeRecordings(context, promise) { - - promise.then(function (result) { - - renderRecordings(context.querySelector('#episodeRecordings'), result.Items, { - showSeriesYear: true, - showParentTitle: false - }); - }); - } - - function renderSportsRecordings(context, promise) { - - promise.then(function (result) { - - renderRecordings(context.querySelector('#sportsRecordings'), result.Items, { - showYear: true, - showParentTitle: false - }); - }); - } - - function renderKidsRecordings(context, promise) { - - promise.then(function (result) { - - renderRecordings(context.querySelector('#kidsRecordings'), result.Items, { - showYear: true, - showParentTitle: false - }); - }); - } - - function onMoreClick(e) { - - var type = this.getAttribute('data-type'); - - switch (type) { - case 'latest': - Dashboard.navigate('livetvitems.html?type=Recordings'); - break; - case 'movies': - Dashboard.navigate('livetvitems.html?type=Recordings&IsMovie=true'); - break; - case 'episodes': - Dashboard.navigate('livetvitems.html?type=RecordingSeries'); - break; - case 'programs': - Dashboard.navigate('livetvitems.html?type=Recordings&IsSeries=false&IsMovie=false'); - break; - case 'kids': - Dashboard.navigate('livetvitems.html?type=Recordings&IsKids=true'); - break; - case 'sports': - Dashboard.navigate('livetvitems.html?type=Recordings&IsSports=true'); - break; - default: - break; - } - } - - return function (view, params, tabContent) { - - var self = this; - var activeRecordingsPromise; - var sportsPromise; - var kidsPromise; - var moviesPromise; - var seriesPromise; - var latestPromise; - var lastFullRender = 0; - - categorysyncbuttons.init(tabContent); - - var moreButtons = tabContent.querySelectorAll('.more'); - for (var i = 0, length = moreButtons.length; i < length; i++) { - moreButtons[i].addEventListener('click', onMoreClick); - } - tabContent.querySelector('#activeRecordings .recordingItems').addEventListener('timercancelled', function () { - self.preRender(); - self.renderTab(); - }); - - function enableFullRender() { - return (new Date().getTime() - lastFullRender) > 300000; - } - - self.preRender = function () { - - activeRecordingsPromise = ApiClient.getLiveTvRecordings({ - - UserId: Dashboard.getCurrentUserId(), - IsInProgress: true, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - EnableImageTypes: "Primary,Thumb,Backdrop" - }); - - if (!enableFullRender()) { - return; - } - - latestPromise = ApiClient.getLiveTvRecordings({ - - UserId: Dashboard.getCurrentUserId(), - Limit: enableScrollX() ? 12 : 8, - IsInProgress: false, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - EnableImageTypes: "Primary,Thumb,Backdrop" - }); - - moviesPromise = ApiClient.getLiveTvRecordings({ - - UserId: Dashboard.getCurrentUserId(), - Limit: enableScrollX() ? 12 : 8, - IsInProgress: false, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - IsMovie: true - }); - - seriesPromise = ApiClient.getLiveTvRecordingSeries({ - - UserId: Dashboard.getCurrentUserId(), - Limit: enableScrollX() ? 12 : 8, - IsInProgress: false, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - IsSeries: true - }); - - kidsPromise = ApiClient.getLiveTvRecordings({ - - UserId: Dashboard.getCurrentUserId(), - Limit: enableScrollX() ? 12 : 8, - IsInProgress: false, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - IsKids: true - }); - - sportsPromise = ApiClient.getLiveTvRecordings({ - UserId: Dashboard.getCurrentUserId(), - Limit: enableScrollX() ? 12 : 8, - IsInProgress: false, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - IsSports: true - }); - }; - - self.renderTab = function () { - - renderActiveRecordings(tabContent, activeRecordingsPromise); - - if (enableFullRender()) { - Dashboard.showLoadingMsg(); - - renderLatestRecordings(tabContent, latestPromise); - renderMovieRecordings(tabContent, moviesPromise); - renderEpisodeRecordings(tabContent, seriesPromise); - renderSportsRecordings(tabContent, sportsPromise); - renderKidsRecordings(tabContent, kidsPromise); - - ApiClient.getLiveTvRecordingGroups({ - - userId: Dashboard.getCurrentUserId() - - }).then(function (result) { - - renderRecordingGroups(tabContent, result.Items); - }); - - lastFullRender = new Date().getTime(); - } - }; - }; - -}); \ No newline at end of file +define(["components/categorysyncbuttons","cardBuilder","apphost","imageLoader","scripts/livetvcomponents","emby-button","listViewStyle","emby-itemscontainer"],function(categorysyncbuttons,cardBuilder,appHost,imageLoader){"use strict";function getRecordingGroupHtml(group){var html="";return html+='"}function renderRecordingGroups(context,groups){groups.length?context.querySelector("#recordingGroups").classList.remove("hide"):context.querySelector("#recordingGroups").classList.add("hide");var html="";html+='
';for(var i=0,length=groups.length;i",context.querySelector("#recordingGroupItems").innerHTML=html,Dashboard.hideLoadingMsg()}function enableScrollX(){return browserInfo.mobile}function renderRecordings(elem,recordings,cardOptions){recordings.length?elem.classList.remove("hide"):elem.classList.add("hide");var recordingItems=elem.querySelector(".recordingItems");enableScrollX()?(recordingItems.classList.add("hiddenScrollX"),recordingItems.classList.remove("vertical-wrap")):(recordingItems.classList.remove("hiddenScrollX"),recordingItems.classList.add("vertical-wrap"));var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=appHost.preferVisualCards||supportsImageAnalysis;recordingItems.innerHTML=cardBuilder.getCardsHtml(Object.assign({items:recordings,shape:enableScrollX()?"autooverflow":"auto",showTitle:!0,showParentTitle:!0,coverImage:!0,lazy:!0,cardLayout:cardLayout,centerText:!cardLayout,vibrant:supportsImageAnalysis,allowBottomPadding:!enableScrollX(),preferThumb:"auto",overlayText:!1},cardOptions||{})),imageLoader.lazyChildren(recordingItems)}function getBackdropShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function renderActiveRecordings(context,promise){promise.then(function(result){result.Items.length&&"InProgress"!=result.Items[0].Status&&(result.Items=[]),renderRecordings(context.querySelector("#activeRecordings"),result.Items,{shape:getBackdropShape(),showParentTitle:!1,showTitle:!0,showAirTime:!0,showAirEndTime:!0,showChannelName:!0,cardLayout:!0,vibrant:!0,preferThumb:!0,coverImage:!0})})}function renderLatestRecordings(context,promise){promise.then(function(result){renderRecordings(context.querySelector("#latestRecordings"),result.Items,{shape:enableScrollX()?"overflowBackdrop":"backdrop",showYear:!0,lines:2}),Dashboard.hideLoadingMsg()})}function renderMovieRecordings(context,promise){promise.then(function(result){renderRecordings(context.querySelector("#movieRecordings"),result.Items,{showYear:!0,showParentTitle:!1})})}function renderEpisodeRecordings(context,promise){promise.then(function(result){renderRecordings(context.querySelector("#episodeRecordings"),result.Items,{showSeriesYear:!0,showParentTitle:!1})})}function renderSportsRecordings(context,promise){promise.then(function(result){renderRecordings(context.querySelector("#sportsRecordings"),result.Items,{showYear:!0,showParentTitle:!1})})}function renderKidsRecordings(context,promise){promise.then(function(result){renderRecordings(context.querySelector("#kidsRecordings"),result.Items,{showYear:!0,showParentTitle:!1})})}function onMoreClick(e){var type=this.getAttribute("data-type");switch(type){case"latest":Dashboard.navigate("livetvitems.html?type=Recordings");break;case"movies":Dashboard.navigate("livetvitems.html?type=Recordings&IsMovie=true");break;case"episodes":Dashboard.navigate("livetvitems.html?type=RecordingSeries");break;case"programs":Dashboard.navigate("livetvitems.html?type=Recordings&IsSeries=false&IsMovie=false");break;case"kids":Dashboard.navigate("livetvitems.html?type=Recordings&IsKids=true");break;case"sports":Dashboard.navigate("livetvitems.html?type=Recordings&IsSports=true")}}return function(view,params,tabContent){function enableFullRender(){return(new Date).getTime()-lastFullRender>3e5}var activeRecordingsPromise,sportsPromise,kidsPromise,moviesPromise,seriesPromise,latestPromise,self=this,lastFullRender=0;categorysyncbuttons.init(tabContent);for(var moreButtons=tabContent.querySelectorAll(".more"),i=0,length=moreButtons.length;i'; - html += Globalize.translate('StatusRecordingProgram').replace('{0}', tuner.ChannelName); - html += ''; - } else { - - html += Globalize.translate('StatusRecording'); - } - } - else if (tuner.Status == 'LiveTv') { - - if (tuner.ChannelName) { - - html += ''; - html += Globalize.translate('StatusWatchingProgram').replace('{0}', tuner.ChannelName); - html += ''; - } else { - - html += Globalize.translate('StatusWatching'); - } - } - else { - html += tuner.Status; - } - html += '
'; - - html += ''; - - if (tuner.CanReset) { - html += ''; - } - - html += ''; - } - - html += ''; - } - - if (tuners.length) { - page.querySelector('.tunerSection').classList.remove('hide'); - } else { - page.querySelector('.tunerSection').classList.add('hide'); - } - - var elem = $('.tunerList', page).html(html); - - $('.btnResetTuner', elem).on('click', function () { - - var id = this.getAttribute('data-tunerid'); - - resetTuner(page, id); - }); - } - - function getServiceHtml(service) { - - var html = ''; - html += '
'; - - var serviceUrl = service.HomePageUrl || '#'; - - html += '

' + service.Name + '

'; - - var versionHtml = service.Version || 'Unknown'; - - if (service.HasUpdateAvailable) { - versionHtml += ' ' + Globalize.translate('LiveTvUpdateAvailable') + ''; - } - else { - versionHtml += ' ' + Globalize.translate('LabelVersionUpToDate'); - } - - html += '

' + versionHtml + '

'; - - var status = service.Status; - - if (service.Status == 'Ok') { - - status = '' + status + ''; - } else { - - if (service.StatusMessage) { - status += ' (' + service.StatusMessage + ')'; - } - - status = '' + status + ''; - } - - html += '

' + Globalize.translate('ValueStatus', status) + '

'; - - html += '
'; - - return html; - } - - function loadPage(page, liveTvInfo) { - - if (liveTvInfo.IsEnabled) { - - $('.liveTvStatusContent', page).show(); - - } else { - $('.liveTvStatusContent', page).hide(); - } - - var servicesToDisplay = liveTvInfo.Services.filter(function (s) { - - return s.IsVisible; - - }); - - if (servicesToDisplay.length) { - $('.servicesSection', page).show(); - } else { - $('.servicesSection', page).hide(); - } - - $('.servicesList', page).html(servicesToDisplay.map(getServiceHtml).join('')); - - var tuners = []; - for (var i = 0, length = liveTvInfo.Services.length; i < length; i++) { - - for (var j = 0, numTuners = liveTvInfo.Services[i].Tuners.length; j < numTuners; j++) { - tuners.push(liveTvInfo.Services[i].Tuners[j]); - } - } - - renderTuners(page, tuners); - - ApiClient.getNamedConfiguration("livetv").then(function (config) { - - renderDevices(page, config.TunerHosts); - renderProviders(page, config.ListingProviders); - }); - - Dashboard.hideLoadingMsg(); - } - - function renderDevices(page, devices) { - - var html = ''; - - if (devices.length) { - html += '
'; - - for (var i = 0, length = devices.length; i < length; i++) { - - var device = devices[i]; - - var href = 'livetvtunerprovider-' + device.Type + '.html?id=' + device.Id; - - html += '
'; - - html += 'live_tv'; - - html += ''; - - html += ''; - html += '
'; - } - - html += '
'; - } - - var elem = $('.devicesList', page).html(html); - - $('.btnDeleteDevice', elem).on('click', function () { - - var id = this.getAttribute('data-id'); - - deleteDevice(page, id); - }); - } - - function deleteDevice(page, id) { - - var message = Globalize.translate('MessageConfirmDeleteTunerDevice'); - - require(['confirm'], function (confirm) { - - confirm(message, Globalize.translate('HeaderDeleteDevice')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl('LiveTv/TunerHosts', { - Id: id - }) - - }).then(function () { - - reload(page); - }); - }); - }); - } - - function reload(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getLiveTvInfo().then(function (liveTvInfo) { - - loadPage(page, liveTvInfo); - - }, function () { - - loadPage(page, { - Services: [], - IsEnabled: true - }); - }); - } - - function submitAddDeviceForm(page) { - - page.querySelector('.dlgAddDevice').close(); - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('LiveTv/TunerHosts'), - data: JSON.stringify({ - Type: $('#selectTunerDeviceType', page).val(), - Url: $('#txtDevicePath', page).val() - }), - contentType: "application/json" - - }).then(function () { - - reload(page); - - }, function () { - Dashboard.alert({ - message: Globalize.translate('ErrorAddingTunerDevice') - }); - }); - - } - - function renderProviders(page, providers) { - - var html = ''; - - if (providers.length) { - html += '
'; - - for (var i = 0, length = providers.length; i < length; i++) { - - var provider = providers[i]; - html += '
'; - - html += 'dvr'; - - html += ''; - html += ''; - html += '
'; - } - - html += '
'; - } - - var elem = $('.providerList', page).html(html); - - $('.btnOptions', elem).on('click', function () { - - var id = this.getAttribute('data-id'); - - showProviderOptions(page, id, this); - }); - } - - function showProviderOptions(page, providerId, button) { - - var items = []; - - items.push({ - name: Globalize.translate('ButtonDelete'), - id: 'delete' - }); - - items.push({ - name: Globalize.translate('MapChannels'), - id: 'map' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: items, - positionTo: button - - }).then(function (id) { - - switch (id) { - - case 'delete': - deleteProvider(page, providerId); - break; - case 'map': - mapChannels(page, providerId); - break; - default: - break; - } - }); - - }); - } - - function mapChannels(page, providerId) { - - require(['components/channelmapper/channelmapper'], function (channelmapper) { - new channelmapper({ - serverId: ApiClient.serverInfo().Id, - providerId: providerId - }).show(); - }); - } - - function deleteProvider(page, id) { - - var message = Globalize.translate('MessageConfirmDeleteGuideProvider'); - - require(['confirm'], function (confirm) { - - confirm(message, Globalize.translate('HeaderDeleteProvider')).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl('LiveTv/ListingProviders', { - Id: id - }) - - }).then(function () { - - reload(page); - - }, function () { - - reload(page); - }); - }); - }); - } - - function getTunerName(providerId) { - - providerId = providerId.toLowerCase(); - - switch (providerId) { - - case 'm3u': - return 'M3U'; - case 'hdhomerun': - return 'HDHomerun'; - case 'satip': - return 'DVB'; - default: - return 'Unknown'; - } - } - - function getProviderName(providerId) { - - providerId = providerId.toLowerCase(); - - switch (providerId) { - - case 'schedulesdirect': - return 'Schedules Direct'; - case 'xmltv': - return 'Xml TV'; - case 'emby': - return 'Emby Guide'; - default: - return 'Unknown'; - } - } - - function getProviderConfigurationUrl(providerId) { - - providerId = providerId.toLowerCase(); - - switch (providerId) { - - case 'xmltv': - return 'livetvguideprovider.html?type=xmltv'; - case 'schedulesdirect': - return 'livetvguideprovider.html?type=schedulesdirect'; - case 'emby': - return 'livetvguideprovider.html?type=emby'; - default: - break; - } - } - - function addProvider(button) { - - var menuItems = []; - - menuItems.push({ - name: 'Schedules Direct', - id: 'SchedulesDirect' - }); - - //menuItems.push({ - // name: 'Emby Guide', - // id: 'emby' - //}); - - menuItems.push({ - name: 'Xml TV', - id: 'xmltv' - }); - - menuItems.push({ - name: Globalize.translate('ButtonOther'), - id: 'other' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: button, - callback: function (id) { - - if (id == 'other') { - Dashboard.alert({ - message: Globalize.translate('ForAdditionalLiveTvOptions') - }); - } else { - Dashboard.navigate(getProviderConfigurationUrl(id)); - } - } - }); - - }); - } - - function addDevice(button) { - - var menuItems = []; - - //menuItems.push({ - // name: getTunerName('satip'), - // id: 'satip' - //}); - - menuItems.push({ - name: 'HDHomerun', - id: 'hdhomerun' - }); - - menuItems.push({ - name: getTunerName('m3u'), - id: 'm3u' - }); - - menuItems.push({ - name: Globalize.translate('ButtonOther'), - id: 'other' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: button, - callback: function (id) { - - if (id == 'other') { - Dashboard.alert({ - message: Globalize.translate('ForAdditionalLiveTvOptions') - }); - } else { - Dashboard.navigate('livetvtunerprovider-' + id + '.html'); - } - } - }); - - }); - } - - function getTabs() { - return [ - { - href: 'livetvstatus.html', - name: Globalize.translate('TabDevices') - }, - { - href: 'livetvsettings.html', - name: Globalize.translate('TabSettings') - }, - { - href: 'appservices.html?context=livetv', - name: Globalize.translate('TabServices') - }]; - } - - $(document).on('pageinit', "#liveTvStatusPage", function () { - - var page = this; - - $('.btnAddDevice', page).on('click', function () { - addDevice(this); - }); - - $('.formAddDevice', page).on('submit', function () { - submitAddDeviceForm(page); - return false; - }); - - $('.btnAddProvider', page).on('click', function () { - addProvider(this); - }); - - }).on('pageshow', "#liveTvStatusPage", function () { - - LibraryMenu.setTabs('livetvadmin', 0, getTabs); - var page = this; - - reload(page); - - // on here - taskButton({ - mode: 'on', - progressElem: page.querySelector('.refreshGuideProgress'), - taskKey: 'RefreshGuide', - button: page.querySelector('.btnRefresh') - }); - - }).on('pagehide', "#liveTvStatusPage", function () { - - var page = this; - - // off here - taskButton({ - mode: 'off', - progressElem: page.querySelector('.refreshGuideProgress'), - taskKey: 'RefreshGuide', - button: page.querySelector('.btnRefresh') - }); - - }); - -}); +define(["jQuery","scripts/taskbutton","listViewStyle"],function($,taskButton){"use strict";function resetTuner(page,id){var message=Globalize.translate("MessageConfirmResetTuner");require(["confirm"],function(confirm){confirm(message,Globalize.translate("HeaderResetTuner")).then(function(){Dashboard.showLoadingMsg(),ApiClient.resetLiveTvTuner(id).then(function(){Dashboard.hideLoadingMsg(),reload(page)})})})}function renderTuners(page,tuners){var html="";if(tuners.length){html+='
';for(var i=0,length=tuners.length;i',html+='live_tv',html+='
',html+='

',html+=tuner.Name,html+="

",html+='
',html+=tuner.SourceType,html+="
",html+='
',"RecordingTv"==tuner.Status?tuner.ChannelName?(html+='',html+=Globalize.translate("StatusRecordingProgram").replace("{0}",tuner.ChannelName),html+=""):html+=Globalize.translate("StatusRecording"):"LiveTv"==tuner.Status?tuner.ChannelName?(html+='',html+=Globalize.translate("StatusWatchingProgram").replace("{0}",tuner.ChannelName),html+=""):html+=Globalize.translate("StatusWatching"):html+=tuner.Status,html+="
",html+="
",tuner.CanReset&&(html+=''),html+="
"}html+=""}tuners.length?page.querySelector(".tunerSection").classList.remove("hide"):page.querySelector(".tunerSection").classList.add("hide");var elem=$(".tunerList",page).html(html);$(".btnResetTuner",elem).on("click",function(){var id=this.getAttribute("data-tunerid");resetTuner(page,id)})}function getServiceHtml(service){var html="";html+="
";var serviceUrl=service.HomePageUrl||"#";html+='

'+service.Name+"

";var versionHtml=service.Version||"Unknown";versionHtml+=service.HasUpdateAvailable?' '+Globalize.translate("LiveTvUpdateAvailable")+"":' '+Globalize.translate("LabelVersionUpToDate"),html+="

"+versionHtml+"

";var status=service.Status;return"Ok"==service.Status?status=''+status+"":(service.StatusMessage&&(status+=" ("+service.StatusMessage+")"),status=''+status+""),html+="

"+Globalize.translate("ValueStatus",status)+"

",html+="
"}function loadPage(page,liveTvInfo){liveTvInfo.IsEnabled?$(".liveTvStatusContent",page).show():$(".liveTvStatusContent",page).hide();var servicesToDisplay=liveTvInfo.Services.filter(function(s){return s.IsVisible});servicesToDisplay.length?$(".servicesSection",page).show():$(".servicesSection",page).hide(),$(".servicesList",page).html(servicesToDisplay.map(getServiceHtml).join(""));for(var tuners=[],i=0,length=liveTvInfo.Services.length;i',html+='live_tv',html+='",html+='',html+=""}html+=""}var elem=$(".devicesList",page).html(html);$(".btnDeleteDevice",elem).on("click",function(){var id=this.getAttribute("data-id");deleteDevice(page,id)})}function deleteDevice(page,id){var message=Globalize.translate("MessageConfirmDeleteTunerDevice");require(["confirm"],function(confirm){confirm(message,Globalize.translate("HeaderDeleteDevice")).then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("LiveTv/TunerHosts",{Id:id})}).then(function(){reload(page)})})})}function reload(page){Dashboard.showLoadingMsg(),ApiClient.getLiveTvInfo().then(function(liveTvInfo){loadPage(page,liveTvInfo)},function(){loadPage(page,{Services:[],IsEnabled:!0})})}function submitAddDeviceForm(page){page.querySelector(".dlgAddDevice").close(),Dashboard.showLoadingMsg(),ApiClient.ajax({type:"POST",url:ApiClient.getUrl("LiveTv/TunerHosts"),data:JSON.stringify({Type:$("#selectTunerDeviceType",page).val(),Url:$("#txtDevicePath",page).val()}),contentType:"application/json"}).then(function(){reload(page)},function(){Dashboard.alert({message:Globalize.translate("ErrorAddingTunerDevice")})})}function renderProviders(page,providers){var html="";if(providers.length){html+='
';for(var i=0,length=providers.length;i',html+='dvr',html+='",html+='',html+="
"}html+=""}var elem=$(".providerList",page).html(html);$(".btnOptions",elem).on("click",function(){var id=this.getAttribute("data-id");showProviderOptions(page,id,this)})}function showProviderOptions(page,providerId,button){var items=[];items.push({name:Globalize.translate("ButtonDelete"),id:"delete"}),items.push({name:Globalize.translate("MapChannels"),id:"map"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:items,positionTo:button}).then(function(id){switch(id){case"delete":deleteProvider(page,providerId);break;case"map":mapChannels(page,providerId)}})})}function mapChannels(page,providerId){require(["components/channelmapper/channelmapper"],function(channelmapper){new channelmapper({serverId:ApiClient.serverInfo().Id,providerId:providerId}).show()})}function deleteProvider(page,id){var message=Globalize.translate("MessageConfirmDeleteGuideProvider");require(["confirm"],function(confirm){confirm(message,Globalize.translate("HeaderDeleteProvider")).then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("LiveTv/ListingProviders",{Id:id})}).then(function(){reload(page)},function(){reload(page)})})})}function getTunerName(providerId){switch(providerId=providerId.toLowerCase()){case"m3u":return"M3U";case"hdhomerun":return"HDHomerun";case"satip":return"DVB";default:return"Unknown"}}function getProviderName(providerId){switch(providerId=providerId.toLowerCase()){case"schedulesdirect":return"Schedules Direct";case"xmltv":return"Xml TV";case"emby":return"Emby Guide";default:return"Unknown"}}function getProviderConfigurationUrl(providerId){switch(providerId=providerId.toLowerCase()){case"xmltv":return"livetvguideprovider.html?type=xmltv";case"schedulesdirect":return"livetvguideprovider.html?type=schedulesdirect";case"emby":return"livetvguideprovider.html?type=emby"}}function addProvider(button){var menuItems=[];menuItems.push({name:"Schedules Direct",id:"SchedulesDirect"}),menuItems.push({name:"Xml TV",id:"xmltv"}),menuItems.push({name:Globalize.translate("ButtonOther"),id:"other"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:button,callback:function(id){"other"==id?Dashboard.alert({message:Globalize.translate("ForAdditionalLiveTvOptions")}):Dashboard.navigate(getProviderConfigurationUrl(id))}})})}function addDevice(button){var menuItems=[];menuItems.push({name:"HDHomerun",id:"hdhomerun"}),menuItems.push({name:getTunerName("m3u"),id:"m3u"}),menuItems.push({name:Globalize.translate("ButtonOther"),id:"other"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:button,callback:function(id){"other"==id?Dashboard.alert({message:Globalize.translate("ForAdditionalLiveTvOptions")}):Dashboard.navigate("livetvtunerprovider-"+id+".html")}})})}function getTabs(){return[{href:"livetvstatus.html",name:Globalize.translate("TabDevices")},{href:"livetvsettings.html",name:Globalize.translate("TabSettings")},{href:"appservices.html?context=livetv",name:Globalize.translate("TabServices")}]}$(document).on("pageinit","#liveTvStatusPage",function(){var page=this;$(".btnAddDevice",page).on("click",function(){addDevice(this)}),$(".formAddDevice",page).on("submit",function(){return submitAddDeviceForm(page),!1}),$(".btnAddProvider",page).on("click",function(){addProvider(this)})}).on("pageshow","#liveTvStatusPage",function(){LibraryMenu.setTabs("livetvadmin",0,getTabs);var page=this;reload(page),taskButton({mode:"on",progressElem:page.querySelector(".refreshGuideProgress"),taskKey:"RefreshGuide",button:page.querySelector(".btnRefresh")})}).on("pagehide","#liveTvStatusPage",function(){var page=this;taskButton({mode:"off",progressElem:page.querySelector(".refreshGuideProgress"),taskKey:"RefreshGuide",button:page.querySelector(".btnRefresh")})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/livetvsuggested.js b/dashboard-ui/scripts/livetvsuggested.js index 27986721cc..3969af2bfd 100644 --- a/dashboard-ui/scripts/livetvsuggested.js +++ b/dashboard-ui/scripts/livetvsuggested.js @@ -1,399 +1 @@ -define(['libraryBrowser', 'cardBuilder', 'apphost', 'imageLoader', 'scrollStyles', 'emby-itemscontainer', 'emby-tabs', 'emby-button'], function (libraryBrowser, cardBuilder, appHost, imageLoader) { - 'use strict'; - - function enableScrollX() { - return browserInfo.mobile; - } - - function renderRecordings(elem, recordings, cardOptions) { - - if (recordings.length) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - - var recordingItems = elem.querySelector('.recordingItems'); - - if (enableScrollX()) { - recordingItems.classList.add('hiddenScrollX'); - recordingItems.classList.remove('vertical-wrap'); - } else { - recordingItems.classList.remove('hiddenScrollX'); - recordingItems.classList.add('vertical-wrap'); - } - - recordingItems.innerHTML = cardBuilder.getCardsHtml(Object.assign({ - items: recordings, - shape: (enableScrollX() ? 'autooverflow' : 'auto'), - showTitle: true, - showParentTitle: true, - coverImage: true, - lazy: true, - cardLayout: true, - vibrant: true, - allowBottomPadding: !enableScrollX(), - preferThumb: 'auto' - - }, cardOptions || {})); - - imageLoader.lazyChildren(recordingItems); - } - - function getBackdropShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function renderActiveRecordings(context, promise) { - - promise.then(function (result) { - - // The IsActive param is new, so handle older servers that don't support it - if (result.Items.length && result.Items[0].Status != 'InProgress') { - result.Items = []; - } - - renderRecordings(context.querySelector('#activeRecordings'), result.Items, { - shape: getBackdropShape(), - showParentTitle: false, - showTitle: true, - showAirTime: true, - showAirEndTime: true, - showChannelName: true, - cardLayout: true, - vibrant: true, - preferThumb: true, - coverImage: true, - overlayText: false - }); - }); - } - - function getPortraitShape() { - return enableScrollX() ? 'overflowPortrait' : 'portrait'; - } - - function getLimit() { - - return enableScrollX() ? 12 : 8; - } - - function loadRecommendedPrograms(page) { - - Dashboard.showLoadingMsg(); - - var limit = getLimit(); - if (enableScrollX()) { - limit *= 2; - } - - ApiClient.getLiveTvRecommendedPrograms({ - - userId: Dashboard.getCurrentUserId(), - IsAiring: true, - limit: limit, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Thumb,Backdrop", - EnableTotalRecordCount: false, - Fields: "ChannelInfo" - - }).then(function (result) { - - renderItems(page, result.Items, 'activeProgramItems', 'play', { - showAirDateTime: false, - showAirEndTime: true - }); - Dashboard.hideLoadingMsg(); - }); - } - - function reload(page, enableFullRender) { - - renderActiveRecordings(page, ApiClient.getLiveTvRecordings({ - UserId: Dashboard.getCurrentUserId(), - IsInProgress: true, - Fields: 'CanDelete,PrimaryImageAspectRatio,BasicSyncInfo', - EnableTotalRecordCount: false, - EnableImageTypes: "Primary,Thumb,Backdrop" - })); - - if (!enableFullRender) { - return; - } - - loadRecommendedPrograms(page); - - ApiClient.getLiveTvRecommendedPrograms({ - - userId: Dashboard.getCurrentUserId(), - IsAiring: false, - HasAired: false, - limit: getLimit(), - IsMovie: false, - IsSports: false, - IsKids: false, - IsSeries: true, - EnableTotalRecordCount: false, - Fields: "ChannelInfo", - EnableImageTypes: "Primary,Thumb" - - }).then(function (result) { - - renderItems(page, result.Items, 'upcomingProgramItems'); - }); - - ApiClient.getLiveTvRecommendedPrograms({ - - userId: Dashboard.getCurrentUserId(), - IsAiring: false, - HasAired: false, - limit: getLimit(), - IsMovie: true, - EnableTotalRecordCount: false, - Fields: "ChannelInfo", - EnableImageTypes: "Primary,Thumb" - - }).then(function (result) { - - renderItems(page, result.Items, 'upcomingTvMovieItems', null, { - shape: getPortraitShape(), - preferThumb: null - }); - }); - - ApiClient.getLiveTvRecommendedPrograms({ - - userId: Dashboard.getCurrentUserId(), - IsAiring: false, - HasAired: false, - limit: getLimit(), - IsSports: true, - EnableTotalRecordCount: false, - Fields: "ChannelInfo", - EnableImageTypes: "Primary,Thumb" - - }).then(function (result) { - - renderItems(page, result.Items, 'upcomingSportsItems'); - }); - - ApiClient.getLiveTvRecommendedPrograms({ - - userId: Dashboard.getCurrentUserId(), - IsAiring: false, - HasAired: false, - limit: getLimit(), - IsKids: true, - EnableTotalRecordCount: false, - Fields: "ChannelInfo", - EnableImageTypes: "Primary,Thumb" - - }).then(function (result) { - - renderItems(page, result.Items, 'upcomingKidsItems'); - }); - } - - function renderItems(page, items, sectionClass, overlayButton, cardOptions) { - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - cardOptions = cardOptions || {}; - - var html = cardBuilder.getCardsHtml(Object.assign({ - items: items, - preferThumb: true, - inheritThumb: false, - shape: (enableScrollX() ? 'overflowBackdrop' : 'backdrop'), - showParentTitleOrTitle: true, - showTitle: false, - centerText: !supportsImageAnalysis, - coverImage: true, - overlayText: false, - lazy: true, - overlayMoreButton: overlayButton != 'play' && !supportsImageAnalysis, - overlayPlayButton: overlayButton == 'play', - allowBottomPadding: !enableScrollX(), - showAirTime: true, - showAirDateTime: true, - showChannelName: true, - vibrant: true, - cardLayout: supportsImageAnalysis - - }, cardOptions)); - - var elem = page.querySelector('.' + sectionClass); - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - } - - return function (view, params) { - - var self = this; - var lastFullRender = 0; - function enableFullRender() { - return (new Date().getTime() - lastFullRender) > 300000; - } - - self.initTab = function () { - - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - - var containers = tabContent.querySelectorAll('.itemsContainer'); - - for (var i = 0, length = containers.length; i < length; i++) { - if (enableScrollX()) { - containers[i].classList.add('hiddenScrollX'); - containers[i].classList.remove('vertical-wrap'); - } else { - containers[i].classList.remove('hiddenScrollX'); - containers[i].classList.add('vertical-wrap'); - } - } - }; - - self.renderTab = function () { - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - - if (enableFullRender()) { - reload(tabContent, true); - lastFullRender = new Date().getTime(); - } else { - reload(tabContent); - } - }; - - var tabControllers = []; - var renderedTabs = []; - var currentTabController; - - function getTabController(page, index, callback) { - - var depends = []; - - switch (index) { - - case 0: - break; - case 1: - depends.push('scripts/livetvguide'); - break; - case 2: - depends.push('scripts/livetvchannels'); - break; - case 3: - depends.push('scripts/livetvrecordings'); - break; - case 4: - depends.push('scripts/livetvschedule'); - break; - case 5: - depends.push('scripts/livetvseriestimers'); - break; - default: - break; - } - - require(depends, function (controllerFactory) { - var tabContent; - if (index == 0) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - self.tabContent = tabContent; - } - var controller = tabControllers[index]; - if (!controller) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - controller = index ? new controllerFactory(view, params, tabContent) : self; - tabControllers[index] = controller; - - if (controller.initTab) { - controller.initTab(); - } - } - - callback(controller); - }); - } - - - function preLoadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - if (controller.preRender) { - controller.preRender(); - } - } - }); - } - - function loadTab(page, index) { - - getTabController(page, index, function (controller) { - - if (index === 1) { - document.body.classList.add('autoScrollY'); - } else { - document.body.classList.remove('autoScrollY'); - } - - if (renderedTabs.indexOf(index) == -1) { - - if (index === 1) { - renderedTabs.push(index); - } - controller.renderTab(); - } else { - if (controller.onShow) { - controller.onShow(); - } - } - currentTabController = controller; - }); - } - - var viewTabs = view.querySelector('.libraryViewNav'); - - libraryBrowser.configurePaperLibraryTabs(view, viewTabs, view.querySelectorAll('.pageTabContent'), [0, 2, 3, 4, 5]); - - viewTabs.addEventListener('beforetabchange', function (e) { - preLoadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - viewTabs.addEventListener('tabchange', function (e) { - - var previousTabController = tabControllers[parseInt(e.detail.previousIndex)]; - if (previousTabController && previousTabController.onHide) { - previousTabController.onHide(); - } - - loadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - view.addEventListener('viewbeforehide', function (e) { - - if (currentTabController && currentTabController.onHide) { - currentTabController.onHide(); - } - document.body.classList.remove('autoScrollY'); - }); - - require(["headroom-window"], function (headroom) { - headroom.add(viewTabs); - self.headroom = headroom; - }); - - view.addEventListener('viewdestroy', function (e) { - - if (self.headroom) { - self.headroom.remove(viewTabs); - } - tabControllers.forEach(function (t) { - if (t.destroy) { - t.destroy(); - } - }); - }); - }; -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","apphost","imageLoader","scrollStyles","emby-itemscontainer","emby-tabs","emby-button"],function(libraryBrowser,cardBuilder,appHost,imageLoader){"use strict";function enableScrollX(){return browserInfo.mobile}function renderRecordings(elem,recordings,cardOptions){recordings.length?elem.classList.remove("hide"):elem.classList.add("hide");var recordingItems=elem.querySelector(".recordingItems");enableScrollX()?(recordingItems.classList.add("hiddenScrollX"),recordingItems.classList.remove("vertical-wrap")):(recordingItems.classList.remove("hiddenScrollX"),recordingItems.classList.add("vertical-wrap")),recordingItems.innerHTML=cardBuilder.getCardsHtml(Object.assign({items:recordings,shape:enableScrollX()?"autooverflow":"auto",showTitle:!0,showParentTitle:!0,coverImage:!0,lazy:!0,cardLayout:!0,vibrant:!0,allowBottomPadding:!enableScrollX(),preferThumb:"auto"},cardOptions||{})),imageLoader.lazyChildren(recordingItems)}function getBackdropShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function renderActiveRecordings(context,promise){promise.then(function(result){result.Items.length&&"InProgress"!=result.Items[0].Status&&(result.Items=[]),renderRecordings(context.querySelector("#activeRecordings"),result.Items,{shape:getBackdropShape(),showParentTitle:!1,showTitle:!0,showAirTime:!0,showAirEndTime:!0,showChannelName:!0,cardLayout:!0,vibrant:!0,preferThumb:!0,coverImage:!0,overlayText:!1})})}function getPortraitShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getLimit(){return enableScrollX()?12:8}function loadRecommendedPrograms(page){Dashboard.showLoadingMsg();var limit=getLimit();enableScrollX()&&(limit*=2),ApiClient.getLiveTvRecommendedPrograms({userId:Dashboard.getCurrentUserId(),IsAiring:!0,limit:limit,ImageTypeLimit:1,EnableImageTypes:"Primary,Thumb,Backdrop",EnableTotalRecordCount:!1,Fields:"ChannelInfo"}).then(function(result){renderItems(page,result.Items,"activeProgramItems","play",{showAirDateTime:!1,showAirEndTime:!0}),Dashboard.hideLoadingMsg()})}function reload(page,enableFullRender){renderActiveRecordings(page,ApiClient.getLiveTvRecordings({UserId:Dashboard.getCurrentUserId(),IsInProgress:!0,Fields:"CanDelete,PrimaryImageAspectRatio,BasicSyncInfo",EnableTotalRecordCount:!1,EnableImageTypes:"Primary,Thumb,Backdrop"})),enableFullRender&&(loadRecommendedPrograms(page),ApiClient.getLiveTvRecommendedPrograms({userId:Dashboard.getCurrentUserId(),IsAiring:!1,HasAired:!1,limit:getLimit(),IsMovie:!1,IsSports:!1,IsKids:!1,IsSeries:!0,EnableTotalRecordCount:!1,Fields:"ChannelInfo",EnableImageTypes:"Primary,Thumb"}).then(function(result){renderItems(page,result.Items,"upcomingProgramItems")}),ApiClient.getLiveTvRecommendedPrograms({userId:Dashboard.getCurrentUserId(),IsAiring:!1,HasAired:!1,limit:getLimit(),IsMovie:!0,EnableTotalRecordCount:!1,Fields:"ChannelInfo",EnableImageTypes:"Primary,Thumb"}).then(function(result){renderItems(page,result.Items,"upcomingTvMovieItems",null,{shape:getPortraitShape(),preferThumb:null})}),ApiClient.getLiveTvRecommendedPrograms({userId:Dashboard.getCurrentUserId(),IsAiring:!1,HasAired:!1,limit:getLimit(),IsSports:!0,EnableTotalRecordCount:!1,Fields:"ChannelInfo",EnableImageTypes:"Primary,Thumb"}).then(function(result){renderItems(page,result.Items,"upcomingSportsItems")}),ApiClient.getLiveTvRecommendedPrograms({userId:Dashboard.getCurrentUserId(),IsAiring:!1,HasAired:!1,limit:getLimit(),IsKids:!0,EnableTotalRecordCount:!1,Fields:"ChannelInfo",EnableImageTypes:"Primary,Thumb"}).then(function(result){renderItems(page,result.Items,"upcomingKidsItems")}))}function renderItems(page,items,sectionClass,overlayButton,cardOptions){var supportsImageAnalysis=appHost.supports("imageanalysis");cardOptions=cardOptions||{};var html=cardBuilder.getCardsHtml(Object.assign({items:items,preferThumb:!0,inheritThumb:!1,shape:enableScrollX()?"overflowBackdrop":"backdrop",showParentTitleOrTitle:!0,showTitle:!1,centerText:!supportsImageAnalysis,coverImage:!0,overlayText:!1,lazy:!0,overlayMoreButton:"play"!=overlayButton&&!supportsImageAnalysis,overlayPlayButton:"play"==overlayButton,allowBottomPadding:!enableScrollX(),showAirTime:!0,showAirDateTime:!0,showChannelName:!0,vibrant:!0,cardLayout:supportsImageAnalysis},cardOptions)),elem=page.querySelector("."+sectionClass);elem.innerHTML=html,imageLoader.lazyChildren(elem)}return function(view,params){function enableFullRender(){return(new Date).getTime()-lastFullRender>3e5}function getTabController(page,index,callback){var depends=[];switch(index){case 0:break;case 1:depends.push("scripts/livetvguide");break;case 2:depends.push("scripts/livetvchannels");break;case 3:depends.push("scripts/livetvrecordings");break;case 4:depends.push("scripts/livetvschedule");break;case 5:depends.push("scripts/livetvseriestimers")}require(depends,function(controllerFactory){var tabContent;0==index&&(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),self.tabContent=tabContent);var controller=tabControllers[index];controller||(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),controller=index?new controllerFactory(view,params,tabContent):self,tabControllers[index]=controller,controller.initTab&&controller.initTab()),callback(controller)})}function preLoadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&controller.preRender&&controller.preRender()})}function loadTab(page,index){getTabController(page,index,function(controller){1===index?document.body.classList.add("autoScrollY"):document.body.classList.remove("autoScrollY"),renderedTabs.indexOf(index)==-1?(1===index&&renderedTabs.push(index),controller.renderTab()):controller.onShow&&controller.onShow(),currentTabController=controller})}var self=this,lastFullRender=0;self.initTab=function(){for(var tabContent=view.querySelector(".pageTabContent[data-index='0']"),containers=tabContent.querySelectorAll(".itemsContainer"),i=0,length=containers.length;i'; - - var imgUrl; - - if (user.PrimaryImageTag) { - - imgUrl = apiClient.getUserImageUrl(user.Id, { - width: 300, - tag: user.PrimaryImageTag, - type: "Primary" - }); - - html += '
'; - } - else { - - var background = getMetroColor(user.Id); - - imgUrl = 'css/images/logindefault.png'; - - html += '
'; - } - - html += ''; - html += ''; - - html += '
'; - html += '
' + user.Name + '
'; - - html += '
'; - html += ''; - - html += ''; - } - - context.querySelector('#divUsers').innerHTML = html; - } - - return function (view, params) { - - var self = this; - - function getApiClient() { - - var serverId = params.serverid; - - if (serverId) { - return connectionManager.getOrCreateApiClient(serverId); - - } else { - return ApiClient; - } - } - - function showVisualForm() { - - view.querySelector('.visualLoginForm').classList.remove('hide'); - view.querySelector('.manualLoginForm').classList.add('hide'); - } - - view.querySelector('#divUsers').addEventListener('click', function (e) { - var cardContent = dom.parentWithClass(e.target, 'cardContent'); - - if (cardContent) { - - var context = view; - var id = cardContent.getAttribute('data-userid'); - var name = cardContent.getAttribute('data-username'); - var haspw = cardContent.getAttribute('data-haspw'); - - if (id == 'manual') { - context.querySelector('#txtManualName').value = ''; - showManualForm(context, true); - } - else if (haspw == 'false') { - authenticateUserByName(context, getApiClient(), name, ''); - } else { - - context.querySelector('#txtManualName').value = name; - context.querySelector('#txtManualPassword').value = ''; - showManualForm(context, true, true); - } - } - }); - - view.querySelector('.manualLoginForm').addEventListener('submit', function (e) { - - appSettings.enableAutoLogin(view.querySelector('.chkRememberLogin').checked); - - var apiClient = getApiClient(); - authenticateUserByName(view, apiClient, view.querySelector('#txtManualName').value, view.querySelector('#txtManualPassword').value); - - e.preventDefault(); - // Disable default form submission - return false; - }); - - view.querySelector('.btnForgotPassword').addEventListener('click', function () { - Dashboard.navigate('forgotpassword.html'); - }); - - view.querySelector('.btnCancel').addEventListener('click', showVisualForm); - - view.querySelector('.btnManual').addEventListener('click', function () { - view.querySelector('#txtManualName').value = ''; - showManualForm(view, true); - }); - - view.addEventListener('viewshow', function (e) { - Dashboard.showLoadingMsg(); - - var apiClient = getApiClient(); - apiClient.getPublicUsers().then(function (users) { - - if (!users.length) { - - view.querySelector('#txtManualName').value = ''; - showManualForm(view, false, false); - - } else { - - showVisualForm(); - loadUserList(view, apiClient, users); - } - - Dashboard.hideLoadingMsg(); - }); - - apiClient.getJSON(apiClient.getUrl('Branding/Configuration')).then(function (options) { - - view.querySelector('.disclaimer').innerHTML = options.LoginDisclaimer || ''; - }); - - if (Dashboard.isConnectMode()) { - view.querySelector('.connectButtons').classList.remove('hide'); - } else { - view.querySelector('.connectButtons').classList.add('hide'); - } - }); - }; -}); \ No newline at end of file +define(["appSettings","dom","connectionManager","cardStyle","emby-checkbox"],function(appSettings,dom,connectionManager){"use strict";function authenticateUserByName(page,apiClient,username,password){Dashboard.showLoadingMsg(),apiClient.authenticateUserByName(username,password).then(function(result){var newUrl,user=result.User,serverId=getParameterByName("serverid");newUrl=user.Policy.IsAdministrator&&!serverId?"dashboard.html":"home.html",Dashboard.hideLoadingMsg(),Dashboard.onServerChanged(user.Id,result.AccessToken,apiClient),Dashboard.navigate(newUrl)},function(response){page.querySelector("#txtManualName").value="",page.querySelector("#txtManualPassword").value="",Dashboard.hideLoadingMsg(),401==response.status?require(["toast"],function(toast){toast(Globalize.translate("MessageInvalidUser"))}):showServerConnectionFailure()})}function showServerConnectionFailure(){Dashboard.alert({message:Globalize.translate("MessageUnableToConnectToServer"),title:Globalize.translate("HeaderConnectionFailure")})}function showManualForm(context,showCancel,focusPassword){context.querySelector(".chkRememberLogin").checked=appSettings.enableAutoLogin(),context.querySelector(".manualLoginForm").classList.remove("hide"),context.querySelector(".visualLoginForm").classList.add("hide"),focusPassword?context.querySelector("#txtManualPassword").focus():context.querySelector("#txtManualName").focus(),showCancel?context.querySelector(".btnCancel").classList.remove("hide"):context.querySelector(".btnCancel").classList.add("hide")}function getRandomMetroColor(){var index=Math.floor(Math.random()*(metroColors.length-1));return metroColors[index]}function getMetroColor(str){if(str){for(var character=String(str.substr(0,1).charCodeAt()),sum=0,i=0;i",html+=""}context.querySelector("#divUsers").innerHTML=html}var metroColors=["#6FBD45","#4BB3DD","#4164A5","#E12026","#800080","#E1B222","#008040","#0094FF","#FF00C7","#FF870F","#7F0037"];return function(view,params){function getApiClient(){var serverId=params.serverid;return serverId?connectionManager.getOrCreateApiClient(serverId):ApiClient}function showVisualForm(){view.querySelector(".visualLoginForm").classList.remove("hide"),view.querySelector(".manualLoginForm").classList.add("hide")}view.querySelector("#divUsers").addEventListener("click",function(e){var cardContent=dom.parentWithClass(e.target,"cardContent");if(cardContent){var context=view,id=cardContent.getAttribute("data-userid"),name=cardContent.getAttribute("data-username"),haspw=cardContent.getAttribute("data-haspw");"manual"==id?(context.querySelector("#txtManualName").value="",showManualForm(context,!0)):"false"==haspw?authenticateUserByName(context,getApiClient(),name,""):(context.querySelector("#txtManualName").value=name,context.querySelector("#txtManualPassword").value="",showManualForm(context,!0,!0))}}),view.querySelector(".manualLoginForm").addEventListener("submit",function(e){appSettings.enableAutoLogin(view.querySelector(".chkRememberLogin").checked);var apiClient=getApiClient();return authenticateUserByName(view,apiClient,view.querySelector("#txtManualName").value,view.querySelector("#txtManualPassword").value),e.preventDefault(),!1}),view.querySelector(".btnForgotPassword").addEventListener("click",function(){Dashboard.navigate("forgotpassword.html")}),view.querySelector(".btnCancel").addEventListener("click",showVisualForm),view.querySelector(".btnManual").addEventListener("click",function(){view.querySelector("#txtManualName").value="",showManualForm(view,!0)}),view.addEventListener("viewshow",function(e){Dashboard.showLoadingMsg();var apiClient=getApiClient();apiClient.getPublicUsers().then(function(users){users.length?(showVisualForm(),loadUserList(view,apiClient,users)):(view.querySelector("#txtManualName").value="",showManualForm(view,!1,!1)),Dashboard.hideLoadingMsg()}),apiClient.getJSON(apiClient.getUrl("Branding/Configuration")).then(function(options){view.querySelector(".disclaimer").innerHTML=options.LoginDisclaimer||""}),Dashboard.isConnectMode()?view.querySelector(".connectButtons").classList.remove("hide"):view.querySelector(".connectButtons").classList.add("hide")})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/medialibrarypage.js b/dashboard-ui/scripts/medialibrarypage.js index ba025fe83c..e5e7e67248 100644 --- a/dashboard-ui/scripts/medialibrarypage.js +++ b/dashboard-ui/scripts/medialibrarypage.js @@ -1,496 +1 @@ -define(['jQuery', 'apphost', 'scripts/taskbutton', 'cardStyle'], function ($, appHost, taskButton) { - 'use strict'; - - function changeCollectionType(page, virtualFolder) { - - require(['alert'], function (alert) { - alert({ - title: Globalize.translate('HeaderChangeFolderType'), - text: Globalize.translate('HeaderChangeFolderTypeHelp') - }); - }); - } - - function addVirtualFolder(page) { - - require(['medialibrarycreator'], function (medialibrarycreator) { - - new medialibrarycreator().show({ - - collectionTypeOptions: getCollectionTypeOptions().filter(function (f) { - return !f.hidden; - }), - refresh: shouldRefreshLibraryAfterChanges(page) - - }).then(function (hasChanges) { - - if (hasChanges) { - reloadLibrary(page); - } - }); - }); - } - - function editVirtualFolder(page, virtualFolder) { - - require(['medialibraryeditor'], function (medialibraryeditor) { - - new medialibraryeditor().show({ - - refresh: shouldRefreshLibraryAfterChanges(page), - library: virtualFolder - - }).then(function (hasChanges) { - - if (hasChanges) { - reloadLibrary(page); - } - }); - }); - } - - function deleteVirtualFolder(page, virtualFolder) { - - var msg = Globalize.translate('MessageAreYouSureYouWishToRemoveMediaFolder'); - - if (virtualFolder.Locations.length) { - msg += "

" + Globalize.translate("MessageTheFollowingLocationWillBeRemovedFromLibrary") + "

"; - msg += virtualFolder.Locations.join("
"); - } - - require(['confirm'], function (confirm) { - - confirm(msg, Globalize.translate('HeaderRemoveMediaFolder')).then(function () { - - var refreshAfterChange = shouldRefreshLibraryAfterChanges(page); - - ApiClient.removeVirtualFolder(virtualFolder.Name, refreshAfterChange).then(function () { - reloadLibrary(page); - }); - }); - }); - } - - function renameVirtualFolder(page, virtualFolder) { - - require(['prompt'], function (prompt) { - - prompt({ - label: Globalize.translate('LabelNewName'), - confirmText: Globalize.translate('ButtonRename') - - }).then(function (newName) { - if (newName && newName != virtualFolder.Name) { - - var refreshAfterChange = shouldRefreshLibraryAfterChanges(page); - - ApiClient.renameVirtualFolder(virtualFolder.Name, newName, refreshAfterChange).then(function () { - reloadLibrary(page); - }); - } - }); - - }); - } - - function showCardMenu(page, elem, virtualFolders) { - - var card = $(elem).parents('.card')[0]; - var index = parseInt(card.getAttribute('data-index')); - var virtualFolder = virtualFolders[index]; - - var menuItems = []; - - menuItems.push({ - name: Globalize.translate('ButtonChangeContentType'), - id: 'changetype', - ironIcon: 'videocam' - }); - - menuItems.push({ - name: Globalize.translate('ButtonEditImages'), - id: 'editimages', - ironIcon: 'photo' - }); - - menuItems.push({ - name: Globalize.translate('ButtonManageFolders'), - id: 'edit', - ironIcon: 'folder_open' - }); - - menuItems.push({ - name: Globalize.translate('ButtonRemove'), - id: 'delete', - ironIcon: 'remove' - }); - - menuItems.push({ - name: Globalize.translate('ButtonRename'), - id: 'rename', - ironIcon: 'mode_edit' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: elem, - callback: function (resultId) { - - switch (resultId) { - - case 'changetype': - changeCollectionType(page, virtualFolder); - break; - case 'edit': - editVirtualFolder(page, virtualFolder); - break; - case 'editimages': - editImages(page, virtualFolder); - break; - case 'rename': - renameVirtualFolder(page, virtualFolder); - break; - case 'delete': - deleteVirtualFolder(page, virtualFolder); - break; - default: - break; - } - } - }); - - }); - } - - function reloadLibrary(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getVirtualFolders().then(function (result) { - reloadVirtualFolders(page, result); - }); - } - - function shouldRefreshLibraryAfterChanges(page) { - - return $(page).is('#mediaLibraryPage'); - } - - function reloadVirtualFolders(page, virtualFolders) { - - var html = ''; - - virtualFolders.push({ - Name: Globalize.translate('ButtonAddMediaLibrary'), - icon: 'add_circle', - Locations: [], - showType: false, - showLocations: false, - showMenu: false, - showNameWithIcon: true - }); - - for (var i = 0, length = virtualFolders.length; i < length; i++) { - - var virtualFolder = virtualFolders[i]; - - html += getVirtualFolderHtml(page, virtualFolder, i); - } - - var divVirtualFolders = page.querySelector('#divVirtualFolders'); - divVirtualFolders.innerHTML = html; - divVirtualFolders.classList.add('itemsContainer'); - divVirtualFolders.classList.add('vertical-wrap'); - - $('.btnCardMenu', divVirtualFolders).on('click', function () { - showCardMenu(page, this, virtualFolders); - }); - - $('.addLibrary', divVirtualFolders).on('click', function () { - addVirtualFolder(page); - }); - - $('.editLibrary', divVirtualFolders).on('click', function () { - var card = $(this).parents('.card')[0]; - var index = parseInt(card.getAttribute('data-index')); - var virtualFolder = virtualFolders[index]; - - if (!virtualFolder.ItemId) { - return; - } - - editVirtualFolder(page, virtualFolder); - }); - - Dashboard.hideLoadingMsg(); - } - - function editImages(page, virtualFolder) { - - require(['imageEditor'], function (imageEditor) { - - imageEditor.show({ - - itemId: virtualFolder.ItemId, - serverId: ApiClient.serverId() - - }).then(function () { - reloadLibrary(page); - }); - }); - } - - function getCollectionTypeOptions() { - - return [ - - { name: "", value: "" }, - { name: Globalize.translate('FolderTypeMovies'), value: "movies" }, - { name: Globalize.translate('FolderTypeMusic'), value: "music" }, - { name: Globalize.translate('FolderTypeTvShows'), value: "tvshows" }, - { name: Globalize.translate('FolderTypeBooks'), value: "books", message: Globalize.translate('BookLibraryHelp') }, - { name: Globalize.translate('FolderTypeGames'), value: "games", message: Globalize.translate('MessageGamePluginRequired') }, - { name: Globalize.translate('OptionHomeVideos'), value: "homevideos" }, - { name: Globalize.translate('FolderTypeMusicVideos'), value: "musicvideos" }, - { name: Globalize.translate('FolderTypePhotos'), value: "photos" }, - { name: Globalize.translate('FolderTypeUnset'), value: "mixed", message: Globalize.translate('MessageUnsetContentHelp') } - ]; - - } - - function getIcon(type) { - - switch (type) { - case "movies": - return "local_movies"; - case "music": - return "library_music"; - case "photos": - return "photo"; - case "livetv": - return "live_tv"; - case "tvshows": - return "live_tv"; - case "games": - return "folder"; - case "trailers": - return "local_movies"; - case "homevideos": - return "video_library"; - case "musicvideos": - return "video_library"; - case "books": - return "folder"; - case "channels": - return "folder"; - case "playlists": - return "folder"; - default: - return "folder"; - } - } - - function getVirtualFolderHtml(page, virtualFolder, index) { - - var html = ''; - - var style = ""; - - if (page.classList.contains('wizardPage')) { - style += "min-width:33.3%;"; - } - - html += '
'; - - html += '
'; - html += '
'; - - html += '
'; - - html += '
'; - var imgUrl = ''; - - if (virtualFolder.PrimaryImageItemId) { - imgUrl = ApiClient.getScaledImageUrl(virtualFolder.PrimaryImageItemId, { - type: 'Primary' - }); - } - - if (imgUrl) { - html += '
'; - } else if (!virtualFolder.showNameWithIcon) { - html += '
'; - html += '' + (virtualFolder.icon || getIcon(virtualFolder.CollectionType)) + ''; - - html += '
'; - } - - if (!imgUrl && virtualFolder.showNameWithIcon) { - html += '

'; - - html += '' + (virtualFolder.icon || getIcon(virtualFolder.CollectionType)) + ''; - - if (virtualFolder.showNameWithIcon) { - html += '
'; - html += virtualFolder.Name; - html += "
"; - } - - html += '

'; - } - - // cardContent - html += "
"; - - // cardScalable - html += "
"; - - html += '
'; - - if (virtualFolder.showMenu !== false) { - var moreIcon = appHost.moreIcon == 'dots-horiz' ? '' : ''; - - html += '
'; - html += ''; - html += "
"; - } - - html += "
"; - if (virtualFolder.showNameWithIcon) { - html += ' '; - } else { - html += virtualFolder.Name; - } - html += "
"; - - var typeName = getCollectionTypeOptions().filter(function (t) { - - return t.value == virtualFolder.CollectionType; - - })[0]; - - typeName = typeName ? typeName.name : Globalize.translate('FolderTypeUnset'); - - html += "
"; - if (virtualFolder.showType === false) { - html += ' '; - } else { - html += typeName; - } - html += "
"; - - if (virtualFolder.showLocations === false) { - html += "
"; - html += ' '; - html += "
"; - } else if (!virtualFolder.Locations.length) { - html += "
"; - html += Globalize.translate('NumLocationsValue', virtualFolder.Locations.length); - html += "
"; - } - else if (virtualFolder.Locations.length == 1) { - html += "
"; - html += virtualFolder.Locations[0]; - html += "
"; - } - else { - html += "
"; - html += Globalize.translate('NumLocationsValue', virtualFolder.Locations.length); - html += "
"; - } - - // cardFooter - html += "
"; - - // cardBox - html += "
"; - - // card - html += "
"; - - return html; - } - - window.WizardLibraryPage = { - - next: function () { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - apiClient.ajax({ - type: "POST", - url: apiClient.getUrl('System/Configuration/MetadataPlugins/Autoset') - - }).then(function () { - - Dashboard.hideLoadingMsg(); - Dashboard.navigate('wizardsettings.html'); - }); - } - }; - - function getTabs() { - return [ - { - href: 'library.html', - name: Globalize.translate('HeaderLibraries') - }, - { - href: 'librarydisplay.html', - name: Globalize.translate('TabDisplay') - }, - { - href: 'metadataimages.html', - name: Globalize.translate('TabMetadata') - }, - { - href: 'metadatanfo.html', - name: Globalize.translate('TabNfoSettings') - }, - { - href: 'librarysettings.html', - name: Globalize.translate('TabAdvanced') - }]; - } - - pageClassOn('pageshow', "mediaLibraryPage", function () { - - var page = this; - reloadLibrary(page); - - }); - - pageIdOn('pageshow', "mediaLibraryPage", function () { - - LibraryMenu.setTabs('librarysetup', 0, getTabs); - var page = this; - - // on here - taskButton({ - mode: 'on', - progressElem: page.querySelector('.refreshProgress'), - taskKey: 'RefreshLibrary', - button: page.querySelector('.btnRefresh') - }); - - }); - - pageIdOn('pagebeforehide', "mediaLibraryPage", function () { - - var page = this; - - // off here - taskButton({ - mode: 'off', - progressElem: page.querySelector('.refreshProgress'), - taskKey: 'RefreshLibrary', - button: page.querySelector('.btnRefresh') - }); - - }); - -}); \ No newline at end of file +define(["jQuery","apphost","scripts/taskbutton","cardStyle"],function($,appHost,taskButton){"use strict";function changeCollectionType(page,virtualFolder){require(["alert"],function(alert){alert({title:Globalize.translate("HeaderChangeFolderType"),text:Globalize.translate("HeaderChangeFolderTypeHelp")})})}function addVirtualFolder(page){require(["medialibrarycreator"],function(medialibrarycreator){(new medialibrarycreator).show({collectionTypeOptions:getCollectionTypeOptions().filter(function(f){return!f.hidden}),refresh:shouldRefreshLibraryAfterChanges(page)}).then(function(hasChanges){hasChanges&&reloadLibrary(page)})})}function editVirtualFolder(page,virtualFolder){require(["medialibraryeditor"],function(medialibraryeditor){(new medialibraryeditor).show({refresh:shouldRefreshLibraryAfterChanges(page),library:virtualFolder}).then(function(hasChanges){hasChanges&&reloadLibrary(page)})})}function deleteVirtualFolder(page,virtualFolder){var msg=Globalize.translate("MessageAreYouSureYouWishToRemoveMediaFolder");virtualFolder.Locations.length&&(msg+="

"+Globalize.translate("MessageTheFollowingLocationWillBeRemovedFromLibrary")+"

",msg+=virtualFolder.Locations.join("
")),require(["confirm"],function(confirm){confirm(msg,Globalize.translate("HeaderRemoveMediaFolder")).then(function(){var refreshAfterChange=shouldRefreshLibraryAfterChanges(page);ApiClient.removeVirtualFolder(virtualFolder.Name,refreshAfterChange).then(function(){reloadLibrary(page)})})})}function renameVirtualFolder(page,virtualFolder){require(["prompt"],function(prompt){prompt({label:Globalize.translate("LabelNewName"),confirmText:Globalize.translate("ButtonRename")}).then(function(newName){if(newName&&newName!=virtualFolder.Name){var refreshAfterChange=shouldRefreshLibraryAfterChanges(page);ApiClient.renameVirtualFolder(virtualFolder.Name,newName,refreshAfterChange).then(function(){reloadLibrary(page)})}})})}function showCardMenu(page,elem,virtualFolders){var card=$(elem).parents(".card")[0],index=parseInt(card.getAttribute("data-index")),virtualFolder=virtualFolders[index],menuItems=[];menuItems.push({name:Globalize.translate("ButtonChangeContentType"),id:"changetype",ironIcon:"videocam"}),menuItems.push({name:Globalize.translate("ButtonEditImages"),id:"editimages",ironIcon:"photo"}),menuItems.push({name:Globalize.translate("ButtonManageFolders"),id:"edit",ironIcon:"folder_open"}),menuItems.push({name:Globalize.translate("ButtonRemove"),id:"delete",ironIcon:"remove"}),menuItems.push({name:Globalize.translate("ButtonRename"),id:"rename",ironIcon:"mode_edit"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:elem,callback:function(resultId){switch(resultId){case"changetype":changeCollectionType(page,virtualFolder);break;case"edit":editVirtualFolder(page,virtualFolder);break;case"editimages":editImages(page,virtualFolder);break;case"rename":renameVirtualFolder(page,virtualFolder);break;case"delete":deleteVirtualFolder(page,virtualFolder)}}})})}function reloadLibrary(page){Dashboard.showLoadingMsg(),ApiClient.getVirtualFolders().then(function(result){reloadVirtualFolders(page,result)})}function shouldRefreshLibraryAfterChanges(page){return $(page).is("#mediaLibraryPage")}function reloadVirtualFolders(page,virtualFolders){var html="";virtualFolders.push({Name:Globalize.translate("ButtonAddMediaLibrary"),icon:"add_circle",Locations:[],showType:!1,showLocations:!1,showMenu:!1,showNameWithIcon:!0});for(var i=0,length=virtualFolders.length;i',html+='
',html+='
',html+='
',html+='
';var imgUrl="";if(virtualFolder.PrimaryImageItemId&&(imgUrl=ApiClient.getScaledImageUrl(virtualFolder.PrimaryImageItemId,{type:"Primary"})),imgUrl?html+='
":virtualFolder.showNameWithIcon||(html+='
',html+=''+(virtualFolder.icon||getIcon(virtualFolder.CollectionType))+"",html+="
"),!imgUrl&&virtualFolder.showNameWithIcon&&(html+='

',html+=''+(virtualFolder.icon||getIcon(virtualFolder.CollectionType))+"",virtualFolder.showNameWithIcon&&(html+='
',html+=virtualFolder.Name,html+="
"),html+="

"),html+="
",html+="
",html+='
',virtualFolder.showMenu!==!1){var moreIcon="dots-horiz"==appHost.moreIcon?"":"";html+='
',html+='",html+="
"}html+="
",html+=virtualFolder.showNameWithIcon?" ":virtualFolder.Name,html+="
";var typeName=getCollectionTypeOptions().filter(function(t){return t.value==virtualFolder.CollectionType})[0];return typeName=typeName?typeName.name:Globalize.translate("FolderTypeUnset"),html+="
",html+=virtualFolder.showType===!1?" ":typeName,html+="
",virtualFolder.showLocations===!1?(html+="
",html+=" ",html+="
"):virtualFolder.Locations.length?1==virtualFolder.Locations.length?(html+="
",html+=virtualFolder.Locations[0],html+="
"):(html+="
",html+=Globalize.translate("NumLocationsValue",virtualFolder.Locations.length),html+="
"):(html+="
",html+=Globalize.translate("NumLocationsValue",virtualFolder.Locations.length),html+="
"),html+="
",html+="
",html+=""}function getTabs(){return[{href:"library.html",name:Globalize.translate("HeaderLibraries")},{href:"librarydisplay.html",name:Globalize.translate("TabDisplay")},{href:"metadataimages.html",name:Globalize.translate("TabMetadata")},{href:"metadatanfo.html",name:Globalize.translate("TabNfoSettings")},{href:"librarysettings.html",name:Globalize.translate("TabAdvanced")}]}window.WizardLibraryPage={next:function(){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.ajax({type:"POST",url:apiClient.getUrl("System/Configuration/MetadataPlugins/Autoset")}).then(function(){Dashboard.hideLoadingMsg(),Dashboard.navigate("wizardsettings.html")})}},pageClassOn("pageshow","mediaLibraryPage",function(){var page=this;reloadLibrary(page)}),pageIdOn("pageshow","mediaLibraryPage",function(){LibraryMenu.setTabs("librarysetup",0,getTabs);var page=this;taskButton({mode:"on",progressElem:page.querySelector(".refreshProgress"),taskKey:"RefreshLibrary",button:page.querySelector(".btnRefresh")})}),pageIdOn("pagebeforehide","mediaLibraryPage",function(){var page=this;taskButton({mode:"off",progressElem:page.querySelector(".refreshProgress"),taskKey:"RefreshLibrary",button:page.querySelector(".btnRefresh")})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/metadataimagespage.js b/dashboard-ui/scripts/metadataimagespage.js index 5da557524e..7931fdd778 100644 --- a/dashboard-ui/scripts/metadataimagespage.js +++ b/dashboard-ui/scripts/metadataimagespage.js @@ -1,624 +1 @@ -define(['jQuery', 'dom', 'listViewStyle'], function ($, dom) { - 'use strict'; - - var currentType; - - function populateLanguages(select) { - - return ApiClient.getCultures().then(function (languages) { - - var html = ""; - - html += ""; - - for (var i = 0, length = languages.length; i < length; i++) { - - var culture = languages[i]; - - html += ""; - } - - select.innerHTML = html; - }); - } - - function populateCountries(select) { - - return ApiClient.getCountries().then(function (allCountries) { - - var html = ""; - - html += ""; - - for (var i = 0, length = allCountries.length; i < length; i++) { - - var culture = allCountries[i]; - - html += ""; - } - - select.innerHTML = html; - }); - } - - function loadTabs(page, tabs) { - - var html = ''; - - for (var i = 0, length = tabs.length; i < length; i++) { - - var tab = tabs[i]; - - var isChecked = i == 0 ? ' selected="selected"' : ''; - - html += ''; - } - - $('#selectItemType', page).html(html).trigger('change'); - - Dashboard.hideLoadingMsg(); - } - - function loadType(page, type) { - - Dashboard.showLoadingMsg(); - - currentType = type; - - var promise1 = ApiClient.getServerConfiguration(); - var promise2 = ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataPlugins")); - - Promise.all([promise1, promise2]).then(function (responses) { - - var config = responses[0]; - var metadataPlugins = responses[1]; - - config = config.MetadataOptions.filter(function (c) { - return c.ItemType == type; - })[0]; - - if (config) { - - renderType(page, type, config, metadataPlugins); - - Dashboard.hideLoadingMsg(); - - } else { - - ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataOptions/Default")).then(function (defaultConfig) { - - - config = defaultConfig; - - renderType(page, type, config, metadataPlugins); - - Dashboard.hideLoadingMsg(); - }); - - } - - }); - - } - - function setVisibilityOfBackdrops(elem, visible) { - - if (visible) { - elem.show(); - - $('input', elem).attr('required', 'required'); - - } else { - elem.hide(); - - $('input', elem).attr('required', '').removeAttr('required'); - } - } - - function renderType(page, type, config, metadataPlugins) { - - var metadataInfo = metadataPlugins.filter(function (f) { - - return type == f.ItemType; - })[0]; - - setVisibilityOfBackdrops($('.backdropFields', page), metadataInfo.SupportedImageTypes.indexOf('Backdrop') != -1); - setVisibilityOfBackdrops($('.screenshotFields', page), metadataInfo.SupportedImageTypes.indexOf('Screenshot') != -1); - - $('.imageType', page).each(function () { - - var imageType = this.getAttribute('data-imagetype'); - var container = dom.parentWithTag(this, 'LABEL'); - - if (metadataInfo.SupportedImageTypes.indexOf(imageType) == -1) { - container.classList.add('hide'); - } else { - container.classList.remove('hide'); - } - - if (getImageConfig(config, imageType).Limit) { - - this.checked = true; - - } else { - this.checked = false; - } - }); - - var backdropConfig = getImageConfig(config, 'Backdrop'); - - $('#txtMaxBackdrops', page).val(backdropConfig.Limit); - $('#txtMinBackdropDownloadWidth', page).val(backdropConfig.MinWidth); - - var screenshotConfig = getImageConfig(config, 'Screenshot'); - - $('#txtMaxScreenshots', page).val(screenshotConfig.Limit); - $('#txtMinScreenshotDownloadWidth', page).val(screenshotConfig.MinWidth); - - renderMetadataLocals(page, type, config, metadataInfo); - renderMetadataFetchers(page, type, config, metadataInfo); - renderMetadataSavers(page, type, config, metadataInfo); - renderImageFetchers(page, type, config, metadataInfo); - } - - function getImageConfig(config, type) { - - return config.ImageOptions.filter(function (i) { - - return i.Type == type; - - })[0] || { - - Type: type, - MinWidth: type == 'Backdrop' ? 1280 : 0, - Limit: type == 'Backdrop' ? 3 : 1 - }; - } - - function renderImageFetchers(page, type, config, metadataInfo) { - - var plugins = metadataInfo.Plugins.filter(function (p) { - return p.Type == 'ImageFetcher'; - }); - - var html = ''; - - if (!plugins.length) { - $('.imageFetchers', page).html(html).hide(); - return; - } - - var i, length, plugin, id; - - html += '

' + Globalize.translate('LabelImageFetchers') + '

'; - html += '
'; - - for (i = 0, length = plugins.length; i < length; i++) { - - plugin = plugins[i]; - - var isChecked = config.DisabledImageFetchers.indexOf(plugin.Name) == -1 ? ' checked="checked"' : ''; - - html += '
'; - - html += ''; - - html += '
'; - - html += '

'; - html += plugin.Name; - html += '

'; - - html += '
'; - - html += ''; - html += ''; - - html += '
'; - } - - html += '
'; - html += '
' + Globalize.translate('LabelImageFetchersHelp') + '
'; - - var elem = $('.imageFetchers', page).html(html).show(); - - $('.btnDown', elem).on('click', function () { - - var elemToMove = $(this).parents('.imageFetcherItem')[0]; - - var insertAfter = $(elemToMove).next('.imageFetcherItem')[0]; - - if (insertAfter) { - elemToMove.parentNode.removeChild(elemToMove); - $(elemToMove).insertAfter(insertAfter); - } - }); - - $('.btnUp', elem).on('click', function () { - - var elemToMove = $(this).parents('.imageFetcherItem')[0]; - - var insertBefore = $(elemToMove).prev('.imageFetcherItem')[0]; - - if (insertBefore) { - elemToMove.parentNode.removeChild(elemToMove); - $(elemToMove).insertBefore(insertBefore); - } - }); - } - - function renderMetadataSavers(page, type, config, metadataInfo) { - - var plugins = metadataInfo.Plugins.filter(function (p) { - return p.Type == 'MetadataSaver'; - }); - - var html = ''; - - if (!plugins.length) { - $('.metadataSavers', page).html(html).hide(); - return; - } - - html += '

' + Globalize.translate('LabelMetadataSavers') + '

'; - html += '
'; - - for (var i = 0, length = plugins.length; i < length; i++) { - - var plugin = plugins[i]; - - var isChecked = config.DisabledMetadataSavers.indexOf(plugin.Name) == -1 ? ' checked="checked"' : ''; - - html += ''; - } - - html += '
'; - html += '
' + Globalize.translate('LabelMetadataSaversHelp') + '
'; - - page.querySelector('.metadataSavers').innerHTML = html; - } - - function renderMetadataFetchers(page, type, config, metadataInfo) { - - var plugins = metadataInfo.Plugins.filter(function (p) { - return p.Type == 'MetadataFetcher'; - }); - - var html = ''; - - if (!plugins.length) { - $('.metadataFetchers', page).html(html).hide(); - return; - } - - var i, length, plugin; - - html += '

' + Globalize.translate('LabelMetadataDownloaders') + '

'; - html += '
'; - - for (i = 0, length = plugins.length; i < length; i++) { - - plugin = plugins[i]; - - var isChecked = config.DisabledMetadataFetchers.indexOf(plugin.Name) == -1 ? ' checked="checked"' : ''; - - html += '
'; - - html += ''; - - html += '
'; - - html += '

'; - html += plugin.Name; - html += '

'; - - html += '
'; - - html += ''; - html += ''; - - html += '
'; - } - - html += '
'; - html += '
' + Globalize.translate('LabelMetadataDownloadersHelp') + '
'; - - var elem = $('.metadataFetchers', page).html(html).show(); - - $('.btnDown', elem).on('click', function () { - - var elemToMove = $(this).parents('.metadataFetcherItem')[0]; - - var insertAfter = $(elemToMove).next('.metadataFetcherItem')[0]; - - if (insertAfter) { - elemToMove.parentNode.removeChild(elemToMove); - $(elemToMove).insertAfter(insertAfter); - } - }); - - $('.btnUp', elem).on('click', function () { - - var elemToMove = $(this).parents('.metadataFetcherItem')[0]; - - var insertBefore = $(elemToMove).prev('.metadataFetcherItem')[0]; - - if (insertBefore) { - elemToMove.parentNode.removeChild(elemToMove); - $(elemToMove).insertBefore(insertBefore); - } - }); - } - - function renderMetadataLocals(page, type, config, metadataInfo) { - - var plugins = metadataInfo.Plugins.filter(function (p) { - return p.Type == 'LocalMetadataProvider'; - }); - - var html = ''; - - if (plugins.length < 2) { - $('.metadataReaders', page).html(html).hide(); - return; - } - - html += '

' + Globalize.translate('LabelMetadataReaders') + '

'; - html += '
'; - - for (var i = 0, length = plugins.length; i < length; i++) { - - var plugin = plugins[i]; - - html += '
'; - - html += 'live_tv'; - - html += '
'; - - html += '

'; - html += plugin.Name; - html += '

'; - - html += '
'; - - if (i > 0) { - html += ''; - } - else if (plugins.length > 1) { - - html += ''; - } - - html += '
'; - } - - html += '
'; - html += '
' + Globalize.translate('LabelMetadataReadersHelp') + '
'; - - $('.metadataReaders', page).html(html).show(); - } - - function loadPage(page) { - - var promises = [ - ApiClient.getServerConfiguration(), - populateLanguages(page.querySelector('#selectLanguage')), - populateCountries(page.querySelector('#selectCountry')) - ]; - - Promise.all(promises).then(function (responses) { - - var config = responses[0]; - page.querySelector('#selectLanguage').value = config.PreferredMetadataLanguage || ''; - page.querySelector('#selectCountry').value = config.MetadataCountryCode || ''; - }); - - loadTabs(page, [ - - { name: 'OptionMovies', type: 'Movie' }, - //{ name: 'Trailers', type: 'Trailer' }, - { name: 'OptionCollections', type: 'BoxSet' }, - { name: 'OptionSeries', type: 'Series' }, - { name: 'OptionSeasons', type: 'Season' }, - { name: 'OptionEpisodes', type: 'Episode' }, - { name: 'OptionGames', type: 'Game' }, - { name: 'OptionGameSystems', type: 'GameSystem' }, - //{ name: 'Game Genres', type: 'GameGenre' }, - { name: 'OptionMusicArtists', type: 'MusicArtist' }, - { name: 'OptionMusicAlbums', type: 'MusicAlbum' }, - { name: 'OptionMusicVideos', type: 'MusicVideo' }, - //{ name: 'Music Genres', type: 'MusicGenre' }, - { name: 'OptionSongs', type: 'Audio' }, - { name: 'OptionHomeVideos', type: 'Video' }, - { name: 'OptionBooks', type: 'Book' }, - { name: 'OptionPeople', type: 'Person' } - //{ name: 'Genres', type: 'Genre' }, - //{ name: 'Studios', type: 'Studio' } - ]); - } - - function saveSettingsIntoConfig(form, config) { - - config.DisabledMetadataSavers = $('.chkMetadataSaver', form).get().filter(function (c) { - - return !c.checked; - - }).map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.LocalMetadataReaderOrder = $('.localReaderOption', form).get().map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.DisabledMetadataFetchers = $('.chkMetadataFetcher', form).get().filter(function (c) { - return !c.checked; - }).map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.MetadataFetcherOrder = $('.chkMetadataFetcher', form).get().map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.DisabledImageFetchers = $('.chkImageFetcher', form).get().filter(function (c) { - return !c.checked; - }).map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.ImageFetcherOrder = $('.chkImageFetcher', form).get().map(function (c) { - - return c.getAttribute('data-pluginname'); - - }); - - config.ImageOptions = $('.imageType:not(.hide)', form).get().map(function (c) { - - - return { - Type: c.getAttribute('data-imagetype'), - Limit: c.checked ? 1 : 0, - MinWidth: 0 - }; - - }); - - config.ImageOptions.push({ - Type: 'Backdrop', - Limit: $('#txtMaxBackdrops', form).val(), - MinWidth: $('#txtMinBackdropDownloadWidth', form).val() - }); - - config.ImageOptions.push({ - Type: 'Screenshot', - Limit: $('#txtMaxScreenshots', form).val(), - MinWidth: $('#txtMinScreenshotDownloadWidth', form).val() - }); - } - - function onSubmit() { - - var form = this; - - Dashboard.showLoadingMsg(); - - ApiClient.getServerConfiguration().then(function (config) { - - var type = currentType; - - var metadataOptions = config.MetadataOptions.filter(function (c) { - return c.ItemType == type; - })[0]; - - if (metadataOptions) { - - config.PreferredMetadataLanguage = form.querySelector('#selectLanguage').value; - config.MetadataCountryCode = form.querySelector('#selectCountry').value; - - saveSettingsIntoConfig(form, metadataOptions); - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult); - - } else { - - ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataOptions/Default")).then(function (defaultOptions) { - - defaultOptions.ItemType = type; - config.MetadataOptions.push(defaultOptions); - saveSettingsIntoConfig(form, defaultOptions); - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult); - - }); - } - }); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'library.html', - name: Globalize.translate('HeaderLibraries') - }, - { - href: 'librarydisplay.html', - name: Globalize.translate('TabDisplay') - }, - { - href: 'metadataimages.html', - name: Globalize.translate('TabMetadata') - }, - { - href: 'metadatanfo.html', - name: Globalize.translate('TabNfoSettings') - }, - { - href: 'librarysettings.html', - name: Globalize.translate('TabAdvanced') - }]; - } - - $(document).on('pageinit', "#metadataImagesConfigurationPage", function () { - - var page = this; - - $('.metadataReaders', page).on('click', '.btnLocalReaderMove', function () { - - var li = $(this).parents('.localReaderOption'); - var list = li.parents('.paperList'); - - if ($(this).hasClass('btnLocalReaderDown')) { - - var next = li.next(); - - li.remove().insertAfter(next); - - } else { - - var prev = li.prev(); - - li.remove().insertBefore(prev); - } - - $('.localReaderOption', list).each(function () { - - if ($(this).prev('.localReaderOption').length) { - $('.btnLocalReaderMove', this).addClass('btnLocalReaderUp').removeClass('btnLocalReaderDown').attr('icon', 'keyboard-arrow-up'); - } else { - $('.btnLocalReaderMove', this).addClass('btnLocalReaderDown').removeClass('btnLocalReaderUp').attr('icon', 'keyboard-arrow-down'); - } - - }); - }); - - $('#selectItemType', page).on('change', function () { - - loadType(page, this.value); - }); - - $('.metadataImagesConfigurationForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#metadataImagesConfigurationPage", function () { - - LibraryMenu.setTabs('metadata', 2, getTabs); - Dashboard.showLoadingMsg(); - - var page = this; - - loadPage(page); - }); - -}); \ No newline at end of file +define(["jQuery","dom","listViewStyle"],function($,dom){"use strict";function populateLanguages(select){return ApiClient.getCultures().then(function(languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html})}function populateCountries(select){return ApiClient.getCountries().then(function(allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html})}function loadTabs(page,tabs){for(var html="",i=0,length=tabs.length;i"+Globalize.translate(tab.name)+""}$("#selectItemType",page).html(html).trigger("change"),Dashboard.hideLoadingMsg()}function loadType(page,type){Dashboard.showLoadingMsg(),currentType=type;var promise1=ApiClient.getServerConfiguration(),promise2=ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataPlugins"));Promise.all([promise1,promise2]).then(function(responses){var config=responses[0],metadataPlugins=responses[1];config=config.MetadataOptions.filter(function(c){return c.ItemType==type})[0],config?(renderType(page,type,config,metadataPlugins),Dashboard.hideLoadingMsg()):ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataOptions/Default")).then(function(defaultConfig){config=defaultConfig,renderType(page,type,config,metadataPlugins),Dashboard.hideLoadingMsg()})})}function setVisibilityOfBackdrops(elem,visible){visible?(elem.show(),$("input",elem).attr("required","required")):(elem.hide(),$("input",elem).attr("required","").removeAttr("required"))}function renderType(page,type,config,metadataPlugins){var metadataInfo=metadataPlugins.filter(function(f){return type==f.ItemType})[0];setVisibilityOfBackdrops($(".backdropFields",page),metadataInfo.SupportedImageTypes.indexOf("Backdrop")!=-1),setVisibilityOfBackdrops($(".screenshotFields",page),metadataInfo.SupportedImageTypes.indexOf("Screenshot")!=-1),$(".imageType",page).each(function(){var imageType=this.getAttribute("data-imagetype"),container=dom.parentWithTag(this,"LABEL");metadataInfo.SupportedImageTypes.indexOf(imageType)==-1?container.classList.add("hide"):container.classList.remove("hide"),getImageConfig(config,imageType).Limit?this.checked=!0:this.checked=!1});var backdropConfig=getImageConfig(config,"Backdrop");$("#txtMaxBackdrops",page).val(backdropConfig.Limit),$("#txtMinBackdropDownloadWidth",page).val(backdropConfig.MinWidth);var screenshotConfig=getImageConfig(config,"Screenshot");$("#txtMaxScreenshots",page).val(screenshotConfig.Limit),$("#txtMinScreenshotDownloadWidth",page).val(screenshotConfig.MinWidth),renderMetadataLocals(page,type,config,metadataInfo),renderMetadataFetchers(page,type,config,metadataInfo),renderMetadataSavers(page,type,config,metadataInfo),renderImageFetchers(page,type,config,metadataInfo)}function getImageConfig(config,type){return config.ImageOptions.filter(function(i){return i.Type==type})[0]||{Type:type,MinWidth:"Backdrop"==type?1280:0,Limit:"Backdrop"==type?3:1}}function renderImageFetchers(page,type,config,metadataInfo){var plugins=metadataInfo.Plugins.filter(function(p){return"ImageFetcher"==p.Type}),html="";if(!plugins.length)return void $(".imageFetchers",page).html(html).hide();var i,length,plugin;for(html+='

'+Globalize.translate("LabelImageFetchers")+"

",html+='
',i=0,length=plugins.length;i',html+='",html+='
',html+='

',html+=plugin.Name,html+="

",html+="
",html+='',html+='',html+="
"}html+="",html+='
'+Globalize.translate("LabelImageFetchersHelp")+"
";var elem=$(".imageFetchers",page).html(html).show();$(".btnDown",elem).on("click",function(){var elemToMove=$(this).parents(".imageFetcherItem")[0],insertAfter=$(elemToMove).next(".imageFetcherItem")[0];insertAfter&&(elemToMove.parentNode.removeChild(elemToMove),$(elemToMove).insertAfter(insertAfter))}),$(".btnUp",elem).on("click",function(){var elemToMove=$(this).parents(".imageFetcherItem")[0],insertBefore=$(elemToMove).prev(".imageFetcherItem")[0];insertBefore&&(elemToMove.parentNode.removeChild(elemToMove),$(elemToMove).insertBefore(insertBefore))})}function renderMetadataSavers(page,type,config,metadataInfo){var plugins=metadataInfo.Plugins.filter(function(p){return"MetadataSaver"==p.Type}),html="";if(!plugins.length)return void $(".metadataSavers",page).html(html).hide();html+='

'+Globalize.translate("LabelMetadataSavers")+"

",html+='
';for(var i=0,length=plugins.length;i"+plugin.Name+""}html+="
",html+='
'+Globalize.translate("LabelMetadataSaversHelp")+"
",page.querySelector(".metadataSavers").innerHTML=html}function renderMetadataFetchers(page,type,config,metadataInfo){var plugins=metadataInfo.Plugins.filter(function(p){return"MetadataFetcher"==p.Type}),html="";if(!plugins.length)return void $(".metadataFetchers",page).html(html).hide();var i,length,plugin;for(html+='

'+Globalize.translate("LabelMetadataDownloaders")+"

",html+='
',i=0,length=plugins.length;i',html+='",html+='
',html+='

',html+=plugin.Name,html+="

",html+="
",html+='',html+='',html+="
"}html+="",html+='
'+Globalize.translate("LabelMetadataDownloadersHelp")+"
";var elem=$(".metadataFetchers",page).html(html).show();$(".btnDown",elem).on("click",function(){var elemToMove=$(this).parents(".metadataFetcherItem")[0],insertAfter=$(elemToMove).next(".metadataFetcherItem")[0];insertAfter&&(elemToMove.parentNode.removeChild(elemToMove),$(elemToMove).insertAfter(insertAfter))}),$(".btnUp",elem).on("click",function(){var elemToMove=$(this).parents(".metadataFetcherItem")[0],insertBefore=$(elemToMove).prev(".metadataFetcherItem")[0];insertBefore&&(elemToMove.parentNode.removeChild(elemToMove),$(elemToMove).insertBefore(insertBefore))})}function renderMetadataLocals(page,type,config,metadataInfo){var plugins=metadataInfo.Plugins.filter(function(p){return"LocalMetadataProvider"==p.Type}),html="";if(plugins.length<2)return void $(".metadataReaders",page).html(html).hide();html+='

'+Globalize.translate("LabelMetadataReaders")+"

",html+='
';for(var i=0,length=plugins.length;i',html+='live_tv',html+='
',html+='

',html+=plugin.Name,html+="

",html+="
",i>0?html+='':plugins.length>1&&(html+=''),html+="
"}html+="",html+='
'+Globalize.translate("LabelMetadataReadersHelp")+"
",$(".metadataReaders",page).html(html).show()}function loadPage(page){var promises=[ApiClient.getServerConfiguration(),populateLanguages(page.querySelector("#selectLanguage")),populateCountries(page.querySelector("#selectCountry"))];Promise.all(promises).then(function(responses){var config=responses[0];page.querySelector("#selectLanguage").value=config.PreferredMetadataLanguage||"",page.querySelector("#selectCountry").value=config.MetadataCountryCode||""}),loadTabs(page,[{name:"OptionMovies",type:"Movie"},{name:"OptionCollections",type:"BoxSet"},{name:"OptionSeries",type:"Series"},{name:"OptionSeasons",type:"Season"},{name:"OptionEpisodes",type:"Episode"},{name:"OptionGames",type:"Game"},{name:"OptionGameSystems",type:"GameSystem"},{name:"OptionMusicArtists",type:"MusicArtist"},{name:"OptionMusicAlbums",type:"MusicAlbum"},{name:"OptionMusicVideos",type:"MusicVideo"},{name:"OptionSongs",type:"Audio"},{name:"OptionHomeVideos",type:"Video"},{name:"OptionBooks",type:"Book"},{name:"OptionPeople",type:"Person"}])}function saveSettingsIntoConfig(form,config){config.DisabledMetadataSavers=$(".chkMetadataSaver",form).get().filter(function(c){return!c.checked}).map(function(c){return c.getAttribute("data-pluginname")}),config.LocalMetadataReaderOrder=$(".localReaderOption",form).get().map(function(c){return c.getAttribute("data-pluginname")}),config.DisabledMetadataFetchers=$(".chkMetadataFetcher",form).get().filter(function(c){return!c.checked}).map(function(c){return c.getAttribute("data-pluginname")}),config.MetadataFetcherOrder=$(".chkMetadataFetcher",form).get().map(function(c){return c.getAttribute("data-pluginname")}),config.DisabledImageFetchers=$(".chkImageFetcher",form).get().filter(function(c){return!c.checked}).map(function(c){return c.getAttribute("data-pluginname")}),config.ImageFetcherOrder=$(".chkImageFetcher",form).get().map(function(c){return c.getAttribute("data-pluginname")}),config.ImageOptions=$(".imageType:not(.hide)",form).get().map(function(c){return{Type:c.getAttribute("data-imagetype"),Limit:c.checked?1:0,MinWidth:0}}),config.ImageOptions.push({Type:"Backdrop",Limit:$("#txtMaxBackdrops",form).val(),MinWidth:$("#txtMinBackdropDownloadWidth",form).val()}),config.ImageOptions.push({Type:"Screenshot",Limit:$("#txtMaxScreenshots",form).val(),MinWidth:$("#txtMinScreenshotDownloadWidth",form).val()})}function onSubmit(){var form=this;return Dashboard.showLoadingMsg(),ApiClient.getServerConfiguration().then(function(config){var type=currentType,metadataOptions=config.MetadataOptions.filter(function(c){return c.ItemType==type})[0];metadataOptions?(config.PreferredMetadataLanguage=form.querySelector("#selectLanguage").value,config.MetadataCountryCode=form.querySelector("#selectCountry").value,saveSettingsIntoConfig(form,metadataOptions),ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult)):ApiClient.getJSON(ApiClient.getUrl("System/Configuration/MetadataOptions/Default")).then(function(defaultOptions){defaultOptions.ItemType=type,config.MetadataOptions.push(defaultOptions),saveSettingsIntoConfig(form,defaultOptions),ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult)})}),!1}function getTabs(){return[{href:"library.html",name:Globalize.translate("HeaderLibraries")},{href:"librarydisplay.html",name:Globalize.translate("TabDisplay")},{href:"metadataimages.html",name:Globalize.translate("TabMetadata")},{href:"metadatanfo.html",name:Globalize.translate("TabNfoSettings")},{href:"librarysettings.html",name:Globalize.translate("TabAdvanced")}]}var currentType;$(document).on("pageinit","#metadataImagesConfigurationPage",function(){var page=this;$(".metadataReaders",page).on("click",".btnLocalReaderMove",function(){var li=$(this).parents(".localReaderOption"),list=li.parents(".paperList");if($(this).hasClass("btnLocalReaderDown")){var next=li.next();li.remove().insertAfter(next)}else{var prev=li.prev();li.remove().insertBefore(prev)}$(".localReaderOption",list).each(function(){$(this).prev(".localReaderOption").length?$(".btnLocalReaderMove",this).addClass("btnLocalReaderUp").removeClass("btnLocalReaderDown").attr("icon","keyboard-arrow-up"):$(".btnLocalReaderMove",this).addClass("btnLocalReaderDown").removeClass("btnLocalReaderUp").attr("icon","keyboard-arrow-down")})}),$("#selectItemType",page).on("change",function(){loadType(page,this.value)}),$(".metadataImagesConfigurationForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#metadataImagesConfigurationPage",function(){LibraryMenu.setTabs("metadata",2,getTabs),Dashboard.showLoadingMsg();var page=this;loadPage(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/metadatanfo.js b/dashboard-ui/scripts/metadatanfo.js index ed740b06f7..40eca1ee09 100644 --- a/dashboard-ui/scripts/metadatanfo.js +++ b/dashboard-ui/scripts/metadatanfo.js @@ -1,106 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - var metadataKey = "xbmcmetadata"; - - function loadPage(page, config, users) { - - var html = ''; - - html += users.map(function (user) { - return ''; - }).join(''); - - $('#selectUser', page).html(html).val(config.UserId || ''); - $('#selectReleaseDateFormat', page).val(config.ReleaseDateFormat); - - page.querySelector('#chkSaveImagePaths').checked = config.SaveImagePathsInNfo; - page.querySelector('#chkEnablePathSubstitution').checked = config.EnablePathSubstitution; - page.querySelector('#chkEnableExtraThumbs').checked = config.EnableExtraThumbsDuplication; - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getNamedConfiguration(metadataKey).then(function (config) { - - config.UserId = $('#selectUser', form).val() || null; - config.ReleaseDateFormat = $('#selectReleaseDateFormat', form).val(); - - config.SaveImagePathsInNfo = form.querySelector('#chkSaveImagePaths').checked; - config.EnablePathSubstitution = form.querySelector('#chkEnablePathSubstitution').checked; - config.EnableExtraThumbsDuplication = form.querySelector('#chkEnableExtraThumbs').checked; - - ApiClient.updateNamedConfiguration(metadataKey, config).then(function () { - Dashboard.processServerConfigurationUpdateResult(); - - showConfirmMessage(config); - }); - }); - - // Disable default form submission - return false; - } - - function showConfirmMessage(config) { - - var msg = []; - - msg.push(Globalize.translate('MetadataSettingChangeHelp')); - - require(['alert'], function (alert) { - alert({ - text: msg.join('

') - }); - }); - } - - function getTabs() { - return [ - { - href: 'library.html', - name: Globalize.translate('HeaderLibraries') - }, - { - href: 'librarydisplay.html', - name: Globalize.translate('TabDisplay') - }, - { - href: 'metadataimages.html', - name: Globalize.translate('TabMetadata') - }, - { - href: 'metadatanfo.html', - name: Globalize.translate('TabNfoSettings') - }, - { - href: 'librarysettings.html', - name: Globalize.translate('TabAdvanced') - }]; - } - - $(document).on('pageinit', "#metadataNfoPage", function () { - - $('.metadataNfoForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#metadataNfoPage", function () { - - LibraryMenu.setTabs('metadata', 3, getTabs); - Dashboard.showLoadingMsg(); - - var page = this; - - var promise1 = ApiClient.getUsers(); - var promise2 = ApiClient.getNamedConfiguration(metadataKey); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadPage(page, responses[1], responses[0]); - }); - }); - -}); +define(["jQuery"],function($){"use strict";function loadPage(page,config,users){var html='";html+=users.map(function(user){return'"}).join(""),$("#selectUser",page).html(html).val(config.UserId||""),$("#selectReleaseDateFormat",page).val(config.ReleaseDateFormat),page.querySelector("#chkSaveImagePaths").checked=config.SaveImagePathsInNfo,page.querySelector("#chkEnablePathSubstitution").checked=config.EnablePathSubstitution,page.querySelector("#chkEnableExtraThumbs").checked=config.EnableExtraThumbsDuplication,Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getNamedConfiguration(metadataKey).then(function(config){config.UserId=$("#selectUser",form).val()||null,config.ReleaseDateFormat=$("#selectReleaseDateFormat",form).val(),config.SaveImagePathsInNfo=form.querySelector("#chkSaveImagePaths").checked,config.EnablePathSubstitution=form.querySelector("#chkEnablePathSubstitution").checked,config.EnableExtraThumbsDuplication=form.querySelector("#chkEnableExtraThumbs").checked,ApiClient.updateNamedConfiguration(metadataKey,config).then(function(){Dashboard.processServerConfigurationUpdateResult(),showConfirmMessage(config)})}),!1}function showConfirmMessage(config){var msg=[];msg.push(Globalize.translate("MetadataSettingChangeHelp")),require(["alert"],function(alert){alert({text:msg.join("

")})})}function getTabs(){return[{href:"library.html",name:Globalize.translate("HeaderLibraries")},{href:"librarydisplay.html",name:Globalize.translate("TabDisplay")},{href:"metadataimages.html",name:Globalize.translate("TabMetadata")},{href:"metadatanfo.html",name:Globalize.translate("TabNfoSettings")},{href:"librarysettings.html",name:Globalize.translate("TabAdvanced")}]}var metadataKey="xbmcmetadata";$(document).on("pageinit","#metadataNfoPage",function(){$(".metadataNfoForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#metadataNfoPage",function(){LibraryMenu.setTabs("metadata",3,getTabs),Dashboard.showLoadingMsg();var page=this,promise1=ApiClient.getUsers(),promise2=ApiClient.getNamedConfiguration(metadataKey);Promise.all([promise1,promise2]).then(function(responses){loadPage(page,responses[1],responses[0])})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/metadatasubtitles.js b/dashboard-ui/scripts/metadatasubtitles.js index 473f8954b3..2eb0c25a95 100644 --- a/dashboard-ui/scripts/metadatasubtitles.js +++ b/dashboard-ui/scripts/metadatasubtitles.js @@ -1,103 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function loadPage(page, config, languages) { - - $('#chkSubtitlesMovies', page).checked(config.DownloadMovieSubtitles); - $('#chkSubtitlesEpisodes', page).checked(config.DownloadEpisodeSubtitles); - - $('#chkSkipIfGraphicalSubsPresent', page).checked(config.SkipIfEmbeddedSubtitlesPresent); - $('#chkSkipIfAudioTrackPresent', page).checked(config.SkipIfAudioTrackMatches); - $('#chkRequirePerfectMatch', page).checked(config.RequirePerfectMatch); - - $('#txtOpenSubtitleUsername', page).val(config.OpenSubtitlesUsername); - $('#txtOpenSubtitlePassword', page).val(''); - - populateLanguages(page, config, languages); - - Dashboard.hideLoadingMsg(); - } - - function populateLanguages(page, config, languages) { - - var html = ''; - - for (var i = 0, length = languages.length; i < length; i++) { - - var culture = languages[i]; - - html += ''; - } - - $('.downloadLanguages', page).html(html); - - var langs = config.DownloadLanguages || []; - - $('.chkLang', page).each(function () { - - this.checked = langs.indexOf(this.getAttribute('data-lang')) != -1; - - }); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getNamedConfiguration("subtitles").then(function (config) { - - config.DownloadMovieSubtitles = $('#chkSubtitlesMovies', form).checked(); - config.DownloadEpisodeSubtitles = $('#chkSubtitlesEpisodes', form).checked(); - - config.SkipIfEmbeddedSubtitlesPresent = $('#chkSkipIfGraphicalSubsPresent', form).checked(); - config.SkipIfAudioTrackMatches = $('#chkSkipIfAudioTrackPresent', form).checked(); - config.RequirePerfectMatch = $('#chkRequirePerfectMatch', form).checked(); - - config.OpenSubtitlesUsername = $('#txtOpenSubtitleUsername', form).val(); - - var newPassword = $('#txtOpenSubtitlePassword', form).val(); - - if (newPassword) { - config.OpenSubtitlesPasswordHash = newPassword; - } - - config.DownloadLanguages = $('.chkLang', form).get().filter(function (c) { - - return c.checked; - - }).map(function (c) { - - return c.getAttribute('data-lang'); - - }); - - ApiClient.updateNamedConfiguration("subtitles", config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - // Disable default form submission - return false; - } - - $(document).on('pageinit', "#metadataSubtitlesPage", function () { - - $('.metadataSubtitlesForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#metadataSubtitlesPage", function () { - - Dashboard.showLoadingMsg(); - - var page = this; - - var promise1 = ApiClient.getNamedConfiguration("subtitles"); - var promise2 = ApiClient.getCultures(); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadPage(page, responses[0], responses[1]); - - }); - - }); - -}); +define(["jQuery","fnchecked"],function($){"use strict";function loadPage(page,config,languages){$("#chkSubtitlesMovies",page).checked(config.DownloadMovieSubtitles),$("#chkSubtitlesEpisodes",page).checked(config.DownloadEpisodeSubtitles),$("#chkSkipIfGraphicalSubsPresent",page).checked(config.SkipIfEmbeddedSubtitlesPresent),$("#chkSkipIfAudioTrackPresent",page).checked(config.SkipIfAudioTrackMatches),$("#chkRequirePerfectMatch",page).checked(config.RequirePerfectMatch),$("#txtOpenSubtitleUsername",page).val(config.OpenSubtitlesUsername),$("#txtOpenSubtitlePassword",page).val(""),populateLanguages(page,config,languages),Dashboard.hideLoadingMsg()}function populateLanguages(page,config,languages){for(var html="",i=0,length=languages.length;i'+culture.DisplayName+""}$(".downloadLanguages",page).html(html);var langs=config.DownloadLanguages||[];$(".chkLang",page).each(function(){this.checked=langs.indexOf(this.getAttribute("data-lang"))!=-1})}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getNamedConfiguration("subtitles").then(function(config){config.DownloadMovieSubtitles=$("#chkSubtitlesMovies",form).checked(),config.DownloadEpisodeSubtitles=$("#chkSubtitlesEpisodes",form).checked(),config.SkipIfEmbeddedSubtitlesPresent=$("#chkSkipIfGraphicalSubsPresent",form).checked(),config.SkipIfAudioTrackMatches=$("#chkSkipIfAudioTrackPresent",form).checked(),config.RequirePerfectMatch=$("#chkRequirePerfectMatch",form).checked(),config.OpenSubtitlesUsername=$("#txtOpenSubtitleUsername",form).val();var newPassword=$("#txtOpenSubtitlePassword",form).val();newPassword&&(config.OpenSubtitlesPasswordHash=newPassword),config.DownloadLanguages=$(".chkLang",form).get().filter(function(c){return c.checked}).map(function(c){return c.getAttribute("data-lang")}),ApiClient.updateNamedConfiguration("subtitles",config).then(Dashboard.processServerConfigurationUpdateResult)}),!1}$(document).on("pageinit","#metadataSubtitlesPage",function(){$(".metadataSubtitlesForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#metadataSubtitlesPage",function(){Dashboard.showLoadingMsg();var page=this,promise1=ApiClient.getNamedConfiguration("subtitles"),promise2=ApiClient.getCultures();Promise.all([promise1,promise2]).then(function(responses){loadPage(page,responses[0],responses[1])})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/moviecollections.js b/dashboard-ui/scripts/moviecollections.js index f0c439624b..63a09f1511 100644 --- a/dashboard-ui/scripts/moviecollections.js +++ b/dashboard-ui/scripts/moviecollections.js @@ -1,291 +1 @@ -define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'cardBuilder', 'apphost', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView, cardBuilder, appHost) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var pageSize = libraryBrowser.getDefaultPageSize(); - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "BoxSet", - Recursive: true, - Fields: "PrimaryImageAspectRatio,SortName", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: pageSize - }, - view: libraryBrowser.getSavedView(key) || (appHost.preferVisualCards ? 'PosterCard' : 'Poster') - }; - - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey('moviecollections'); - } - return context.savedQueryKey; - } - - function onViewStyleChange() { - - var viewStyle = self.getCurrentViewStyle(); - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - updateFilterControls(page); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: false, - sortButton: false, - filterButton: false - }); - - var html; - var viewStyle = self.getCurrentViewStyle(); - - if (viewStyle == "Thumb") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'movies', - lazy: true, - overlayPlayButton: true, - showTitle: true - }); - } - else if (viewStyle == "ThumbCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'movies', - lazy: true, - cardLayout: true, - showTitle: true, - showItemCounts: true, - vibrant: true - }); - } - else if (viewStyle == "Banner") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "banner", - preferBanner: true, - context: 'movies', - lazy: true - }); - } - else if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - context: 'movies', - sortBy: query.SortBy - }); - } - else if (viewStyle == "PosterCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "auto", - context: 'movies', - showTitle: true, - centerText: false, - cardLayout: true, - showItemCounts: true, - vibrant: true - }); - } - else { - - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "auto", - context: 'movies', - centerText: true, - lazy: true, - overlayPlayButton: true, - showTitle: true - }); - } - - var i, length; - var elems = tabContent.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(tabContent); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(tabContent); - } - - elems = tabContent.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = tabContent.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - if (!result.Items.length) { - html = '

' + Globalize.translate('MessageNoCollectionsAvailable') + '

'; - } - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - function updateFilterControls(tabContent) { - - } - - function initPage(tabContent) { - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SortName' - }, - { - name: Globalize.translate('OptionImdbRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'PremiereDate,SortName' - }], - callback: function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - - var btnSelectView = tabContent.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), 'List,Poster,PosterCard,Thumb,ThumbCard'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - - var viewStyle = e.detail.viewStyle; - - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - getQuery(tabContent).StartIndex = 0; - onViewStyleChange(); - reloadItems(tabContent); - }); - - // The button is created dynamically - tabContent.querySelector('.btnNewCollection').addEventListener('click', function () { - - require(['collectionEditor'], function (collectionEditor) { - - var serverId = ApiClient.serverInfo().Id; - new collectionEditor().show({ - items: [], - serverId: serverId - }); - - }); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - onViewStyleChange(); - - self.renderTab = function () { - - reloadItems(tabContent); - updateFilterControls(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","listView","cardBuilder","apphost","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,listView,cardBuilder,appHost){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"BoxSet",Recursive:!0,Fields:"PrimaryImageAspectRatio,SortName",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("moviecollections")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0),updateFilterControls(page);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle();html="Thumb"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",lazy:!0,overlayPlayButton:!0,showTitle:!0}):"ThumbCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",lazy:!0,cardLayout:!0,showTitle:!0,showItemCounts:!0,vibrant:!0}):"Banner"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"banner",preferBanner:!0,context:"movies",lazy:!0}):"List"==viewStyle?listView.getListViewHtml({items:result.Items,context:"movies",sortBy:query.SortBy}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"auto",context:"movies",showTitle:!0,centerText:!1,cardLayout:!0,showItemCounts:!0,vibrant:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"auto",context:"movies",centerText:!0,lazy:!0,overlayPlayButton:!0,showTitle:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i'+Globalize.translate("MessageNoCollectionsAvailable")+"

");var itemsContainer=tabContent.querySelector(".itemsContainer");itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer),libraryBrowser.saveQueryValues(getSavedQueryKey(page),query),Dashboard.hideLoadingMsg()})}function updateFilterControls(tabContent){}function initPage(tabContent){tabContent.querySelector(".btnSort").addEventListener("click",function(e){libraryBrowser.showSortMenu({items:[{name:Globalize.translate("OptionNameSort"),id:"SortName"},{name:Globalize.translate("OptionImdbRating"),id:"CommunityRating,SortName"},{name:Globalize.translate("OptionDateAdded"),id:"DateCreated,SortName"},{name:Globalize.translate("OptionParentalRating"),id:"OfficialRating,SortName"},{name:Globalize.translate("OptionReleaseDate"),id:"PremiereDate,SortName"}],callback:function(){getQuery(tabContent).StartIndex=0,reloadItems(tabContent)},query:getQuery(tabContent),button:e.target})});var btnSelectView=tabContent.querySelector(".btnSelectView");btnSelectView.addEventListener("click",function(e){libraryBrowser.showLayoutMenu(e.target,self.getCurrentViewStyle(),"List,Poster,PosterCard,Thumb,ThumbCard".split(","))}),btnSelectView.addEventListener("layoutchange",function(e){var viewStyle=e.detail.viewStyle;getPageData(tabContent).view=viewStyle,libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent),viewStyle),getQuery(tabContent).StartIndex=0,onViewStyleChange(),reloadItems(tabContent)}),tabContent.querySelector(".btnNewCollection").addEventListener("click",function(){require(["collectionEditor"],function(collectionEditor){var serverId=ApiClient.serverInfo().Id;(new collectionEditor).show({items:[],serverId:serverId})})})}var self=this,pageSize=libraryBrowser.getDefaultPageSize(),data={};self.getCurrentViewStyle=function(){return getPageData(tabContent).view},initPage(tabContent),onViewStyleChange(),self.renderTab=function(){reloadItems(tabContent),updateFilterControls(tabContent)},self.destroy=function(){}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/moviegenres.js b/dashboard-ui/scripts/moviegenres.js index 5bec443c7a..9ee1ab6b0b 100644 --- a/dashboard-ui/scripts/moviegenres.js +++ b/dashboard-ui/scripts/moviegenres.js @@ -1,246 +1 @@ -define(['libraryBrowser', 'cardBuilder', 'lazyLoader', 'apphost', 'globalize', 'dom'], function (libraryBrowser, cardBuilder, lazyLoader, appHost, globalize, dom) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - - var data = {}; - function getPageData() { - var key = getSavedQueryKey(); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Movie", - Recursive: true, - EnableTotalRecordCount: false - }, - view: libraryBrowser.getSavedView(key) || (appHost.preferVisualCards ? 'PosterCard' : 'Poster') - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery() { - - return getPageData().query; - } - - function getSavedQueryKey() { - - return libraryBrowser.getSavedQueryKey('moviegenres'); - } - - function getPromise() { - - Dashboard.showLoadingMsg(); - var query = getQuery(); - - return ApiClient.getGenres(Dashboard.getCurrentUserId(), query); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function getThumbShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function getPortraitShape() { - return enableScrollX() ? 'overflowPortrait' : 'portrait'; - } - - function getMoreItemsHref(itemId, type) { - - return 'secondaryitems.html?type=' + type + '&genreId=' + itemId + '&parentId=' + params.topParentId; - } - - dom.addEventListener(tabContent, 'click', function (e) { - - var btnMoreFromGenre = dom.parentWithClass(e.target, 'btnMoreFromGenre'); - if (btnMoreFromGenre) { - var id = btnMoreFromGenre.getAttribute('data-id'); - Dashboard.navigate(getMoreItemsHref(id, 'Movie')); - } - - }, { - passive: true - }); - - function fillItemsContainer(elem) { - - var id = elem.getAttribute('data-id'); - - var viewStyle = self.getCurrentViewStyle(); - - var limit = viewStyle == 'Thumb' || viewStyle == 'ThumbCard' ? - 5 : - 8; - - if (enableScrollX()) { - limit = 10; - } - - var enableImageTypes = viewStyle == 'Thumb' || viewStyle == 'ThumbCard' ? - "Primary,Backdrop,Thumb" : - "Primary"; - - var query = { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Movie", - Recursive: true, - Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: enableImageTypes, - Limit: limit, - GenreIds: id, - EnableTotalRecordCount: false, - ParentId: params.topParentId - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - if (viewStyle == "Thumb") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getThumbShape(), - preferThumb: true, - showTitle: true, - scalable: true, - centerText: true, - overlayMoreButton: true, - allowBottomPadding: false - }); - } - else if (viewStyle == "ThumbCard") { - - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getThumbShape(), - preferThumb: true, - showTitle: true, - scalable: true, - centerText: false, - cardLayout: true, - vibrant: supportsImageAnalysis, - showYear: true - }); - } - else if (viewStyle == "PosterCard") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getPortraitShape(), - showTitle: true, - scalable: true, - centerText: false, - cardLayout: true, - vibrant: supportsImageAnalysis, - showYear: true - }); - } - else if (viewStyle == "Poster") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getPortraitShape(), - showTitle: true, - scalable: true, - centerText: true, - overlayMoreButton: true, - allowBottomPadding: false - }); - } - - if (result.Items.length >= query.Limit) { - tabContent.querySelector('.btnMoreFromGenre' + id).classList.remove('hide'); - } - }); - } - - function reloadItems(context, promise) { - - var query = getQuery(); - - promise.then(function (result) { - - var elem = context.querySelector('#items'); - var html = ''; - - var items = result.Items; - - for (var i = 0, length = items.length; i < length; i++) { - - var item = items[i]; - - html += '
'; - - html += '
'; - html += '

'; - html += item.Name; - html += '

'; - html += ''; - html += '
'; - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - html += '
'; - - html += '
'; - } - - elem.innerHTML = html; - - lazyLoader.lazyChildren(elem, fillItemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - self.getViewStyles = function () { - return 'Poster,PosterCard,Thumb,ThumbCard'.split(','); - }; - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - self.setCurrentViewStyle = function (viewStyle) { - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - fullyReload(); - }; - - self.enableViewSelection = true; - var promise; - - self.preRender = function () { - promise = getPromise(); - }; - - self.renderTab = function () { - - reloadItems(tabContent, promise); - }; - - function fullyReload() { - self.preRender(); - self.renderTab(); - } - }; -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","lazyLoader","apphost","globalize","dom"],function(libraryBrowser,cardBuilder,lazyLoader,appHost,globalize,dom){"use strict";return function(view,params,tabContent){function getPageData(){var key=getSavedQueryKey(),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Movie",Recursive:!0,EnableTotalRecordCount:!1},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(){return getPageData().query}function getSavedQueryKey(){return libraryBrowser.getSavedQueryKey("moviegenres")}function getPromise(){Dashboard.showLoadingMsg();var query=getQuery();return ApiClient.getGenres(Dashboard.getCurrentUserId(),query)}function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function getPortraitShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getMoreItemsHref(itemId,type){return"secondaryitems.html?type="+type+"&genreId="+itemId+"&parentId="+params.topParentId}function fillItemsContainer(elem){var id=elem.getAttribute("data-id"),viewStyle=self.getCurrentViewStyle(),limit="Thumb"==viewStyle||"ThumbCard"==viewStyle?5:8;enableScrollX()&&(limit=10);var enableImageTypes="Thumb"==viewStyle||"ThumbCard"==viewStyle?"Primary,Backdrop,Thumb":"Primary",query={SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Movie",Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:enableImageTypes,Limit:limit,GenreIds:id,EnableTotalRecordCount:!1,ParentId:params.topParentId};ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){var supportsImageAnalysis=appHost.supports("imageanalysis");"Thumb"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getThumbShape(),preferThumb:!0,showTitle:!0,scalable:!0,centerText:!0,overlayMoreButton:!0,allowBottomPadding:!1}):"ThumbCard"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getThumbShape(),preferThumb:!0,showTitle:!0,scalable:!0,centerText:!1,cardLayout:!0,vibrant:supportsImageAnalysis,showYear:!0}):"PosterCard"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getPortraitShape(),showTitle:!0,scalable:!0,centerText:!1,cardLayout:!0,vibrant:supportsImageAnalysis,showYear:!0}):"Poster"==viewStyle&&cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getPortraitShape(),showTitle:!0,scalable:!0,centerText:!0,overlayMoreButton:!0,allowBottomPadding:!1}),result.Items.length>=query.Limit&&tabContent.querySelector(".btnMoreFromGenre"+id).classList.remove("hide")})}function reloadItems(context,promise){var query=getQuery();promise.then(function(result){for(var elem=context.querySelector("#items"),html="",items=result.Items,i=0,length=items.length;i',html+='
',html+='

',html+=item.Name,html+="

",html+='",html+="
",html+=enableScrollX()?'
':'
',html+="
",html+="
"}elem.innerHTML=html,lazyLoader.lazyChildren(elem,fillItemsContainer),libraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}function fullyReload(){self.preRender(),self.renderTab()}var self=this,data={};dom.addEventListener(tabContent,"click",function(e){var btnMoreFromGenre=dom.parentWithClass(e.target,"btnMoreFromGenre");if(btnMoreFromGenre){var id=btnMoreFromGenre.getAttribute("data-id");Dashboard.navigate(getMoreItemsHref(id,"Movie"))}},{passive:!0}),self.getViewStyles=function(){return"Poster,PosterCard,Thumb,ThumbCard".split(",")},self.getCurrentViewStyle=function(){return getPageData(tabContent).view},self.setCurrentViewStyle=function(viewStyle){getPageData(tabContent).view=viewStyle,libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent),viewStyle),fullyReload()},self.enableViewSelection=!0;var promise;self.preRender=function(){promise=getPromise()},self.renderTab=function(){reloadItems(tabContent,promise)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/movies.js b/dashboard-ui/scripts/movies.js index ab66afd8ad..f9219a6cdd 100644 --- a/dashboard-ui/scripts/movies.js +++ b/dashboard-ui/scripts/movies.js @@ -1,340 +1 @@ -define(['events', 'libraryBrowser', 'imageLoader', 'alphaPicker', 'listView', 'cardBuilder', 'apphost', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, alphaPicker, listView, cardBuilder, appHost) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var pageSize = libraryBrowser.getDefaultPageSize(); - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Movie", - Recursive: true, - Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: pageSize - }, - view: libraryBrowser.getSavedView(key) || (appHost.preferVisualCards ? 'PosterCard' : 'Poster') - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey('movies'); - } - return context.savedQueryKey; - } - - function onViewStyleChange() { - - var viewStyle = self.getCurrentViewStyle(); - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - updateFilterControls(page); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: false, - sortButton: false, - filterButton: false - }); - - var html; - var viewStyle = self.getCurrentViewStyle(); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - if (viewStyle == "Thumb") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'movies', - lazy: true, - overlayPlayButton: true - }); - } - else if (viewStyle == "ThumbCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'movies', - lazy: true, - cardLayout: true, - showTitle: true, - showYear: true, - vibrant: supportsImageAnalysis - }); - } - else if (viewStyle == "Banner") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "banner", - preferBanner: true, - context: 'movies', - lazy: true - }); - } - else if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - context: 'movies', - sortBy: query.SortBy - }); - } - else if (viewStyle == "PosterCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "portrait", - context: 'movies', - showTitle: true, - showYear: true, - lazy: true, - cardLayout: true, - vibrant: supportsImageAnalysis - }); - } - else { - - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "portrait", - context: 'movies', - centerText: true, - lazy: true, - overlayPlayButton: true - }); - } - - var i, length; - var elems = tabContent.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(tabContent); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(tabContent); - } - - elems = tabContent.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = tabContent.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.showFilterMenu = function () { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(tabContent), - mode: 'movies' - }); - - Events.on(filterDialog, 'filterchange', function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }); - - filterDialog.show(); - }); - } - - function updateFilterControls(tabContent) { - - var query = getQuery(tabContent); - self.alphaPicker.value(query.NameStartsWithOrGreater); - } - - function initPage(tabContent) { - - var alphaPickerElement = tabContent.querySelector('.alphaPicker'); - alphaPickerElement.addEventListener('alphavaluechanged', function (e) { - var newValue = e.detail.value; - var query = getQuery(tabContent); - query.NameStartsWithOrGreater = newValue; - query.StartIndex = 0; - reloadItems(tabContent); - }); - - self.alphaPicker = new alphaPicker({ - element: alphaPickerElement, - valueChangeEvent: 'click' - }); - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - self.showFilterMenu(); - }); - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SortName' - }, - { - name: Globalize.translate('OptionBudget'), - id: 'Budget,SortName' - }, - { - name: Globalize.translate('OptionImdbRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionCriticRating'), - id: 'CriticRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionDatePlayed'), - id: 'DatePlayed,SortName' - }, - { - name: Globalize.translate('OptionMetascore'), - id: 'Metascore,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SortName' - }, - { - name: Globalize.translate('OptionPlayCount'), - id: 'PlayCount,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'PremiereDate,SortName' - }, - { - name: Globalize.translate('OptionRevenue'), - id: 'Revenue,SortName' - }, - { - name: Globalize.translate('OptionRuntime'), - id: 'Runtime,SortName' - }], - callback: function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - - var btnSelectView = tabContent.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), 'Banner,List,Poster,PosterCard,Thumb,ThumbCard'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - - var viewStyle = e.detail.viewStyle; - - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - getQuery(tabContent).StartIndex = 0; - onViewStyleChange(); - reloadItems(tabContent); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - onViewStyleChange(); - - self.renderTab = function () { - - reloadItems(tabContent); - updateFilterControls(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","alphaPicker","listView","cardBuilder","apphost","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,alphaPicker,listView,cardBuilder,appHost){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Movie",Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("movies")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0),updateFilterControls(page);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle(),supportsImageAnalysis=appHost.supports("imageanalysis");html="Thumb"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",lazy:!0,overlayPlayButton:!0}):"ThumbCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",lazy:!0,cardLayout:!0,showTitle:!0,showYear:!0,vibrant:supportsImageAnalysis}):"Banner"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"banner",preferBanner:!0,context:"movies",lazy:!0}):"List"==viewStyle?listView.getListViewHtml({items:result.Items,context:"movies",sortBy:query.SortBy}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"movies",showTitle:!0,showYear:!0,lazy:!0,cardLayout:!0,vibrant:supportsImageAnalysis}):cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"movies",centerText:!0,lazy:!0,overlayPlayButton:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i= 1920 ? 5 : (screenWidth >= 1600 ? 5 : 3), - Recursive: true, - Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo", - CollapseBoxSetItems: false, - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - ApiClient.getItems(userId, options).then(function (result) { - - if (result.Items.length) { - page.querySelector('#resumableSection').classList.remove('hide'); - } else { - page.querySelector('#resumableSection').classList.add('hide'); - } - - var allowBottomPadding = !enableScrollX(); - - var container = page.querySelector('#resumableItems'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = appHost.preferVisualCards; - - cardBuilder.buildCards(result.Items, { - itemsContainer: container, - preferThumb: true, - shape: getThumbShape(), - scalable: true, - overlayPlayButton: true, - allowBottomPadding: allowBottomPadding, - cardLayout: cardLayout, - vibrant: cardLayout && supportsImageAnalysis, - showTitle: cardLayout, - showYear: cardLayout - }); - - }); - } - - function getRecommendationHtml(recommendation) { - - var html = ''; - - var title = ''; - - switch (recommendation.RecommendationType) { - - case 'SimilarToRecentlyPlayed': - title = Globalize.translate('RecommendationBecauseYouWatched').replace("{0}", recommendation.BaselineItemName); - break; - case 'SimilarToLikedItem': - title = Globalize.translate('RecommendationBecauseYouLike').replace("{0}", recommendation.BaselineItemName); - break; - case 'HasDirectorFromRecentlyPlayed': - case 'HasLikedDirector': - title = Globalize.translate('RecommendationDirectedBy').replace("{0}", recommendation.BaselineItemName); - break; - case 'HasActorFromRecentlyPlayed': - case 'HasLikedActor': - title = Globalize.translate('RecommendationStarring').replace("{0}", recommendation.BaselineItemName); - break; - } - - html += '
'; - html += '

' + title + '

'; - - var allowBottomPadding = true; - - if (enableScrollX()) { - allowBottomPadding = false; - html += '
'; - } else { - html += '
'; - } - - html += cardBuilder.getCardsHtml(recommendation.Items, { - shape: getPortraitShape(), - scalable: true, - overlayPlayButton: true, - allowBottomPadding: allowBottomPadding - }); - - html += '
'; - html += '
'; - - return html; - } - - function loadSuggestions(page, userId, parentId) { - - var screenWidth = dom.getWindowSize().innerWidth; - - var url = ApiClient.getUrl("Movies/Recommendations", { - - userId: userId, - categoryLimit: 6, - ItemLimit: screenWidth >= 1920 ? 8 : (screenWidth >= 1600 ? 8 : (screenWidth >= 1200 ? 6 : 5)), - Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb" - }); - - ApiClient.getJSON(url).then(function (recommendations) { - - if (!recommendations.length) { - - page.querySelector('.noItemsMessage').classList.remove('hide'); - page.querySelector('.recommendations').innerHTML = ''; - return; - } - - var html = recommendations.map(getRecommendationHtml).join(''); - - page.querySelector('.noItemsMessage').classList.add('hide'); - - var recs = page.querySelector('.recommendations'); - recs.innerHTML = html; - imageLoader.lazyChildren(recs); - }); - } - - function initSuggestedTab(page, tabContent) { - - var containers = tabContent.querySelectorAll('.itemsContainer'); - for (var i = 0, length = containers.length; i < length; i++) { - if (enableScrollX()) { - containers[i].classList.add('hiddenScrollX'); - containers[i].classList.remove('vertical-wrap'); - } else { - containers[i].classList.remove('hiddenScrollX'); - containers[i].classList.add('vertical-wrap'); - } - } - } - - function loadSuggestionsTab(view, params, tabContent) { - - var parentId = params.topParentId; - - var userId = Dashboard.getCurrentUserId(); - - console.log('loadSuggestionsTab'); - loadResume(tabContent, userId, parentId); - loadLatest(tabContent, userId, parentId); - - loadSuggestions(tabContent, userId, parentId); - } - - return function (view, params) { - - var self = this; - - self.initTab = function () { - - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - categorysyncbuttons.init(tabContent); - initSuggestedTab(view, tabContent); - }; - - self.renderTab = function () { - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - loadSuggestionsTab(view, params, tabContent); - }; - - var viewTabs = view.querySelector('.libraryViewNav'); - - libraryBrowser.configurePaperLibraryTabs(view, viewTabs, view.querySelectorAll('.pageTabContent'), [0, 3, 4, 5]); - - var tabControllers = []; - var renderedTabs = []; - - function getTabController(page, index, callback) { - - var depends = []; - - switch (index) { - - case 0: - break; - case 1: - depends.push('scripts/movies'); - break; - case 2: - depends.push('scripts/movietrailers'); - break; - case 3: - depends.push('scripts/moviecollections'); - break; - case 4: - depends.push('scripts/moviegenres'); - break; - case 5: - depends.push('scripts/moviestudios'); - break; - default: - break; - } - - require(depends, function (controllerFactory) { - var tabContent; - if (index == 0) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - self.tabContent = tabContent; - } - var controller = tabControllers[index]; - if (!controller) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - controller = index ? new controllerFactory(view, params, tabContent) : self; - tabControllers[index] = controller; - - if (controller.initTab) { - controller.initTab(); - } - } - - callback(controller); - }); - } - - function preLoadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - if (controller.preRender) { - controller.preRender(); - } - } - }); - } - - function loadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - renderedTabs.push(index); - controller.renderTab(); - } - }); - } - - viewTabs.addEventListener('beforetabchange', function (e) { - preLoadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - viewTabs.addEventListener('tabchange', function (e) { - loadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - view.addEventListener('viewbeforeshow', function (e) { - - if (!view.getAttribute('data-title')) { - - var parentId = params.topParentId; - - if (parentId) { - - ApiClient.getItem(Dashboard.getCurrentUserId(), parentId).then(function (item) { - - view.setAttribute('data-title', item.Name); - LibraryMenu.setTitle(item.Name); - }); - - - } else { - view.setAttribute('data-title', Globalize.translate('TabMovies')); - LibraryMenu.setTitle(Globalize.translate('TabMovies')); - } - } - }); - - function onPlaybackStop(e, state) { - - if (state.NowPlayingItem && state.NowPlayingItem.MediaType == 'Video') { - - renderedTabs = []; - viewTabs.triggerTabChange(); - } - } - - view.addEventListener('viewshow', function (e) { - Events.on(playbackManager, 'playbackstop', onPlaybackStop); - }); - - view.addEventListener('viewbeforehide', function (e) { - Events.off(playbackManager, 'playbackstop', onPlaybackStop); - }); - - require(["headroom-window"], function (headroom) { - headroom.add(viewTabs); - self.headroom = headroom; - }); - - view.addEventListener('viewdestroy', function (e) { - if (self.headroom) { - self.headroom.remove(viewTabs); - } - }); - }; - -}); \ No newline at end of file +define(["libraryBrowser","components/categorysyncbuttons","cardBuilder","dom","apphost","imageLoader","playbackManager","scrollStyles","emby-itemscontainer","emby-tabs","emby-button"],function(libraryBrowser,categorysyncbuttons,cardBuilder,dom,appHost,imageLoader,playbackManager){"use strict";function enableScrollX(){return browserInfo.mobile}function getPortraitShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function loadLatest(page,userId,parentId){var options={IncludeItemTypes:"Movie",Limit:18,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};ApiClient.getJSON(ApiClient.getUrl("Users/"+userId+"/Items/Latest",options)).then(function(items){var allowBottomPadding=!enableScrollX(),container=page.querySelector("#recentlyAddedItems");cardBuilder.buildCards(items,{itemsContainer:container,shape:getPortraitShape(),scalable:!0,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding})})}function loadResume(page,userId,parentId){var screenWidth=dom.getWindowSize().innerWidth,options={SortBy:"DatePlayed",SortOrder:"Descending",IncludeItemTypes:"Movie",Filters:"IsResumable",Limit:screenWidth>=1920?5:screenWidth>=1600?5:3,Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",CollapseBoxSetItems:!1,ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(userId,options).then(function(result){result.Items.length?page.querySelector("#resumableSection").classList.remove("hide"):page.querySelector("#resumableSection").classList.add("hide");var allowBottomPadding=!enableScrollX(),container=page.querySelector("#resumableItems"),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=appHost.preferVisualCards;cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:getThumbShape(),scalable:!0,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding,cardLayout:cardLayout,vibrant:cardLayout&&supportsImageAnalysis,showTitle:cardLayout,showYear:cardLayout})})}function getRecommendationHtml(recommendation){var html="",title="";switch(recommendation.RecommendationType){case"SimilarToRecentlyPlayed":title=Globalize.translate("RecommendationBecauseYouWatched").replace("{0}",recommendation.BaselineItemName);break;case"SimilarToLikedItem":title=Globalize.translate("RecommendationBecauseYouLike").replace("{0}",recommendation.BaselineItemName);break;case"HasDirectorFromRecentlyPlayed":case"HasLikedDirector":title=Globalize.translate("RecommendationDirectedBy").replace("{0}",recommendation.BaselineItemName);break;case"HasActorFromRecentlyPlayed":case"HasLikedActor":title=Globalize.translate("RecommendationStarring").replace("{0}",recommendation.BaselineItemName)}html+='
',html+='

'+title+"

";var allowBottomPadding=!0;return enableScrollX()?(allowBottomPadding=!1,html+='
'):html+='
',html+=cardBuilder.getCardsHtml(recommendation.Items,{shape:getPortraitShape(),scalable:!0,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding}),html+="
",html+="
"}function loadSuggestions(page,userId,parentId){var screenWidth=dom.getWindowSize().innerWidth,url=ApiClient.getUrl("Movies/Recommendations",{userId:userId,categoryLimit:6,ItemLimit:screenWidth>=1920?8:screenWidth>=1600?8:screenWidth>=1200?6:5,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb"});ApiClient.getJSON(url).then(function(recommendations){if(!recommendations.length)return page.querySelector(".noItemsMessage").classList.remove("hide"),void(page.querySelector(".recommendations").innerHTML="");var html=recommendations.map(getRecommendationHtml).join("");page.querySelector(".noItemsMessage").classList.add("hide");var recs=page.querySelector(".recommendations");recs.innerHTML=html,imageLoader.lazyChildren(recs)})}function initSuggestedTab(page,tabContent){for(var containers=tabContent.querySelectorAll(".itemsContainer"),i=0,length=containers.length;i'; - } - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(tabContent), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.showFilterMenu = function () { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(tabContent), - mode: 'movies' - }); - - Events.on(filterDialog, 'filterchange', function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(); - }); - - filterDialog.show(); - }); - } - - function updateFilterControls(tabContent) { - - var query = getQuery(tabContent); - self.alphaPicker.value(query.NameStartsWithOrGreater); - } - - function initPage(tabContent) { - - var alphaPickerElement = tabContent.querySelector('.alphaPicker'); - alphaPickerElement.addEventListener('alphavaluechanged', function (e) { - var newValue = e.detail.value; - var query = getQuery(tabContent); - query.NameStartsWithOrGreater = newValue; - query.StartIndex = 0; - reloadItems(); - }); - - self.alphaPicker = new alphaPicker({ - element: alphaPickerElement, - valueChangeEvent: 'click' - }); - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - self.showFilterMenu(); - }); - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SortName' - }, - { - name: Globalize.translate('OptionImdbRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionDatePlayed'), - id: 'DatePlayed,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SortName' - }, - { - name: Globalize.translate('OptionPlayCount'), - id: 'PlayCount,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'PremiereDate,SortName' - }], - callback: function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - - self.renderTab = function () { - - reloadItems(); - updateFilterControls(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","alphaPicker","listView","cardBuilder","apphost","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,alphaPicker,listView,cardBuilder,appHost){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Trailer",Recursive:!0,Fields:"PrimaryImageAspectRatio,SortName,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("trailers")),context.savedQueryKey}function reloadItems(){Dashboard.showLoadingMsg();var query=getQuery(tabContent);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems()}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems()}window.scrollTo(0,0),updateFilterControls(tabContent);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle();html="Thumb"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",overlayPlayButton:!0}):"ThumbCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"movies",cardLayout:!0,showTitle:!0,showYear:!0,vibrant:!0}):"Banner"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"banner",preferBanner:!0,context:"movies"}):"List"==viewStyle?listView.getListViewHtml({items:result.Items,context:"movies",sortBy:query.SortBy}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"movies",showTitle:!0,showYear:!0,cardLayout:!0,vibrant:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"movies",centerText:!0,overlayPlayButton:!0,showTitle:!0,showYear:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i'+Globalize.translate("MessageNoTrailersFound")+"

");var itemsContainer=tabContent.querySelector(".itemsContainer");itemsContainer.innerHTML=html,imageLoader.lazyChildren(itemsContainer),libraryBrowser.saveQueryValues(getSavedQueryKey(tabContent),query),Dashboard.hideLoadingMsg()})}function updateFilterControls(tabContent){var query=getQuery(tabContent);self.alphaPicker.value(query.NameStartsWithOrGreater)}function initPage(tabContent){var alphaPickerElement=tabContent.querySelector(".alphaPicker");alphaPickerElement.addEventListener("alphavaluechanged",function(e){var newValue=e.detail.value,query=getQuery(tabContent);query.NameStartsWithOrGreater=newValue,query.StartIndex=0,reloadItems()}),self.alphaPicker=new alphaPicker({element:alphaPickerElement,valueChangeEvent:"click"}),tabContent.querySelector(".btnFilter").addEventListener("click",function(){self.showFilterMenu()}),tabContent.querySelector(".btnSort").addEventListener("click",function(e){libraryBrowser.showSortMenu({items:[{name:Globalize.translate("OptionNameSort"),id:"SortName"},{name:Globalize.translate("OptionImdbRating"),id:"CommunityRating,SortName"},{name:Globalize.translate("OptionDateAdded"),id:"DateCreated,SortName"},{name:Globalize.translate("OptionDatePlayed"),id:"DatePlayed,SortName"},{name:Globalize.translate("OptionParentalRating"),id:"OfficialRating,SortName"},{name:Globalize.translate("OptionPlayCount"),id:"PlayCount,SortName"},{name:Globalize.translate("OptionReleaseDate"),id:"PremiereDate,SortName"}],callback:function(){getQuery(tabContent).StartIndex=0,reloadItems()},query:getQuery(tabContent),button:e.target})})}var self=this,pageSize=libraryBrowser.getDefaultPageSize(),data={};self.showFilterMenu=function(){require(["components/filterdialog/filterdialog"],function(filterDialogFactory){var filterDialog=new filterDialogFactory({query:getQuery(tabContent),mode:"movies"});Events.on(filterDialog,"filterchange",function(){getQuery(tabContent).StartIndex=0,reloadItems()}),filterDialog.show()})},self.getCurrentViewStyle=function(){return getPageData(tabContent).view},initPage(tabContent),self.renderTab=function(){reloadItems(),updateFilterControls(tabContent)},self.destroy=function(){}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/musicalbums.js b/dashboard-ui/scripts/musicalbums.js index 40fa8b82e4..b3e14c21af 100644 --- a/dashboard-ui/scripts/musicalbums.js +++ b/dashboard-ui/scripts/musicalbums.js @@ -1,283 +1 @@ -define(['events', 'libraryBrowser', 'imageLoader', 'alphaPicker', 'listView', 'cardBuilder', 'apphost', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, alphaPicker, listView, cardBuilder, appHost) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var pageSize = libraryBrowser.getDefaultPageSize(); - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "MusicAlbum", - Recursive: true, - Fields: "PrimaryImageAspectRatio,SortName,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: pageSize - }, - view: libraryBrowser.getSavedView(key) || (appHost.preferVisualCards ? 'PosterCard' : 'Poster') - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey('musicalbums'); - } - return context.savedQueryKey; - } - - function onViewStyleChange() { - - var viewStyle = self.getCurrentViewStyle(); - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - updateFilterControls(page); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: false, - sortButton: false, - filterButton: false - }); - - var html; - var viewStyle = self.getCurrentViewStyle(); - - if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - context: 'music', - sortBy: query.SortBy, - addToListButton: true - }); - } - else if (viewStyle == "PosterCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "square", - context: 'music', - showTitle: true, - coverImage: true, - showParentTitle: true, - lazy: true, - cardLayout: true, - vibrant: true - }); - } - else { - - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "square", - context: 'music', - showTitle: true, - showParentTitle: true, - lazy: true, - centerText: true, - overlayPlayButton: true - }); - } - - var i, length; - var elems = tabContent.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(tabContent); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(tabContent); - } - - elems = tabContent.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = tabContent.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.showFilterMenu = function () { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(tabContent), - mode: 'albums' - }); - - Events.on(filterDialog, 'filterchange', function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }); - - filterDialog.show(); - }); - } - - function updateFilterControls(tabContent) { - - var query = getQuery(tabContent); - self.alphaPicker.value(query.NameStartsWithOrGreater); - } - - function initPage(tabContent) { - - var alphaPickerElement = tabContent.querySelector('.alphaPicker'); - alphaPickerElement.addEventListener('alphavaluechanged', function (e) { - var newValue = e.detail.value; - var query = getQuery(tabContent); - query.NameStartsWithOrGreater = newValue; - query.StartIndex = 0; - reloadItems(tabContent); - }); - - self.alphaPicker = new alphaPicker({ - element: alphaPickerElement, - valueChangeEvent: 'click' - }); - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - self.showFilterMenu(); - }); - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SortName' - }, - { - name: Globalize.translate('OptionAlbumArtist'), - id: 'AlbumArtist,SortName' - }, - { - name: Globalize.translate('OptionCommunityRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionCriticRating'), - id: 'CriticRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'ProductionYear,PremiereDate,SortName' - }], - callback: function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - - var btnSelectView = tabContent.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), 'List,Poster,PosterCard'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - - var viewStyle = e.detail.viewStyle; - - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - getQuery(tabContent).StartIndex = 0; - onViewStyleChange(); - reloadItems(tabContent); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - onViewStyleChange(); - - self.renderTab = function () { - - reloadItems(tabContent); - updateFilterControls(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","alphaPicker","listView","cardBuilder","apphost","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,alphaPicker,listView,cardBuilder,appHost){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"MusicAlbum",Recursive:!0,Fields:"PrimaryImageAspectRatio,SortName,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("musicalbums")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0),updateFilterControls(page);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle();html="List"==viewStyle?listView.getListViewHtml({items:result.Items,context:"music",sortBy:query.SortBy,addToListButton:!0}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"square",context:"music",showTitle:!0,coverImage:!0,showParentTitle:!0,lazy:!0,cardLayout:!0,vibrant:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"square",context:"music",showTitle:!0,showParentTitle:!0,lazy:!0,centerText:!0,overlayPlayButton:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i= 1920 ? 9 : (screenWidth >= 1200 ? 12 : (screenWidth >= 1000 ? 10 : 8)); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function getSquareShape() { - return enableScrollX() ? 'overflowSquare' : 'square'; - } - - function loadLatest(page, parentId) { - - Dashboard.showLoadingMsg(); - - var userId = Dashboard.getCurrentUserId(); - - var options = { - IncludeItemTypes: "Audio", - Limit: itemsPerRow(), - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - ApiClient.getJSON(ApiClient.getUrl('Users/' + userId + '/Items/Latest', options)).then(function (items) { - - var elem = page.querySelector('#recentlyAddedSongs'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - elem.innerHTML = cardBuilder.getCardsHtml({ - items: items, - showUnplayedIndicator: false, - showLatestItemsPopup: false, - shape: getSquareShape(), - showTitle: true, - showParentTitle: true, - lazy: true, - centerText: !supportsImageAnalysis, - overlayPlayButton: !supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - imageLoader.lazyChildren(elem); - - Dashboard.hideLoadingMsg(); - }); - } - - function loadRecentlyPlayed(page, parentId) { - - var options = { - - SortBy: "DatePlayed", - SortOrder: "Descending", - IncludeItemTypes: "Audio", - Limit: itemsPerRow(), - Recursive: true, - Fields: "PrimaryImageAspectRatio,AudioInfo", - Filters: "IsPlayed", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), options).then(function (result) { - - var elem = page.querySelector('#recentlyPlayed'); - - if (result.Items.length) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - - var itemsContainer = elem.querySelector('.itemsContainer'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - itemsContainer.innerHTML = cardBuilder.getCardsHtml({ - items: result.Items, - showUnplayedIndicator: false, - shape: getSquareShape(), - showTitle: true, - showParentTitle: true, - action: 'instantmix', - lazy: true, - centerText: !supportsImageAnalysis, - overlayMoreButton: !supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - imageLoader.lazyChildren(itemsContainer); - - }); - - } - - function loadFrequentlyPlayed(page, parentId) { - - var options = { - - SortBy: "PlayCount", - SortOrder: "Descending", - IncludeItemTypes: "Audio", - Limit: itemsPerRow(), - Recursive: true, - Fields: "PrimaryImageAspectRatio,AudioInfo", - Filters: "IsPlayed", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), options).then(function (result) { - - var elem = page.querySelector('#topPlayed'); - - if (result.Items.length) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - - var itemsContainer = elem.querySelector('.itemsContainer'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - itemsContainer.innerHTML = cardBuilder.getCardsHtml({ - items: result.Items, - showUnplayedIndicator: false, - shape: getSquareShape(), - showTitle: true, - showParentTitle: true, - action: 'instantmix', - lazy: true, - centerText: !supportsImageAnalysis, - overlayMoreButton: !supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - imageLoader.lazyChildren(itemsContainer); - - }); - - } - - function loadPlaylists(page, parentId) { - - var options = { - - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Playlist", - Recursive: true, - Fields: "PrimaryImageAspectRatio,SortName,CumulativeRunTimeTicks,CanDelete", - StartIndex: 0, - Limit: itemsPerRow(), - EnableTotalRecordCount: false - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), options).then(function (result) { - - var elem = page.querySelector('#playlists'); - - if (result.Items.length) { - elem.classList.remove('hide'); - } else { - elem.classList.add('hide'); - } - - var itemsContainer = elem.querySelector('.itemsContainer'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - itemsContainer.innerHTML = cardBuilder.getCardsHtml({ - items: result.Items, - shape: getSquareShape(), - showTitle: true, - lazy: true, - coverImage: true, - showItemCounts: true, - centerText: !supportsImageAnalysis, - overlayPlayButton: !supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - imageLoader.lazyChildren(itemsContainer); - - }); - } - - function loadSuggestionsTab(page, tabContent, parentId) { - - console.log('loadSuggestionsTab'); - loadLatest(tabContent, parentId); - loadPlaylists(tabContent, parentId); - loadRecentlyPlayed(tabContent, parentId); - loadFrequentlyPlayed(tabContent, parentId); - - require(['components/favoriteitems'], function (favoriteItems) { - - favoriteItems.render(tabContent, Dashboard.getCurrentUserId(), parentId, ['favoriteArtists', 'favoriteAlbums', 'favoriteSongs']); - - }); - } - - return function (view, params) { - - var self = this; - - function reload() { - - Dashboard.showLoadingMsg(); - - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - loadSuggestionsTab(view, tabContent, params.topParentId); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - self.initTab = function () { - - var tabContent = view.querySelector('.pageTabContent[data-index=\'' + 0 + '\']'); - - var containers = tabContent.querySelectorAll('.itemsContainer'); - for (var i = 0, length = containers.length; i < length; i++) { - if (enableScrollX()) { - containers[i].classList.add('hiddenScrollX'); - containers[i].classList.remove('vertical-wrap'); - } else { - containers[i].classList.remove('hiddenScrollX'); - containers[i].classList.add('vertical-wrap'); - } - } - }; - - self.renderTab = function () { - reload(); - }; - - var tabControllers = []; - var renderedTabs = []; - - function getTabController(page, index, callback) { - - var depends = []; - - switch (index) { - - case 0: - break; - case 1: - depends.push('scripts/musicalbums'); - break; - case 2: - depends.push('scripts/musicartists'); - break; - case 3: - depends.push('scripts/musicartists'); - break; - case 4: - depends.push('scripts/songs'); - break; - case 5: - depends.push('scripts/musicgenres'); - break; - case 6: - depends.push('scripts/musicfolders'); - break; - default: - break; - } - - require(depends, function (controllerFactory) { - var tabContent; - if (index == 0) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - self.tabContent = tabContent; - } - var controller = tabControllers[index]; - if (!controller) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - controller = index ? new controllerFactory(view, params, tabContent) : self; - - if (index == 2) { - controller.mode = 'albumartists'; - } else if (index == 3) { - controller.mode = 'artists'; - } - - tabControllers[index] = controller; - - if (controller.initTab) { - controller.initTab(); - } - } - - callback(controller); - }); - } - - function preLoadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - if (controller.preRender) { - controller.preRender(); - } - } - }); - } - - function loadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - renderedTabs.push(index); - controller.renderTab(); - } - }); - } - - var viewTabs = view.querySelector('.libraryViewNav'); - - libraryBrowser.configurePaperLibraryTabs(view, viewTabs, view.querySelectorAll('.pageTabContent'), [0, 4, 5, 6]); - - viewTabs.addEventListener('beforetabchange', function (e) { - preLoadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - viewTabs.addEventListener('tabchange', function (e) { - loadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - view.addEventListener('viewbeforeshow', function (e) { - - if (!view.getAttribute('data-title')) { - - var parentId = params.topParentId; - - if (parentId) { - - ApiClient.getItem(Dashboard.getCurrentUserId(), parentId).then(function (item) { - - view.setAttribute('data-title', item.Name); - libraryMenu.setTitle(item.Name); - }); - - - } else { - view.setAttribute('data-title', Globalize.translate('TabMusic')); - libraryMenu.setTitle(Globalize.translate('TabMusic')); - } - } - }); - - require(["headroom-window"], function (headroom) { - headroom.add(viewTabs); - self.headroom = headroom; - }); - - view.addEventListener('viewdestroy', function (e) { - - if (self.headroom) { - self.headroom.remove(viewTabs); - } - tabControllers.forEach(function (t) { - if (t.destroy) { - t.destroy(); - } - }); - }); - }; - -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","dom","apphost","imageLoader","libraryMenu","scrollStyles","emby-itemscontainer","emby-tabs","emby-button"],function(libraryBrowser,cardBuilder,dom,appHost,imageLoader,libraryMenu){"use strict";function itemsPerRow(){var screenWidth=dom.getWindowSize().innerWidth;return screenWidth>=1920?9:screenWidth>=1200?12:screenWidth>=1e3?10:8}function enableScrollX(){return browserInfo.mobile}function getSquareShape(){return enableScrollX()?"overflowSquare":"square"}function loadLatest(page,parentId){Dashboard.showLoadingMsg();var userId=Dashboard.getCurrentUserId(),options={IncludeItemTypes:"Audio",Limit:itemsPerRow(),Fields:"PrimaryImageAspectRatio,BasicSyncInfo",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};ApiClient.getJSON(ApiClient.getUrl("Users/"+userId+"/Items/Latest",options)).then(function(items){var elem=page.querySelector("#recentlyAddedSongs"),supportsImageAnalysis=appHost.supports("imageanalysis");elem.innerHTML=cardBuilder.getCardsHtml({items:items,showUnplayedIndicator:!1,showLatestItemsPopup:!1,shape:getSquareShape(),showTitle:!0,showParentTitle:!0,lazy:!0,centerText:!supportsImageAnalysis,overlayPlayButton:!supportsImageAnalysis,allowBottomPadding:!enableScrollX(),cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),imageLoader.lazyChildren(elem),Dashboard.hideLoadingMsg()})}function loadRecentlyPlayed(page,parentId){var options={SortBy:"DatePlayed",SortOrder:"Descending",IncludeItemTypes:"Audio",Limit:itemsPerRow(),Recursive:!0,Fields:"PrimaryImageAspectRatio,AudioInfo",Filters:"IsPlayed",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){var elem=page.querySelector("#recentlyPlayed");result.Items.length?elem.classList.remove("hide"):elem.classList.add("hide");var itemsContainer=elem.querySelector(".itemsContainer"),supportsImageAnalysis=appHost.supports("imageanalysis");itemsContainer.innerHTML=cardBuilder.getCardsHtml({items:result.Items,showUnplayedIndicator:!1,shape:getSquareShape(),showTitle:!0,showParentTitle:!0,action:"instantmix",lazy:!0,centerText:!supportsImageAnalysis,overlayMoreButton:!supportsImageAnalysis,allowBottomPadding:!enableScrollX(),cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),imageLoader.lazyChildren(itemsContainer)})}function loadFrequentlyPlayed(page,parentId){var options={SortBy:"PlayCount",SortOrder:"Descending",IncludeItemTypes:"Audio",Limit:itemsPerRow(),Recursive:!0,Fields:"PrimaryImageAspectRatio,AudioInfo",Filters:"IsPlayed",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){var elem=page.querySelector("#topPlayed");result.Items.length?elem.classList.remove("hide"):elem.classList.add("hide");var itemsContainer=elem.querySelector(".itemsContainer"),supportsImageAnalysis=appHost.supports("imageanalysis");itemsContainer.innerHTML=cardBuilder.getCardsHtml({items:result.Items,showUnplayedIndicator:!1,shape:getSquareShape(),showTitle:!0,showParentTitle:!0,action:"instantmix",lazy:!0,centerText:!supportsImageAnalysis,overlayMoreButton:!supportsImageAnalysis,allowBottomPadding:!enableScrollX(),cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),imageLoader.lazyChildren(itemsContainer)})}function loadPlaylists(page,parentId){var options={SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Playlist",Recursive:!0,Fields:"PrimaryImageAspectRatio,SortName,CumulativeRunTimeTicks,CanDelete",StartIndex:0,Limit:itemsPerRow(),EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){var elem=page.querySelector("#playlists");result.Items.length?elem.classList.remove("hide"):elem.classList.add("hide");var itemsContainer=elem.querySelector(".itemsContainer"),supportsImageAnalysis=appHost.supports("imageanalysis");itemsContainer.innerHTML=cardBuilder.getCardsHtml({items:result.Items,shape:getSquareShape(),showTitle:!0,lazy:!0,coverImage:!0,showItemCounts:!0,centerText:!supportsImageAnalysis,overlayPlayButton:!supportsImageAnalysis,allowBottomPadding:!enableScrollX(),cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),imageLoader.lazyChildren(itemsContainer)})}function loadSuggestionsTab(page,tabContent,parentId){console.log("loadSuggestionsTab"),loadLatest(tabContent,parentId),loadPlaylists(tabContent,parentId),loadRecentlyPlayed(tabContent,parentId),loadFrequentlyPlayed(tabContent,parentId),require(["components/favoriteitems"],function(favoriteItems){favoriteItems.render(tabContent,Dashboard.getCurrentUserId(),parentId,["favoriteArtists","favoriteAlbums","favoriteSongs"])})}return function(view,params){function reload(){Dashboard.showLoadingMsg();var tabContent=view.querySelector(".pageTabContent[data-index='0']");loadSuggestionsTab(view,tabContent,params.topParentId)}function enableScrollX(){return browserInfo.mobile}function getTabController(page,index,callback){var depends=[];switch(index){case 0:break;case 1:depends.push("scripts/musicalbums");break;case 2:depends.push("scripts/musicartists");break;case 3:depends.push("scripts/musicartists");break;case 4:depends.push("scripts/songs");break;case 5:depends.push("scripts/musicgenres");break;case 6:depends.push("scripts/musicfolders")}require(depends,function(controllerFactory){var tabContent;0==index&&(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),self.tabContent=tabContent);var controller=tabControllers[index];controller||(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),controller=index?new controllerFactory(view,params,tabContent):self,2==index?controller.mode="albumartists":3==index&&(controller.mode="artists"),tabControllers[index]=controller,controller.initTab&&controller.initTab()),callback(controller)})}function preLoadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&controller.preRender&&controller.preRender()})}function loadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&(renderedTabs.push(index),controller.renderTab())})}var self=this;self.initTab=function(){for(var tabContent=view.querySelector(".pageTabContent[data-index='0']"),containers=tabContent.querySelectorAll(".itemsContainer"),i=0,length=containers.length;i'; - currentHtml += '' + i.Name + ''; - currentHtml += ''; - - return currentHtml; - - }).join(''); - - folderHtml += '
'; - - page.querySelector('.folderGroupList').innerHTML = folderHtml; - } - - function renderLatestItems(page, user, result) { - - var folderHtml = ''; - - folderHtml += '
'; - var excludeViewTypes = ['playlists', 'livetv', 'boxsets', 'channels']; - var excludeItemTypes = ['Channel']; - - folderHtml += result.Items.map(function (i) { - - if (excludeViewTypes.indexOf(i.CollectionType || []) !== -1) { - return ''; - } - - // not implemented yet - if (excludeItemTypes.indexOf(i.Type) !== -1) { - return ''; - } - - var currentHtml = ''; - - var id = 'chkIncludeInLatest' + i.Id; - - var isChecked = user.Configuration.LatestItemsExcludes.indexOf(i.Id) == -1; - var checkedHtml = isChecked ? ' checked="checked"' : ''; - - currentHtml += ''; - - return currentHtml; - - }).join(''); - - folderHtml += '
'; - - page.querySelector('.latestItemsList').innerHTML = folderHtml; - } - - function renderViewOrder(page, user, result) { - - var html = ''; - - var index = 0; - - html += result.Items.map(function (view) { - - var currentHtml = ''; - - currentHtml += '
'; - - currentHtml += ''; - - currentHtml += '
'; - - currentHtml += '
'; - currentHtml += view.Name; - currentHtml += '
'; - - currentHtml += '
'; - - if (index > 0) { - - currentHtml += ''; - } - else if (result.Items.length > 1) { - - currentHtml += ''; - } - - - currentHtml += '
'; - - index++; - return currentHtml; - - }).join(''); - - page.querySelector('.viewOrderList').innerHTML = html; - } - - function loadForm(page, user, userSettings) { - - page.querySelector('.chkHidePlayedFromLatest').checked = user.Configuration.HidePlayedInLatest || false; - - page.querySelector('#selectHomeSection1').value = userSettings.get('homesection0') || ''; - page.querySelector('#selectHomeSection2').value = userSettings.get('homesection1') || ''; - page.querySelector('#selectHomeSection3').value = userSettings.get('homesection2') || ''; - page.querySelector('#selectHomeSection4').value = userSettings.get('homesection3') || ''; - - var promise1 = ApiClient.getUserViews({}, user.Id); - var promise2 = ApiClient.getJSON(ApiClient.getUrl("Users/" + user.Id + "/GroupingOptions")); - - Promise.all([promise1, promise2]).then(function (responses) { - - renderViews(page, user, responses[1]); - renderLatestItems(page, user, responses[0]); - renderViewOrder(page, user, responses[0]); - - Dashboard.hideLoadingMsg(); - }); - } - - function getCheckboxItems(selector, page, isChecked) { - - var inputs = page.querySelectorAll(selector); - var list = []; - - for (var i = 0, length = inputs.length; i < length; i++) { - - if (inputs[i].checked == isChecked) { - list.push(inputs[i]); - } - - } - - return list; - } - - function refreshGlobalUserSettings(userSettingsInstance) { - require(['userSettings'], function (userSettings) { - userSettings.importFrom(userSettingsInstance); - }); - } - - function saveUser(page, user, userSettingsInstance) { - - user.Configuration.HidePlayedInLatest = page.querySelector('.chkHidePlayedFromLatest').checked; - - user.Configuration.LatestItemsExcludes = getCheckboxItems(".chkIncludeInLatest", page, false).map(function (i) { - - return i.getAttribute('data-folderid'); - }); - - user.Configuration.GroupedFolders = getCheckboxItems(".chkGroupFolder", page, true).map(function (i) { - - return i.getAttribute('data-folderid'); - }); - - var viewItems = page.querySelectorAll('.viewItem'); - var orderedViews = []; - for (var i = 0, length = viewItems.length; i < length; i++) { - orderedViews.push(viewItems[i].getAttribute('data-viewid')); - } - - user.Configuration.OrderedViews = orderedViews; - - userSettingsInstance.set('homesection0', page.querySelector('#selectHomeSection1').value); - userSettingsInstance.set('homesection1', page.querySelector('#selectHomeSection2').value); - userSettingsInstance.set('homesection2', page.querySelector('#selectHomeSection3').value); - userSettingsInstance.set('homesection3', page.querySelector('#selectHomeSection4').value); - - if (user.Id === Dashboard.getCurrentUserId()) { - refreshGlobalUserSettings(userSettingsInstance); - } - - return ApiClient.updateUserConfiguration(user.Id, user.Configuration); - } - - function save(page, userId, userSettings) { - - Dashboard.showLoadingMsg(); - - if (!AppInfo.enableAutoSave) { - Dashboard.showLoadingMsg(); - } - - ApiClient.getUser(userId).then(function (user) { - - saveUser(page, user, userSettings).then(function () { - - Dashboard.hideLoadingMsg(); - if (!AppInfo.enableAutoSave) { - require(['toast'], function (toast) { - toast(Globalize.translate('SettingsSaved')); - }); - } - - }, function () { - Dashboard.hideLoadingMsg(); - }); - }); - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - function getSibling(elem, type, className) { - - var sibling = elem[type]; - - while (sibling != null) { - if (sibling.classList.contains(className)) { - break; - } - } - - if (sibling != null) { - if (!sibling.classList.contains(className)) { - sibling = null; - } - } - - return sibling; - } - - return function (view, params) { - - var userId = params.userId || Dashboard.getCurrentUserId(); - var userSettings = new userSettingsBuilder(); - var userSettingsLoaded; - - function onSubmit(e) { - - userSettings.setUserInfo(userId, ApiClient).then(function () { - - save(view, userId, userSettings); - }); - - // Disable default form submission - if (e) { - e.preventDefault(); - } - return false; - } - - view.querySelector('.viewOrderList').addEventListener('click', function (e) { - - var target = parentWithClass(e.target, 'btnViewItemMove'); - - var li = parentWithClass(target, 'viewItem'); - var ul = parentWithClass(li, 'paperList'); - - if (target.classList.contains('btnViewItemDown')) { - - var next = li.nextSibling; - - li.parentNode.removeChild(li); - next.parentNode.insertBefore(li, next.nextSibling); - - } else { - - var prev = li.previousSibling; - - li.parentNode.removeChild(li); - prev.parentNode.insertBefore(li, prev); - } - - var viewItems = ul.querySelectorAll('.viewItem'); - for (var i = 0, length = viewItems.length; i < length; i++) { - var viewItem = viewItems[i]; - - var btn = viewItem.querySelector('.btnViewItemMove'); - - var prevViewItem = getSibling(viewItem, 'previousSibling', 'viewItem'); - - if (prevViewItem) { - - btn.classList.add('btnViewItemUp'); - btn.classList.remove('btnViewItemDown'); - btn.icon = 'keyboard-arrow-up'; - } else { - - btn.classList.remove('btnViewItemUp'); - btn.classList.add('btnViewItemDown'); - btn.icon = 'keyboard-arrow-down'; - } - } - }); - - view.querySelector('.homeScreenPreferencesForm').addEventListener('submit', onSubmit); - - if (AppInfo.enableAutoSave) { - view.querySelector('.btnSave').classList.add('hide'); - } else { - view.querySelector('.btnSave').classList.remove('hide'); - } - - view.addEventListener('viewshow', function () { - var page = this; - - Dashboard.showLoadingMsg(); - - var userId = params.userId || Dashboard.getCurrentUserId(); - - ApiClient.getUser(userId).then(function (user) { - - userSettings.setUserInfo(userId, ApiClient).then(function () { - - userSettingsLoaded = true; - - loadForm(page, user, userSettings); - }); - }); - }); - - view.addEventListener('viewbeforehide', function () { - if (AppInfo.enableAutoSave) { - onSubmit(); - } - }); - }; -}); \ No newline at end of file +define(["userSettingsBuilder","listViewStyle"],function(userSettingsBuilder){"use strict";function renderViews(page,user,result){var folderHtml="";folderHtml+='
',folderHtml+=result.map(function(i){var currentHtml="",id="chkGroupFolder"+i.Id,isChecked=user.Configuration.GroupedFolders.indexOf(i.Id)!=-1,checkedHtml=isChecked?' checked="checked"':"";return currentHtml+=""}).join(""),folderHtml+="
",page.querySelector(".folderGroupList").innerHTML=folderHtml}function renderLatestItems(page,user,result){var folderHtml="";folderHtml+='
';var excludeViewTypes=["playlists","livetv","boxsets","channels"],excludeItemTypes=["Channel"];folderHtml+=result.Items.map(function(i){if(excludeViewTypes.indexOf(i.CollectionType||[])!==-1)return"";if(excludeItemTypes.indexOf(i.Type)!==-1)return"";var currentHtml="",id="chkIncludeInLatest"+i.Id,isChecked=user.Configuration.LatestItemsExcludes.indexOf(i.Id)==-1,checkedHtml=isChecked?' checked="checked"':"";return currentHtml+=""}).join(""),folderHtml+="
",page.querySelector(".latestItemsList").innerHTML=folderHtml}function renderViewOrder(page,user,result){var html="",index=0;html+=result.Items.map(function(view){var currentHtml="";return currentHtml+='
',currentHtml+='',currentHtml+='
',currentHtml+="
",currentHtml+=view.Name,currentHtml+="
",currentHtml+="
",index>0?currentHtml+='':result.Items.length>1&&(currentHtml+=''),currentHtml+="
",index++,currentHtml}).join(""),page.querySelector(".viewOrderList").innerHTML=html}function loadForm(page,user,userSettings){page.querySelector(".chkHidePlayedFromLatest").checked=user.Configuration.HidePlayedInLatest||!1,page.querySelector("#selectHomeSection1").value=userSettings.get("homesection0")||"",page.querySelector("#selectHomeSection2").value=userSettings.get("homesection1")||"",page.querySelector("#selectHomeSection3").value=userSettings.get("homesection2")||"",page.querySelector("#selectHomeSection4").value=userSettings.get("homesection3")||"";var promise1=ApiClient.getUserViews({},user.Id),promise2=ApiClient.getJSON(ApiClient.getUrl("Users/"+user.Id+"/GroupingOptions"));Promise.all([promise1,promise2]).then(function(responses){renderViews(page,user,responses[1]),renderLatestItems(page,user,responses[0]),renderViewOrder(page,user,responses[0]),Dashboard.hideLoadingMsg()})}function getCheckboxItems(selector,page,isChecked){for(var inputs=page.querySelectorAll(selector),list=[],i=0,length=inputs.length;i" + culture.DisplayName + ""; - } - - select.innerHTML = html; - } - - return function (view, params) { - - var userId = params.userId || Dashboard.getCurrentUserId(); - var userSettingsInstance = new userSettingsBuilder(); - var userSettingsLoaded; - - function loadForm(page, user, loggedInUser, allCulturesPromise) { - - userSettingsInstance.setUserInfo(userId, ApiClient).then(function () { - userSettingsLoaded = true; - allCulturesPromise.then(function (allCultures) { - - populateLanguages(page.querySelector('#selectAudioLanguage'), allCultures); - populateLanguages(page.querySelector('#selectSubtitleLanguage'), allCultures); - - page.querySelector('#selectAudioLanguage', page).value = user.Configuration.AudioLanguagePreference || ""; - page.querySelector('#selectSubtitleLanguage', page).value = user.Configuration.SubtitleLanguagePreference || ""; - page.querySelector('.chkEpisodeAutoPlay').checked = user.Configuration.EnableNextEpisodeAutoPlay || false; - }); - - page.querySelector('#selectSubtitlePlaybackMode').value = user.Configuration.SubtitleMode || ""; - - page.querySelector('.chkPlayDefaultAudioTrack').checked = user.Configuration.PlayDefaultAudioTrack || false; - page.querySelector('.chkEnableCinemaMode').checked = userSettingsInstance.enableCinemaMode(); - page.querySelector('.chkExternalVideoPlayer').checked = appSettings.enableExternalPlayers(); - - require(['qualityoptions'], function (qualityoptions) { - - var bitrateOptions = qualityoptions.getVideoQualityOptions(appSettings.maxStreamingBitrate()).map(function (i) { - - return ''; - - }).join(''); - - bitrateOptions = '' + bitrateOptions; - - page.querySelector('#selectMaxBitrate').innerHTML = bitrateOptions; - page.querySelector('#selectMaxChromecastBitrate').innerHTML = bitrateOptions; - - if (appSettings.enableAutomaticBitrateDetection()) { - page.querySelector('#selectMaxBitrate').value = ''; - } else { - page.querySelector('#selectMaxBitrate').value = appSettings.maxStreamingBitrate(); - } - - page.querySelector('#selectMaxChromecastBitrate').value = appSettings.maxChromecastBitrate() || ''; - - Dashboard.hideLoadingMsg(); - }); - }); - } - - function loadPage(page) { - - Dashboard.showLoadingMsg(); - - var promise1 = ApiClient.getUser(userId); - - var promise2 = Dashboard.getCurrentUser(); - - var allCulturesPromise = ApiClient.getCultures(); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadForm(page, responses[1], responses[0], allCulturesPromise); - - }); - - ApiClient.getNamedConfiguration("cinemamode").then(function (cinemaConfig) { - - if (cinemaConfig.EnableIntrosForMovies || cinemaConfig.EnableIntrosForEpisodes) { - page.querySelector('.cinemaModeOptions').classList.remove('hide'); - } else { - page.querySelector('.cinemaModeOptions').classList.add('hide'); - } - }); - } - - function refreshGlobalUserSettings() { - require(['userSettings'], function (userSettings) { - userSettings.importFrom(userSettingsInstance); - }); - } - - function saveUser(page, user) { - - user.Configuration.AudioLanguagePreference = page.querySelector('#selectAudioLanguage').value; - user.Configuration.SubtitleLanguagePreference = page.querySelector('#selectSubtitleLanguage').value; - - user.Configuration.SubtitleMode = page.querySelector('#selectSubtitlePlaybackMode').value; - user.Configuration.PlayDefaultAudioTrack = page.querySelector('.chkPlayDefaultAudioTrack').checked; - user.Configuration.EnableNextEpisodeAutoPlay = page.querySelector('.chkEpisodeAutoPlay').checked; - if (userSettingsLoaded) { - userSettingsInstance.enableCinemaMode(page.querySelector('.chkEnableCinemaMode').checked); - - if (userId === Dashboard.getCurrentUserId()) { - refreshGlobalUserSettings(); - } - } - - return ApiClient.updateUserConfiguration(user.Id, user.Configuration); - } - - function save(page) { - - appSettings.enableExternalPlayers(page.querySelector('.chkExternalVideoPlayer').checked); - - if (page.querySelector('#selectMaxBitrate').value) { - appSettings.maxStreamingBitrate(page.querySelector('#selectMaxBitrate').value); - appSettings.enableAutomaticBitrateDetection(false); - } else { - appSettings.enableAutomaticBitrateDetection(true); - } - - appSettings.maxChromecastBitrate(page.querySelector('#selectMaxChromecastBitrate').value); - - if (!AppInfo.enableAutoSave) { - Dashboard.showLoadingMsg(); - } - - ApiClient.getUser(userId).then(function (result) { - - saveUser(page, result).then(function () { - - Dashboard.hideLoadingMsg(); - if (!AppInfo.enableAutoSave) { - require(['toast'], function (toast) { - toast(Globalize.translate('SettingsSaved')); - }); - } - - }, function () { - Dashboard.hideLoadingMsg(); - }); - - }); - } - - view.querySelector('#selectSubtitlePlaybackMode').addEventListener('change', function () { - - var subtitlesHelp = view.querySelectorAll('.subtitlesHelp'); - for (var i = 0, length = subtitlesHelp.length; i < length; i++) { - subtitlesHelp[i].classList.add('hide'); - } - view.querySelector('.subtitles' + this.value + 'Help').classList.remove('hide'); - }); - - view.querySelector('.languagePreferencesForm').addEventListener('submit', function (e) { - save(view); - - // Disable default form submission - e.preventDefault(); - return false; - }); - - if (AppInfo.enableAutoSave) { - view.querySelector('.btnSave').classList.add('hide'); - } else { - view.querySelector('.btnSave').classList.remove('hide'); - } - - view.addEventListener('viewshow', function () { - - if (AppInfo.supportsExternalPlayers) { - view.querySelector('.fldExternalPlayer').classList.remove('hide'); - } else { - view.querySelector('.fldExternalPlayer').classList.add('hide'); - } - - loadPage(view); - }); - - view.addEventListener('viewbeforehide', function () { - var page = this; - - if (AppInfo.enableAutoSave) { - save(page); - } - }); - }; - -}); \ No newline at end of file +define(["appSettings","userSettingsBuilder"],function(appSettings,userSettingsBuilder){"use strict";function populateLanguages(select,languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html}return function(view,params){function loadForm(page,user,loggedInUser,allCulturesPromise){userSettingsInstance.setUserInfo(userId,ApiClient).then(function(){userSettingsLoaded=!0,allCulturesPromise.then(function(allCultures){populateLanguages(page.querySelector("#selectAudioLanguage"),allCultures),populateLanguages(page.querySelector("#selectSubtitleLanguage"),allCultures),page.querySelector("#selectAudioLanguage",page).value=user.Configuration.AudioLanguagePreference||"",page.querySelector("#selectSubtitleLanguage",page).value=user.Configuration.SubtitleLanguagePreference||"",page.querySelector(".chkEpisodeAutoPlay").checked=user.Configuration.EnableNextEpisodeAutoPlay||!1}),page.querySelector("#selectSubtitlePlaybackMode").value=user.Configuration.SubtitleMode||"",page.querySelector(".chkPlayDefaultAudioTrack").checked=user.Configuration.PlayDefaultAudioTrack||!1,page.querySelector(".chkEnableCinemaMode").checked=userSettingsInstance.enableCinemaMode(),page.querySelector(".chkExternalVideoPlayer").checked=appSettings.enableExternalPlayers(),require(["qualityoptions"],function(qualityoptions){var bitrateOptions=qualityoptions.getVideoQualityOptions(appSettings.maxStreamingBitrate()).map(function(i){return'"}).join("");bitrateOptions='"+bitrateOptions,page.querySelector("#selectMaxBitrate").innerHTML=bitrateOptions,page.querySelector("#selectMaxChromecastBitrate").innerHTML=bitrateOptions,appSettings.enableAutomaticBitrateDetection()?page.querySelector("#selectMaxBitrate").value="":page.querySelector("#selectMaxBitrate").value=appSettings.maxStreamingBitrate(),page.querySelector("#selectMaxChromecastBitrate").value=appSettings.maxChromecastBitrate()||"",Dashboard.hideLoadingMsg()})})}function loadPage(page){Dashboard.showLoadingMsg();var promise1=ApiClient.getUser(userId),promise2=Dashboard.getCurrentUser(),allCulturesPromise=ApiClient.getCultures();Promise.all([promise1,promise2]).then(function(responses){loadForm(page,responses[1],responses[0],allCulturesPromise)}),ApiClient.getNamedConfiguration("cinemamode").then(function(cinemaConfig){cinemaConfig.EnableIntrosForMovies||cinemaConfig.EnableIntrosForEpisodes?page.querySelector(".cinemaModeOptions").classList.remove("hide"):page.querySelector(".cinemaModeOptions").classList.add("hide")})}function refreshGlobalUserSettings(){require(["userSettings"],function(userSettings){userSettings.importFrom(userSettingsInstance)})}function saveUser(page,user){return user.Configuration.AudioLanguagePreference=page.querySelector("#selectAudioLanguage").value,user.Configuration.SubtitleLanguagePreference=page.querySelector("#selectSubtitleLanguage").value,user.Configuration.SubtitleMode=page.querySelector("#selectSubtitlePlaybackMode").value,user.Configuration.PlayDefaultAudioTrack=page.querySelector(".chkPlayDefaultAudioTrack").checked,user.Configuration.EnableNextEpisodeAutoPlay=page.querySelector(".chkEpisodeAutoPlay").checked,userSettingsLoaded&&(userSettingsInstance.enableCinemaMode(page.querySelector(".chkEnableCinemaMode").checked),userId===Dashboard.getCurrentUserId()&&refreshGlobalUserSettings()),ApiClient.updateUserConfiguration(user.Id,user.Configuration)}function save(page){appSettings.enableExternalPlayers(page.querySelector(".chkExternalVideoPlayer").checked),page.querySelector("#selectMaxBitrate").value?(appSettings.maxStreamingBitrate(page.querySelector("#selectMaxBitrate").value),appSettings.enableAutomaticBitrateDetection(!1)):appSettings.enableAutomaticBitrateDetection(!0),appSettings.maxChromecastBitrate(page.querySelector("#selectMaxChromecastBitrate").value),AppInfo.enableAutoSave||Dashboard.showLoadingMsg(),ApiClient.getUser(userId).then(function(result){saveUser(page,result).then(function(){Dashboard.hideLoadingMsg(),AppInfo.enableAutoSave||require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))})},function(){Dashboard.hideLoadingMsg()})})}var userSettingsLoaded,userId=params.userId||Dashboard.getCurrentUserId(),userSettingsInstance=new userSettingsBuilder;view.querySelector("#selectSubtitlePlaybackMode").addEventListener("change",function(){for(var subtitlesHelp=view.querySelectorAll(".subtitlesHelp"),i=0,length=subtitlesHelp.length;i"; - - var showImageEditing = false; - - if (user.ConnectLinkType == 'Guest') { - - page.querySelector('.connectMessage').classList.remove('hide'); - } - else if (user.PrimaryImageTag) { - - showImageEditing = true; - page.querySelector('.connectMessage').classList.add('hide'); - - } else { - showImageEditing = true; - page.querySelector('.connectMessage').classList.add('hide'); - } - - Dashboard.getCurrentUser().then(function (loggedInUser) { - - if (showImageEditing && AppInfo.supportsFileInput && (loggedInUser.Policy.IsAdministrator || user.Policy.EnableUserPreferenceAccess)) { - page.querySelector('.newImageForm').classList.remove('hide'); - page.querySelector('#btnDeleteImage').classList.remove('hide'); - } else { - page.querySelector('.newImageForm').classList.add('hide'); - page.querySelector('#btnDeleteImage').classList.add('hide'); - } - }); - - Dashboard.hideLoadingMsg(); - }); - - } - - function onFileReaderError(evt) { - - Dashboard.hideLoadingMsg(); - - switch (evt.target.error.code) { - case evt.target.error.NOT_FOUND_ERR: - require(['toast'], function (toast) { - toast(Globalize.translate('FileNotFound')); - }); - break; - case evt.target.error.NOT_READABLE_ERR: - require(['toast'], function (toast) { - toast(Globalize.translate('FileReadError')); - }); - break; - case evt.target.error.ABORT_ERR: - break; // noop - default: - { - require(['toast'], function (toast) { - toast(Globalize.translate('FileReadError')); - }); - break; - } - }; - } - - function onFileReaderAbort(evt) { - - Dashboard.hideLoadingMsg(); - require(['toast'], function (toast) { - toast(Globalize.translate('FileReadCancelled')); - }); - } - - function setFiles(page, files) { - - var file = files[0]; - - if (!file || !file.type.match('image.*')) { - page.querySelector('#userImageOutput').innerHTML = ''; - page.querySelector('#fldUpload').classList.add('hide'); - currentFile = null; - return; - } - - currentFile = file; - - var reader = new FileReader(); - - reader.onerror = onFileReaderError; - reader.onloadstart = function () { - page.querySelector('#fldUpload').classList.add('hide'); - }; - reader.onabort = onFileReaderAbort; - - // Closure to capture the file information. - reader.onload = function (e) { - - // Render thumbnail. - var html = [''].join(''); - - page.querySelector('#userImageOutput').innerHTML = html; - page.querySelector('#fldUpload').classList.remove('hide'); - }; - - // Read in the image file as a data URL. - reader.readAsDataURL(file); - } - - function onImageDragOver(e) { - - e.preventDefault(); - - e.originalEvent.dataTransfer.dropEffect = 'Copy'; - - return false; - } - - return function (view, params) { - - reloadUser(view); - - var userpasswordpage = new Userpasswordpage(view, params); - - var userImageDropZone = view.querySelector('#userImageDropZone'); - userImageDropZone.addEventListener('dragOver', onImageDragOver); - userImageDropZone.addEventListener('drop', function (e) { - - e.preventDefault(); - - setFiles(view, e.originalEvent.dataTransfer.files); - - return false; - }); - - view.querySelector('#btnDeleteImage').addEventListener('click', function () { - - require(['confirm'], function (confirm) { - - confirm(Globalize.translate('DeleteImageConfirmation'), Globalize.translate('DeleteImage')).then(function () { - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - ApiClient.deleteUserImage(userId, "primary").then(function () { - - Dashboard.hideLoadingMsg(); - - reloadUser(view); - }); - }); - }); - }); - - view.querySelector('.newImageForm').addEventListener('submit', function (e) { - - var file = currentFile; - - if (!file) { - return false; - } - - if (file.type != "image/png" && file.type != "image/jpeg" && file.type != "image/jpeg") { - return false; - } - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - ApiClient.uploadUserImage(userId, 'Primary', file).then(function () { - - Dashboard.hideLoadingMsg(); - - reloadUser(view); - }); - - e.preventDefault(); - return false; - }); - - view.querySelector('#uploadUserImage').addEventListener('change', function (e) { - setFiles(view, e.target.files); - }); - }; -}); \ No newline at end of file +define(["scripts/userpasswordpage"],function(Userpasswordpage){"use strict";function reloadUser(page){var userId=getParameterByName("userId");Dashboard.showLoadingMsg(),ApiClient.getUser(userId).then(function(user){page.querySelector(".username").innerHTML=user.Name;var uploadUserImage=page.querySelector("#uploadUserImage");uploadUserImage.value="",uploadUserImage.dispatchEvent(new CustomEvent("change",{})),LibraryMenu.setTitle(user.Name);var imageUrl,fldImage=page.querySelector("#fldImage");imageUrl=user.PrimaryImageTag?ApiClient.getUserImageUrl(user.Id,{height:200,tag:user.PrimaryImageTag,type:"Primary"}):"css/images/logindefault.png",fldImage.classList.remove("hide"),fldImage.innerHTML="";var showImageEditing=!1;"Guest"==user.ConnectLinkType?page.querySelector(".connectMessage").classList.remove("hide"):user.PrimaryImageTag?(showImageEditing=!0,page.querySelector(".connectMessage").classList.add("hide")):(showImageEditing=!0,page.querySelector(".connectMessage").classList.add("hide")),Dashboard.getCurrentUser().then(function(loggedInUser){showImageEditing&&AppInfo.supportsFileInput&&(loggedInUser.Policy.IsAdministrator||user.Policy.EnableUserPreferenceAccess)?(page.querySelector(".newImageForm").classList.remove("hide"),page.querySelector("#btnDeleteImage").classList.remove("hide")):(page.querySelector(".newImageForm").classList.add("hide"),page.querySelector("#btnDeleteImage").classList.add("hide"))}),Dashboard.hideLoadingMsg()})}function onFileReaderError(evt){switch(Dashboard.hideLoadingMsg(),evt.target.error.code){case evt.target.error.NOT_FOUND_ERR:require(["toast"],function(toast){toast(Globalize.translate("FileNotFound"))});break;case evt.target.error.NOT_READABLE_ERR:require(["toast"],function(toast){toast(Globalize.translate("FileReadError"))});break;case evt.target.error.ABORT_ERR:break;default:require(["toast"],function(toast){toast(Globalize.translate("FileReadError"))})}}function onFileReaderAbort(evt){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("FileReadCancelled"))})}function setFiles(page,files){var file=files[0];if(!file||!file.type.match("image.*"))return page.querySelector("#userImageOutput").innerHTML="",page.querySelector("#fldUpload").classList.add("hide"),void(currentFile=null);currentFile=file;var reader=new FileReader;reader.onerror=onFileReaderError,reader.onloadstart=function(){page.querySelector("#fldUpload").classList.add("hide")},reader.onabort=onFileReaderAbort,reader.onload=function(e){var html=[''].join("");page.querySelector("#userImageOutput").innerHTML=html,page.querySelector("#fldUpload").classList.remove("hide")},reader.readAsDataURL(file)}function onImageDragOver(e){return e.preventDefault(),e.originalEvent.dataTransfer.dropEffect="Copy",!1}var currentFile;return function(view,params){reloadUser(view);var userImageDropZone=(new Userpasswordpage(view,params),view.querySelector("#userImageDropZone"));userImageDropZone.addEventListener("dragOver",onImageDragOver),userImageDropZone.addEventListener("drop",function(e){return e.preventDefault(),setFiles(view,e.originalEvent.dataTransfer.files),!1}),view.querySelector("#btnDeleteImage").addEventListener("click",function(){require(["confirm"],function(confirm){confirm(Globalize.translate("DeleteImageConfirmation"),Globalize.translate("DeleteImage")).then(function(){Dashboard.showLoadingMsg();var userId=getParameterByName("userId");ApiClient.deleteUserImage(userId,"primary").then(function(){Dashboard.hideLoadingMsg(),reloadUser(view)})})})}),view.querySelector(".newImageForm").addEventListener("submit",function(e){var file=currentFile;if(!file)return!1;if("image/png"!=file.type&&"image/jpeg"!=file.type&&"image/jpeg"!=file.type)return!1;Dashboard.showLoadingMsg();var userId=getParameterByName("userId");return ApiClient.uploadUserImage(userId,"Primary",file).then(function(){Dashboard.hideLoadingMsg(),reloadUser(view)}),e.preventDefault(),!1}),view.querySelector("#uploadUserImage").addEventListener("change",function(e){setFiles(view,e.target.files)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/mysync.js b/dashboard-ui/scripts/mysync.js index 4d154d3dbf..e737bfff52 100644 --- a/dashboard-ui/scripts/mysync.js +++ b/dashboard-ui/scripts/mysync.js @@ -1,80 +1 @@ -define(['apphost', 'globalize', 'syncJobList', 'events', 'localsync', 'emby-button', 'paper-icon-button-light'], function (appHost, globalize, syncJobList, events, localSync) { - 'use strict'; - - return function (view, params) { - - var interval; - - function isLocalSyncManagement() { - return appHost.supports('sync') && params.mode == 'offline'; - } - - function refreshSyncStatus(page) { - - if (isLocalSyncManagement()) { - - var status = localSync.getSyncStatus(); - - if (status == "Active") { - page.querySelector('.btnSyncNow').classList.add('hide'); - } - else { - page.querySelector('.btnSyncNow').classList.remove('hide'); - } - } - } - - function syncNow(page) { - - localSync.sync(); - require(['toast'], function (toast) { - toast(Globalize.translate('MessageSyncStarted')); - }); - refreshSyncStatus(page); - } - - view.querySelector('.btnSyncNow').addEventListener('click', function () { - syncNow(view); - }); - - if (isLocalSyncManagement()) { - - view.querySelector('.localSyncStatus').classList.remove('hide'); - - } else { - view.querySelector('.localSyncStatus').classList.add('hide'); - } - - var mySyncJobList = new syncJobList({ - isLocalSync: params.mode === 'offline', - serverId: ApiClient.serverId(), - userId: params.mode === 'offline' ? null : ApiClient.getCurrentUserId(), - element: view.querySelector('.syncActivity'), - mode: params.mode - }); - - view.addEventListener('viewbeforeshow', function () { - - refreshSyncStatus(view); - - if (appHost.supports('sync')) { - interval = setInterval(function () { - refreshSyncStatus(view); - }, 5000); - } - }); - - view.addEventListener('viewbeforehide', function () { - - if (interval) { - clearInterval(interval); - interval = null; - } - }); - - view.addEventListener('viewdestroy', function () { - - mySyncJobList.destroy(); - }); - }; -}); \ No newline at end of file +define(["apphost","globalize","syncJobList","events","localsync","emby-button","paper-icon-button-light"],function(appHost,globalize,syncJobList,events,localSync){"use strict";return function(view,params){function isLocalSyncManagement(){return appHost.supports("sync")&&"offline"==params.mode}function refreshSyncStatus(page){if(isLocalSyncManagement()){var status=localSync.getSyncStatus();"Active"==status?page.querySelector(".btnSyncNow").classList.add("hide"):page.querySelector(".btnSyncNow").classList.remove("hide")}}function syncNow(page){localSync.sync(),require(["toast"],function(toast){toast(Globalize.translate("MessageSyncStarted"))}),refreshSyncStatus(page)}var interval;view.querySelector(".btnSyncNow").addEventListener("click",function(){syncNow(view)}),isLocalSyncManagement()?view.querySelector(".localSyncStatus").classList.remove("hide"):view.querySelector(".localSyncStatus").classList.add("hide");var mySyncJobList=new syncJobList({isLocalSync:"offline"===params.mode,serverId:ApiClient.serverId(),userId:"offline"===params.mode?null:ApiClient.getCurrentUserId(),element:view.querySelector(".syncActivity"),mode:params.mode});view.addEventListener("viewbeforeshow",function(){refreshSyncStatus(view),appHost.supports("sync")&&(interval=setInterval(function(){refreshSyncStatus(view)},5e3))}),view.addEventListener("viewbeforehide",function(){interval&&(clearInterval(interval),interval=null)}),view.addEventListener("viewdestroy",function(){mySyncJobList.destroy()})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/mysyncsettings.js b/dashboard-ui/scripts/mysyncsettings.js index 161eef5cf5..e06eef8e76 100644 --- a/dashboard-ui/scripts/mysyncsettings.js +++ b/dashboard-ui/scripts/mysyncsettings.js @@ -1,66 +1 @@ -define(['appSettings', 'apphost', 'emby-checkbox', 'emby-select', 'emby-input'], function (appSettings, appHost) { - 'use strict'; - - function loadForm(page, user) { - - page.querySelector('#txtSyncPath').value = appSettings.syncPath() || ''; - page.querySelector('#chkWifi').checked = appSettings.syncOnlyOnWifi(); - page.querySelector('.selectAudioBitrate').value = appSettings.maxStaticMusicBitrate() || ''; - } - - function saveUser(page) { - - var syncPath = page.querySelector('#txtSyncPath').value; - - appSettings.syncPath(syncPath); - appSettings.syncOnlyOnWifi(page.querySelector('#chkWifi').checked); - appSettings.maxStaticMusicBitrate(page.querySelector('.selectAudioBitrate').value || null); - } - - return function (view, params) { - - view.querySelector('form').addEventListener('submit', function (e) { - - saveUser(view); - - // Disable default form submission - e.preventDefault(); - return false; - }); - - view.querySelector('#btnSelectSyncPath').addEventListener('click', function () { - - require(['nativedirectorychooser'], function () { - NativeDirectoryChooser.chooseDirectory().then(function (path) { - - if (path) { - view.querySelector('#txtSyncPath').value = path; - } - }); - }); - }); - - view.addEventListener('viewshow', function () { - var page = this; - - var userId = getParameterByName('userId') || Dashboard.getCurrentUserId(); - - ApiClient.getUser(userId).then(function (user) { - - loadForm(page, user); - }); - - if (appHost.supports('customsyncpath')) { - page.querySelector('.fldSyncPath').classList.remove('hide'); - } else { - page.querySelector('.fldSyncPath').classList.add('hide'); - } - }); - - view.addEventListener('viewbeforehide', function () { - - saveUser(this); - }); - }; - -}); \ No newline at end of file +define(["appSettings","apphost","emby-checkbox","emby-select","emby-input"],function(appSettings,appHost){"use strict";function loadForm(page,user){page.querySelector("#txtSyncPath").value=appSettings.syncPath()||"",page.querySelector("#chkWifi").checked=appSettings.syncOnlyOnWifi(),page.querySelector(".selectAudioBitrate").value=appSettings.maxStaticMusicBitrate()||""}function saveUser(page){var syncPath=page.querySelector("#txtSyncPath").value;appSettings.syncPath(syncPath),appSettings.syncOnlyOnWifi(page.querySelector("#chkWifi").checked),appSettings.maxStaticMusicBitrate(page.querySelector(".selectAudioBitrate").value||null)}return function(view,params){view.querySelector("form").addEventListener("submit",function(e){return saveUser(view),e.preventDefault(),!1}),view.querySelector("#btnSelectSyncPath").addEventListener("click",function(){require(["nativedirectorychooser"],function(){NativeDirectoryChooser.chooseDirectory().then(function(path){path&&(view.querySelector("#txtSyncPath").value=path)})})}),view.addEventListener("viewshow",function(){var page=this,userId=getParameterByName("userId")||Dashboard.getCurrentUserId();ApiClient.getUser(userId).then(function(user){loadForm(page,user)}),appHost.supports("customsyncpath")?page.querySelector(".fldSyncPath").classList.remove("hide"):page.querySelector(".fldSyncPath").classList.add("hide")}),view.addEventListener("viewbeforehide",function(){saveUser(this)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/notificationlist.js b/dashboard-ui/scripts/notificationlist.js index cf7c88b7d9..cfd90d44c3 100644 --- a/dashboard-ui/scripts/notificationlist.js +++ b/dashboard-ui/scripts/notificationlist.js @@ -1,39 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - $(document).on("pageshow", "#notificationsPage", function () { - - // If there is no user logged in there can be no notifications - if (!Dashboard.getCurrentUserId()) return; - - var elem = $(".notificationsList"); - var startIndex = 0; - var limit = 10; - - Notifications.showNotificationsList(startIndex, limit, elem); - - elem.on("click", ".btnPreviousPage", function (e) { - - e.preventDefault(); - - startIndex = startIndex - limit; - - if (startIndex < 0) startIndex = 0; - - Notifications.showNotificationsList(startIndex, limit, elem); - - }).on("click", ".btnNextPage", function (e) { - - e.preventDefault(); - - startIndex = startIndex + limit; - - Notifications.showNotificationsList(startIndex, limit, elem); - - }); - - Notifications.markNotificationsRead([]); - - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";$(document).on("pageshow","#notificationsPage",function(){if(Dashboard.getCurrentUserId()){var elem=$(".notificationsList"),startIndex=0,limit=10;Notifications.showNotificationsList(startIndex,limit,elem),elem.on("click",".btnPreviousPage",function(e){e.preventDefault(),startIndex-=limit,startIndex<0&&(startIndex=0),Notifications.showNotificationsList(startIndex,limit,elem)}).on("click",".btnNextPage",function(e){e.preventDefault(),startIndex+=limit,Notifications.showNotificationsList(startIndex,limit,elem)}),Notifications.markNotificationsRead([])}})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/notifications.js b/dashboard-ui/scripts/notifications.js index c316a0dd83..d82fb90c2a 100644 --- a/dashboard-ui/scripts/notifications.js +++ b/dashboard-ui/scripts/notifications.js @@ -1,216 +1 @@ -define(['libraryBrowser', 'listViewStyle'], function (libraryBrowser) { - 'use strict'; - - function notifications() { - - var self = this; - - self.getNotificationsSummaryPromise = null; - - self.total = 0; - - self.getNotificationsSummary = function () { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return; - } - - self.getNotificationsSummaryPromise = self.getNotificationsSummaryPromise || apiClient.getNotificationSummary(Dashboard.getCurrentUserId()); - - return self.getNotificationsSummaryPromise; - }; - - self.updateNotificationCount = function () { - - if (!Dashboard.getCurrentUserId()) { - return; - } - - if (!window.ApiClient) { - return; - } - - var promise = self.getNotificationsSummary(); - - if (!promise) { - return; - } - - promise.then(function (summary) { - - var btnNotificationsInner = document.querySelector('.btnNotificationsInner'); - if (btnNotificationsInner) { - - btnNotificationsInner.classList.remove('levelNormal'); - btnNotificationsInner.classList.remove('levelWarning'); - btnNotificationsInner.classList.remove('levelError'); - btnNotificationsInner.innerHTML = summary.UnreadCount; - - if (summary.UnreadCount) { - btnNotificationsInner.classList.add('level' + summary.MaxUnreadNotificationLevel); - } - } - }); - }; - - self.markNotificationsRead = function (ids, callback) { - - ApiClient.markNotificationsRead(Dashboard.getCurrentUserId(), ids, true).then(function () { - - self.getNotificationsSummaryPromise = null; - - self.updateNotificationCount(); - - if (callback) { - callback(); - } - - }); - - }; - - self.showNotificationsList = function (startIndex, limit, elem) { - - refreshNotifications(startIndex, limit, elem, true); - - }; - } - - function refreshNotifications(startIndex, limit, elem, showPaging) { - - var apiClient = window.ApiClient; - - if (apiClient) { - return apiClient.getNotifications(Dashboard.getCurrentUserId(), { StartIndex: startIndex, Limit: limit }).then(function (result) { - - listUnreadNotifications(result.Notifications, result.TotalRecordCount, startIndex, limit, elem, showPaging); - - }); - } - } - - function listUnreadNotifications(list, totalRecordCount, startIndex, limit, elem, showPaging) { - - if (!totalRecordCount) { - elem.html('

' + Globalize.translate('LabelNoUnreadNotifications') + '

'); - - return; - } - - Notifications.total = totalRecordCount; - - var html = ''; - - if (totalRecordCount > limit && showPaging === true) { - - var query = { StartIndex: startIndex, Limit: limit }; - - html += libraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: totalRecordCount, - showLimit: false, - updatePageSizeSetting: false - }); - } - - require(['humanedate'], function () { - for (var i = 0, length = list.length; i < length; i++) { - - var notification = list[i]; - - html += getNotificationHtml(notification); - - } - - elem.html(html).trigger('create'); - }); - } - - function getNotificationHtml(notification) { - - var itemHtml = ''; - - if (notification.Url) { - itemHtml += ''; - } - - itemHtml += '
'; - - if (notification.Level == "Error") { - itemHtml += 'error'; - } else { - itemHtml += 'dvr'; - } - - itemHtml += '
'; - - itemHtml += '

'; - itemHtml += notification.Name; - itemHtml += '

'; - - itemHtml += '
'; - itemHtml += humane_date(notification.Date); - itemHtml += '
'; - - if (notification.Description) { - itemHtml += '
'; - itemHtml += notification.Description; - itemHtml += '
'; - } - - itemHtml += '
'; - - itemHtml += '
'; - - if (notification.Url) { - itemHtml += '
'; - } - - return itemHtml; - } - - window.Notifications = new notifications(); - var needsRefresh = true; - - function onWebSocketMessage(e, msg) { - if (msg.MessageType === "NotificationUpdated" || msg.MessageType === "NotificationAdded" || msg.MessageType === "NotificationsMarkedRead") { - - Notifications.getNotificationsSummaryPromise = null; - - Notifications.updateNotificationCount(); - } - } - - function initializeApiClient(apiClient) { - Events.off(apiClient, "websocketmessage", onWebSocketMessage); - Events.on(apiClient, "websocketmessage", onWebSocketMessage); - } - - if (window.ApiClient) { - initializeApiClient(window.ApiClient); - } - - Events.on(ConnectionManager, 'apiclientcreated', function (e, apiClient) { - initializeApiClient(apiClient); - }); - - Events.on(ConnectionManager, 'localusersignedin', function () { - needsRefresh = true; - }); - - Events.on(ConnectionManager, 'localusersignedout', function () { - needsRefresh = true; - }); - - pageClassOn('pageshow', "type-interior", function () { - - if (needsRefresh) { - Notifications.updateNotificationCount(); - } - - }); - -}); \ No newline at end of file +define(["libraryBrowser","listViewStyle"],function(libraryBrowser){"use strict";function notifications(){var self=this;self.getNotificationsSummaryPromise=null,self.total=0,self.getNotificationsSummary=function(){var apiClient=window.ApiClient;if(apiClient)return self.getNotificationsSummaryPromise=self.getNotificationsSummaryPromise||apiClient.getNotificationSummary(Dashboard.getCurrentUserId()),self.getNotificationsSummaryPromise},self.updateNotificationCount=function(){if(Dashboard.getCurrentUserId()&&window.ApiClient){var promise=self.getNotificationsSummary();promise&&promise.then(function(summary){var btnNotificationsInner=document.querySelector(".btnNotificationsInner");btnNotificationsInner&&(btnNotificationsInner.classList.remove("levelNormal"),btnNotificationsInner.classList.remove("levelWarning"),btnNotificationsInner.classList.remove("levelError"),btnNotificationsInner.innerHTML=summary.UnreadCount,summary.UnreadCount&&btnNotificationsInner.classList.add("level"+summary.MaxUnreadNotificationLevel))})}},self.markNotificationsRead=function(ids,callback){ApiClient.markNotificationsRead(Dashboard.getCurrentUserId(),ids,!0).then(function(){self.getNotificationsSummaryPromise=null,self.updateNotificationCount(),callback&&callback()})},self.showNotificationsList=function(startIndex,limit,elem){refreshNotifications(startIndex,limit,elem,!0)}}function refreshNotifications(startIndex,limit,elem,showPaging){var apiClient=window.ApiClient;if(apiClient)return apiClient.getNotifications(Dashboard.getCurrentUserId(),{StartIndex:startIndex,Limit:limit}).then(function(result){listUnreadNotifications(result.Notifications,result.TotalRecordCount,startIndex,limit,elem,showPaging)})}function listUnreadNotifications(list,totalRecordCount,startIndex,limit,elem,showPaging){if(!totalRecordCount)return void elem.html('

'+Globalize.translate("LabelNoUnreadNotifications")+"

");Notifications.total=totalRecordCount;var html="";if(totalRecordCount>limit&&showPaging===!0){var query={StartIndex:startIndex,Limit:limit};html+=libraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:totalRecordCount,showLimit:!1,updatePageSizeSetting:!1})}require(["humanedate"],function(){for(var i=0,length=list.length;i'),itemHtml+='
',itemHtml+="Error"==notification.Level?'error':'dvr',itemHtml+='
',itemHtml+='

',itemHtml+=notification.Name,itemHtml+="

",itemHtml+='
',itemHtml+=humane_date(notification.Date),itemHtml+="
",notification.Description&&(itemHtml+='
',itemHtml+=notification.Description,itemHtml+="
"),itemHtml+="
",itemHtml+="
",notification.Url&&(itemHtml+=""),itemHtml}function onWebSocketMessage(e,msg){"NotificationUpdated"!==msg.MessageType&&"NotificationAdded"!==msg.MessageType&&"NotificationsMarkedRead"!==msg.MessageType||(Notifications.getNotificationsSummaryPromise=null,Notifications.updateNotificationCount())}function initializeApiClient(apiClient){Events.off(apiClient,"websocketmessage",onWebSocketMessage),Events.on(apiClient,"websocketmessage",onWebSocketMessage)}window.Notifications=new notifications;var needsRefresh=!0;window.ApiClient&&initializeApiClient(window.ApiClient),Events.on(ConnectionManager,"apiclientcreated",function(e,apiClient){initializeApiClient(apiClient)}),Events.on(ConnectionManager,"localusersignedin",function(){needsRefresh=!0}),Events.on(ConnectionManager,"localusersignedout",function(){needsRefresh=!0}),pageClassOn("pageshow","type-interior",function(){needsRefresh&&Notifications.updateNotificationCount()})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/notificationsetting.js b/dashboard-ui/scripts/notificationsetting.js index 0c49b3545f..8dbc8d5e87 100644 --- a/dashboard-ui/scripts/notificationsetting.js +++ b/dashboard-ui/scripts/notificationsetting.js @@ -1,193 +1 @@ -define(['jQuery', 'emby-checkbox', 'fnchecked'], function ($) { - 'use strict'; - - var notificationsConfigurationKey = "notifications"; - - function fillItems(elem, items, cssClass, idPrefix, currentList, isEnabledList) { - - var html = '
'; - - html += items.map(function (u) { - - var isChecked = isEnabledList ? currentList.indexOf(u.Id) != -1 : currentList.indexOf(u.Id) == -1; - - var checkedHtml = isChecked ? ' checked="checked"' : ''; - - return ''; - - }).join(''); - - html += '
'; - - elem.html(html).trigger('create'); - } - - function reload(page) { - - var type = getParameterByName('type'); - - var promise1 = ApiClient.getUsers(); - var promise2 = ApiClient.getNamedConfiguration(notificationsConfigurationKey); - var promise3 = ApiClient.getJSON(ApiClient.getUrl("Notifications/Types")); - var promise4 = ApiClient.getJSON(ApiClient.getUrl("Notifications/Services")); - - Promise.all([promise1, promise2, promise3, promise4]).then(function (responses) { - - var users = responses[0]; - var notificationOptions = responses[1]; - var types = responses[2]; - var services = responses[3]; - - var notificationConfig = notificationOptions.Options.filter(function (n) { - - return n.Type == type; - - })[0]; - - var typeInfo = types.filter(function (n) { - - return n.Type == type; - - })[0] || {}; - - if (typeInfo.IsBasedOnUserEvent) { - $('.monitorUsers', page).show(); - } else { - $('.monitorUsers', page).hide(); - } - - if (typeInfo.Variables.length) { - $('.tokenHelp', page).show(); - - $('.tokenList', page).html(typeInfo.Variables.map(function (v) { - - return '{' + v + '}'; - - }).join(', ')); - - } else { - $('.tokenHelp', page).hide(); - } - - $('.notificationType', page).html(typeInfo.Name || 'Unknown Notification'); - - if (!notificationConfig) { - - notificationConfig = { - DisabledMonitorUsers: [], - SendToUsers: [], - DisabledServices: [], - SendToUserMode: 'Admins' - }; - } - - fillItems($('.monitorUsersList', page), users, 'chkMonitor', 'chkMonitor', notificationConfig.DisabledMonitorUsers); - fillItems($('.sendToUsersList', page), users, 'chkSendTo', 'chkSendTo', notificationConfig.SendToUsers, true); - fillItems($('.servicesList', page), services, 'chkService', 'chkService', notificationConfig.DisabledServices); - - $('#chkEnabled', page).checked(notificationConfig.Enabled || false); - - $('#txtTitle', page).val(notificationConfig.Title || typeInfo.DefaultTitle); - - $('#selectUsers', page).val(notificationConfig.SendToUserMode).trigger('change'); - - }); - } - - function save(page) { - - var type = getParameterByName('type'); - - var promise1 = ApiClient.getNamedConfiguration(notificationsConfigurationKey); - var promise2 = ApiClient.getJSON(ApiClient.getUrl("Notifications/Types")); - - Promise.all([promise1, promise2]).then(function (responses) { - - var notificationOptions = responses[0]; - var types = responses[1]; - - var notificationConfig = notificationOptions.Options.filter(function (n) { - - return n.Type == type; - - })[0]; - - if (!notificationConfig) { - notificationConfig = { - Type: type - }; - notificationOptions.Options.push(notificationConfig); - } - - var typeInfo = types.filter(function (n) { - - return n.Type == type; - - })[0] || {}; - - notificationConfig.Enabled = $('#chkEnabled', page).checked(); - notificationConfig.Title = $('#txtTitle', page).val(); - notificationConfig.SendToUserMode = $('#selectUsers', page).val(); - - // Don't persist if it's just the default - if (notificationConfig.Title == typeInfo.DefaultTitle) { - notificationConfig.Title = null; - } - - notificationConfig.DisabledMonitorUsers = $('.chkMonitor', page).get().filter(function (c) { - return !c.checked; - }).map(function (c) { - return c.getAttribute('data-itemid'); - }); - - notificationConfig.SendToUsers = $('.chkSendTo', page).get().filter(function (c) { - return c.checked; - }).map(function (c) { - return c.getAttribute('data-itemid'); - }); - - notificationConfig.DisabledServices = $('.chkService', page).get().filter(function (c) { - return !c.checked; - }).map(function (c) { - return c.getAttribute('data-itemid'); - }); - - ApiClient.updateNamedConfiguration(notificationsConfigurationKey, notificationOptions).then(function (r) { - - Dashboard.processServerConfigurationUpdateResult(); - Dashboard.navigate('notificationsettings.html'); - }); - - }); - } - - function onSubmit() { - var page = $(this).parents('.page'); - save(page); - return false; - } - - $(document).on('pageinit', "#notificationSettingPage", function () { - - var page = this; - - $('#selectUsers', page).on('change', function () { - - if (this.value == 'Custom') { - $('.selectCustomUsers', page).show(); - } else { - $('.selectCustomUsers', page).hide(); - } - - }); - - $('.notificationSettingForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#notificationSettingPage", function () { - - var page = this; - - reload(page); - }); - -}); \ No newline at end of file +define(["jQuery","emby-checkbox","fnchecked"],function($){"use strict";function fillItems(elem,items,cssClass,idPrefix,currentList,isEnabledList){var html='
';html+=items.map(function(u){var isChecked=isEnabledList?currentList.indexOf(u.Id)!=-1:currentList.indexOf(u.Id)==-1,checkedHtml=isChecked?' checked="checked"':"";return'"}).join(""),html+="
",elem.html(html).trigger("create")}function reload(page){var type=getParameterByName("type"),promise1=ApiClient.getUsers(),promise2=ApiClient.getNamedConfiguration(notificationsConfigurationKey),promise3=ApiClient.getJSON(ApiClient.getUrl("Notifications/Types")),promise4=ApiClient.getJSON(ApiClient.getUrl("Notifications/Services"));Promise.all([promise1,promise2,promise3,promise4]).then(function(responses){var users=responses[0],notificationOptions=responses[1],types=responses[2],services=responses[3],notificationConfig=notificationOptions.Options.filter(function(n){return n.Type==type})[0],typeInfo=types.filter(function(n){return n.Type==type})[0]||{};typeInfo.IsBasedOnUserEvent?$(".monitorUsers",page).show():$(".monitorUsers",page).hide(),typeInfo.Variables.length?($(".tokenHelp",page).show(),$(".tokenList",page).html(typeInfo.Variables.map(function(v){return"{"+v+"}"}).join(", "))):$(".tokenHelp",page).hide(),$(".notificationType",page).html(typeInfo.Name||"Unknown Notification"),notificationConfig||(notificationConfig={DisabledMonitorUsers:[],SendToUsers:[],DisabledServices:[],SendToUserMode:"Admins"}),fillItems($(".monitorUsersList",page),users,"chkMonitor","chkMonitor",notificationConfig.DisabledMonitorUsers),fillItems($(".sendToUsersList",page),users,"chkSendTo","chkSendTo",notificationConfig.SendToUsers,!0),fillItems($(".servicesList",page),services,"chkService","chkService",notificationConfig.DisabledServices),$("#chkEnabled",page).checked(notificationConfig.Enabled||!1),$("#txtTitle",page).val(notificationConfig.Title||typeInfo.DefaultTitle),$("#selectUsers",page).val(notificationConfig.SendToUserMode).trigger("change")})}function save(page){var type=getParameterByName("type"),promise1=ApiClient.getNamedConfiguration(notificationsConfigurationKey),promise2=ApiClient.getJSON(ApiClient.getUrl("Notifications/Types"));Promise.all([promise1,promise2]).then(function(responses){var notificationOptions=responses[0],types=responses[1],notificationConfig=notificationOptions.Options.filter(function(n){return n.Type==type})[0];notificationConfig||(notificationConfig={Type:type},notificationOptions.Options.push(notificationConfig));var typeInfo=types.filter(function(n){return n.Type==type})[0]||{};notificationConfig.Enabled=$("#chkEnabled",page).checked(),notificationConfig.Title=$("#txtTitle",page).val(),notificationConfig.SendToUserMode=$("#selectUsers",page).val(),notificationConfig.Title==typeInfo.DefaultTitle&&(notificationConfig.Title=null),notificationConfig.DisabledMonitorUsers=$(".chkMonitor",page).get().filter(function(c){return!c.checked}).map(function(c){return c.getAttribute("data-itemid")}),notificationConfig.SendToUsers=$(".chkSendTo",page).get().filter(function(c){return c.checked}).map(function(c){return c.getAttribute("data-itemid")}),notificationConfig.DisabledServices=$(".chkService",page).get().filter(function(c){return!c.checked}).map(function(c){return c.getAttribute("data-itemid")}),ApiClient.updateNamedConfiguration(notificationsConfigurationKey,notificationOptions).then(function(r){Dashboard.processServerConfigurationUpdateResult(),Dashboard.navigate("notificationsettings.html")})})}function onSubmit(){var page=$(this).parents(".page");return save(page),!1}var notificationsConfigurationKey="notifications";$(document).on("pageinit","#notificationSettingPage",function(){var page=this;$("#selectUsers",page).on("change",function(){"Custom"==this.value?$(".selectCustomUsers",page).show():$(".selectCustomUsers",page).hide()}),$(".notificationSettingForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#notificationSettingPage",function(){var page=this;reload(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/notificationsettings.js b/dashboard-ui/scripts/notificationsettings.js index b5da527208..b3897bd360 100644 --- a/dashboard-ui/scripts/notificationsettings.js +++ b/dashboard-ui/scripts/notificationsettings.js @@ -1,87 +1 @@ -define(['jQuery', 'listViewStyle'], function ($) { - 'use strict'; - - function reload(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getJSON(ApiClient.getUrl("Notifications/Types")).then(function (list) { - - var html = ''; - - var lastCategory = ""; - - html += list.map(function (i) { - - var itemHtml = ''; - - if (i.Category != lastCategory) { - lastCategory = i.Category; - - if (lastCategory) { - itemHtml += '
'; - - } - itemHtml += '

'; - itemHtml += i.Category; - itemHtml += '

'; - - itemHtml += ''; - } - - $('.notificationList', page).html(html).trigger('create'); - - Dashboard.hideLoadingMsg(); - }); - } - - function getTabs() { - return [ - { - href: 'notificationsettings.html', - name: Globalize.translate('TabNotifications') - }, - { - href: 'appservices.html?context=notifications', - name: Globalize.translate('TabServices') - }]; - } - - return function (view, params) { - - view.addEventListener('viewshow', function () { - - LibraryMenu.setTabs('notifications', 0, getTabs); - - reload(view); - }); - }; -}); \ No newline at end of file +define(["jQuery","listViewStyle"],function($){"use strict";function reload(page){Dashboard.showLoadingMsg(),ApiClient.getJSON(ApiClient.getUrl("Notifications/Types")).then(function(list){var html="",lastCategory="";html+=list.map(function(i){var itemHtml="";return i.Category!=lastCategory&&(lastCategory=i.Category,lastCategory&&(itemHtml+="
"),itemHtml+="

",itemHtml+=i.Category,itemHtml+="

",itemHtml+='"),$(".notificationList",page).html(html).trigger("create"),Dashboard.hideLoadingMsg()})}function getTabs(){return[{href:"notificationsettings.html",name:Globalize.translate("TabNotifications")},{href:"appservices.html?context=notifications",name:Globalize.translate("TabServices")}]}return function(view,params){view.addEventListener("viewshow",function(){LibraryMenu.setTabs("notifications",0,getTabs),reload(view)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/nowplayingbar.js b/dashboard-ui/scripts/nowplayingbar.js index 0edbe2bf50..4c00f8c7a2 100644 --- a/dashboard-ui/scripts/nowplayingbar.js +++ b/dashboard-ui/scripts/nowplayingbar.js @@ -1,753 +1 @@ -define(['datetime', 'userdataButtons', 'itemHelper', 'events', 'browser', 'imageLoader', 'playbackManager', 'nowPlayingHelper', 'apphost', 'dom', 'connectionManager', 'paper-icon-button-light'], function (datetime, userdataButtons, itemHelper, events, browser, imageLoader, playbackManager, nowPlayingHelper, appHost, dom, connectionManager) { - 'use strict'; - - var currentPlayer; - var currentPlayerSupportedCommands = []; - - var currentTimeElement; - var nowPlayingImageElement; - var nowPlayingTextElement; - var nowPlayingUserData; - var muteButton; - var volumeSlider; - var volumeSliderContainer; - var playPauseButtons; - var positionSlider; - var toggleRepeatButton; - var toggleRepeatButtonIcon; - - var lastUpdateTime = 0; - var lastPlayerState = {}; - var isEnabled; - var currentRuntimeTicks = 0; - - function getNowPlayingBarHtml() { - - var html = ''; - - html += '
'; - - html += '
'; - html += '
'; - html += ''; - html += '
'; - - html += '
'; - html += '
'; - html += '
'; - html += '
'; - - // The onclicks are needed due to the return false above - html += '
'; - - html += ''; - - html += ''; - - html += ''; - html += ''; - - html += '
'; - html += '
'; - - html += '
'; - - html += ''; - - html += '
'; - html += ''; - html += '
'; - - html += ''; - - html += '
'; - html += '
'; - - html += ''; - html += ''; - - html += '
'; - html += '
'; - - html += '
'; - - return html; - } - - function onSlideDownComplete() { - this.classList.add('hide'); - } - - function slideDown(elem) { - - requestAnimationFrame(function () { - - // trigger reflow - void elem.offsetWidth; - - elem.classList.add('nowPlayingBar-hidden'); - - dom.addEventListener(elem, dom.whichTransitionEvent(), onSlideDownComplete, { - once: true - }); - }); - } - - function slideUp(elem) { - - elem.classList.remove('hide'); - - dom.removeEventListener(elem, dom.whichTransitionEvent(), onSlideDownComplete, { - once: true - }); - - requestAnimationFrame(function () { - - // trigger reflow - void elem.offsetWidth; - - elem.classList.remove('nowPlayingBar-hidden'); - }); - } - - function slideUpToFullScreen(elem) { - - if (!elem.classList.contains('hide')) { - return; - } - - elem.classList.remove('hide'); - - if (!browser.animate || browser.slow) { - return; - } - - requestAnimationFrame(function () { - - var keyframes = [ - { transform: 'none', offset: 0 }, - { transform: 'translateY(-100%)', offset: 1 }]; - var timing = { duration: 200, iterations: 1, fill: 'both', easing: 'ease-out' }; - elem.animate(keyframes, timing); - }); - } - - function onPlayPauseClick() { - playbackManager.playPause(currentPlayer); - } - - function bindEvents(elem) { - - currentTimeElement = elem.querySelector('.nowPlayingBarCurrentTime'); - nowPlayingImageElement = elem.querySelector('.nowPlayingImage'); - nowPlayingTextElement = elem.querySelector('.nowPlayingBarText'); - nowPlayingUserData = elem.querySelector('.nowPlayingBarUserDataButtons'); - - muteButton = elem.querySelector('.muteButton'); - muteButton.addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.toggleMute(currentPlayer); - } - - }); - - elem.querySelector('.stopButton').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.stop(currentPlayer); - } - }); - - var i, length; - playPauseButtons = elem.querySelectorAll('.playPauseButton'); - for (i = 0, length = playPauseButtons.length; i < length; i++) { - playPauseButtons[i].addEventListener('click', onPlayPauseClick); - } - - elem.querySelector('.nextTrackButton').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.nextTrack(currentPlayer); - } - }); - - elem.querySelector('.previousTrackButton').addEventListener('click', function () { - - if (currentPlayer) { - playbackManager.previousTrack(currentPlayer); - } - }); - - elem.querySelector('.remoteControlButton').addEventListener('click', function () { - - showRemoteControl(); - }); - - toggleRepeatButton = elem.querySelector('.toggleRepeatButton'); - toggleRepeatButton.addEventListener('click', function () { - - if (currentPlayer) { - - switch (playbackManager.getRepeatMode(currentPlayer)) { - case 'RepeatAll': - playbackManager.setRepeatMode('RepeatOne', currentPlayer); - break; - case 'RepeatOne': - playbackManager.setRepeatMode('RepeatNone', currentPlayer); - break; - default: - playbackManager.setRepeatMode('RepeatAll', currentPlayer); - break; - } - } - }); - - toggleRepeatButtonIcon = toggleRepeatButton.querySelector('i'); - - volumeSlider = elem.querySelector('.nowPlayingBarVolumeSlider'); - volumeSliderContainer = elem.querySelector('.nowPlayingBarVolumeSliderContainer'); - - if (appHost.supports('physicalvolumecontrol')) { - volumeSliderContainer.classList.add('hide'); - } else { - volumeSliderContainer.classList.remove('hide'); - } - - volumeSlider.addEventListener('change', function () { - - if (currentPlayer) { - currentPlayer.setVolume(this.value); - } - - }); - - positionSlider = elem.querySelector('.nowPlayingBarPositionSlider'); - positionSlider.addEventListener('change', function () { - - if (currentPlayer) { - - var newPercent = parseFloat(this.value); - - playbackManager.seekPercent(newPercent, currentPlayer); - } - - }); - - positionSlider.getBubbleText = function (value) { - - var state = lastPlayerState; - - if (!state || !state.NowPlayingItem || !currentRuntimeTicks) { - return '--:--'; - } - - var ticks = currentRuntimeTicks; - ticks /= 100; - ticks *= value; - - return datetime.getDisplayRunningTime(ticks); - }; - } - - function showRemoteControl(tabIndex) { - - if (tabIndex) { - Dashboard.navigate('nowplaying.html?tab=' + tabIndex); - } else { - Dashboard.navigate('nowplaying.html'); - } - } - - var nowPlayingBarElement; - function getNowPlayingBar() { - - if (nowPlayingBarElement) { - return Promise.resolve(nowPlayingBarElement); - } - - return new Promise(function (resolve, reject) { - - require(['appfooter-shared', 'itemShortcuts', 'css!css/nowplayingbar.css', 'emby-slider'], function (appfooter, itemShortcuts) { - - var parentContainer = appfooter.element; - nowPlayingBarElement = parentContainer.querySelector('.nowPlayingBar'); - - if (nowPlayingBarElement) { - resolve(nowPlayingBarElement); - return; - } - - parentContainer.insertAdjacentHTML('afterbegin', getNowPlayingBarHtml()); - nowPlayingBarElement = parentContainer.querySelector('.nowPlayingBar'); - - if (browser.safari && browser.slow) { - // Not handled well here. The wrong elements receive events, bar doesn't update quickly enough, etc. - nowPlayingBarElement.classList.add('noMediaProgress'); - } - - itemShortcuts.on(nowPlayingBarElement); - - bindEvents(nowPlayingBarElement); - resolve(nowPlayingBarElement); - }); - }); - } - - function showButton(button) { - button.classList.remove('hide'); - } - - function hideButton(button) { - button.classList.add('hide'); - } - - function updatePlayPauseState(isPaused) { - - var i, length; - - if (playPauseButtons) { - if (isPaused) { - - for (i = 0, length = playPauseButtons.length; i < length; i++) { - playPauseButtons[i].querySelector('i').innerHTML = 'play_arrow'; - } - - } else { - - for (i = 0, length = playPauseButtons.length; i < length; i++) { - playPauseButtons[i].querySelector('i').innerHTML = 'pause'; - } - } - } - } - - function updatePlayerStateInternal(event, state) { - - showNowPlayingBar(); - - lastPlayerState = state; - - var playerInfo = playbackManager.getPlayerInfo(); - - var playState = state.PlayState || {}; - - updatePlayPauseState(playState.IsPaused); - - var supportedCommands = playerInfo.supportedCommands; - currentPlayerSupportedCommands = supportedCommands; - - if (supportedCommands.indexOf('SetRepeatMode') == -1) { - toggleRepeatButton.classList.add('hide'); - } else { - toggleRepeatButton.classList.remove('hide'); - } - - updateRepeatModeDisplay(playState.RepeatMode); - - updatePlayerVolumeState(playState.IsMuted, playState.VolumeLevel); - - if (positionSlider && !positionSlider.dragging) { - positionSlider.disabled = !playState.CanSeek; - } - - var nowPlayingItem = state.NowPlayingItem || {}; - updateTimeDisplay(playState.PositionTicks, nowPlayingItem.RunTimeTicks); - - updateNowPlayingInfo(state); - } - - function updateRepeatModeDisplay(repeatMode) { - - if (repeatMode == 'RepeatAll') { - toggleRepeatButtonIcon.innerHTML = "repeat"; - toggleRepeatButton.classList.add('repeatActive'); - } - else if (repeatMode == 'RepeatOne') { - toggleRepeatButtonIcon.innerHTML = "repeat_one"; - toggleRepeatButton.classList.add('repeatActive'); - } else { - toggleRepeatButtonIcon.innerHTML = "repeat"; - toggleRepeatButton.classList.remove('repeatActive'); - } - } - - function updateTimeDisplay(positionTicks, runtimeTicks) { - - // See bindEvents for why this is necessary - if (positionSlider && !positionSlider.dragging) { - if (runtimeTicks) { - - var pct = positionTicks / runtimeTicks; - pct *= 100; - - positionSlider.value = pct; - - } else { - - positionSlider.value = 0; - } - } - - if (currentTimeElement) { - - var timeText = positionTicks == null ? '--:--' : datetime.getDisplayRunningTime(positionTicks); - - if (runtimeTicks) { - timeText += " / " + datetime.getDisplayRunningTime(runtimeTicks); - } - - currentTimeElement.innerHTML = timeText; - } - } - - function updatePlayerVolumeState(isMuted, volumeLevel) { - - var supportedCommands = currentPlayerSupportedCommands; - - var showMuteButton = true; - var showVolumeSlider = true; - - if (supportedCommands.indexOf('ToggleMute') == -1) { - showMuteButton = false; - } - - if (isMuted) { - muteButton.querySelector('i').innerHTML = ''; - } else { - muteButton.querySelector('i').innerHTML = ''; - } - - if (supportedCommands.indexOf('SetVolume') == -1) { - showVolumeSlider = false; - } - - if (currentPlayer.isLocalPlayer && appHost.supports('physicalvolumecontrol')) { - showMuteButton = false; - showVolumeSlider = false; - } - - if (showMuteButton) { - showButton(muteButton); - } else { - hideButton(muteButton); - } - - // See bindEvents for why this is necessary - if (volumeSlider) { - - if (showVolumeSlider) { - volumeSliderContainer.classList.remove('hide'); - } else { - volumeSliderContainer.classList.add('hide'); - } - - if (!volumeSlider.dragging) { - volumeSlider.value = volumeLevel || 0; - } - } - } - - function getTextActionButton(item, text) { - - if (!text) { - text = itemHelper.getDisplayName(item); - } - - var html = ''; - - return html; - } - - function seriesImageUrl(item, options) { - - if (!item) { - throw new Error('item cannot be null!'); - } - - if (item.Type !== 'Episode') { - return null; - } - - options = options || {}; - options.type = options.type || "Primary"; - - if (options.type === 'Primary') { - - if (item.SeriesPrimaryImageTag) { - - options.tag = item.SeriesPrimaryImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - } - - if (options.type === 'Thumb') { - - if (item.SeriesThumbImageTag) { - - options.tag = item.SeriesThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - if (item.ParentThumbImageTag) { - - options.tag = item.ParentThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId, options); - } - } - - return null; - } - - function imageUrl(item, options) { - - if (!item) { - throw new Error('item cannot be null!'); - } - - options = options || {}; - options.type = options.type || "Primary"; - - if (item.ImageTags && item.ImageTags[options.type]) { - - options.tag = item.ImageTags[options.type]; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId || item.Id, options); - } - - if (item.AlbumId && item.AlbumPrimaryImageTag) { - - options.tag = item.AlbumPrimaryImageTag; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId, options); - } - - return null; - } - - var currentImgUrl; - function updateNowPlayingInfo(state) { - - var nowPlayingItem = state.NowPlayingItem; - - nowPlayingTextElement.innerHTML = nowPlayingItem ? nowPlayingHelper.getNowPlayingNames(nowPlayingItem).map(function (nowPlayingName) { - - if (nowPlayingName.item) { - return '
' + getTextActionButton(nowPlayingName.item, nowPlayingName.text) + '
'; - } - - return '
' + nowPlayingName.text + '
'; - - }).join('') : ''; - - var imgHeight = 70; - - var url = nowPlayingItem ? (seriesImageUrl(nowPlayingItem, { - height: imgHeight - }) || imageUrl(nowPlayingItem, { - height: imgHeight - })) : null; - - if (url !== currentImgUrl) { - currentImgUrl = url; - - imageLoader.lazyImage(nowPlayingImageElement, url); - } - - if (nowPlayingItem.Id) { - ApiClient.getItem(Dashboard.getCurrentUserId(), nowPlayingItem.Id).then(function(item) { - userdataButtons.fill({ - item: item, - includePlayed: false, - element: nowPlayingUserData - }); - }); - } else { - userdataButtons.destroy({ - element: nowPlayingUserData - }); - } - } - - function onPlaybackStart(e, state) { - - console.log('nowplaying event: ' + e.type); - - var player = this; - - onStateChanged.call(player, e, state); - } - - function onRepeatModeChange(e) { - - var player = this; - - updateRepeatModeDisplay(playbackManager.getRepeatMode(player)); - } - - function showNowPlayingBar() { - - getNowPlayingBar().then(slideUp); - } - - function hideNowPlayingBar() { - - isEnabled = false; - - // Use a timeout to prevent the bar from hiding and showing quickly - // in the event of a stop->play command - - // Don't call getNowPlayingBar here because we don't want to end up creating it just to hide it - var elem = document.getElementsByClassName('nowPlayingBar')[0]; - if (elem) { - - // If it's not currently visible, don't bother with the animation - // transitionend events not firing in mobile chrome/safari when hidden - if (document.body.classList.contains('hiddenNowPlayingBar')) { - - dom.removeEventListener(elem, dom.whichTransitionEvent(), onSlideDownComplete, { - once: true - }); - elem.classList.add('hide'); - elem.classList.add('nowPlayingBar-hidden'); - - } else { - slideDown(elem); - } - } - } - - function onPlaybackStopped(e, stopInfo) { - - console.log('nowplaying event: ' + e.type); - var player = this; - - if (stopInfo.nextMediaType !== 'Audio') { - hideNowPlayingBar(); - } - } - - function onPlayPauseStateChanged(e) { - - if (!isEnabled) { - return; - } - - var player = this; - updatePlayPauseState(player.paused()); - } - - function onStateChanged(event, state) { - - //console.log('nowplaying event: ' + e.type); - var player = this; - - if (!state.NowPlayingItem) { - hideNowPlayingBar(); - return; - } - - if (player.isLocalPlayer && state.NowPlayingItem && state.NowPlayingItem.MediaType == 'Video') { - hideNowPlayingBar(); - return; - } - - isEnabled = true; - - if (nowPlayingBarElement) { - updatePlayerStateInternal(event, state); - return; - } - - getNowPlayingBar().then(function () { - updatePlayerStateInternal(event, state); - }); - } - - function onTimeUpdate(e) { - - if (!isEnabled) { - return; - } - - // Try to avoid hammering the document with changes - var now = new Date().getTime(); - if ((now - lastUpdateTime) < 700) { - - return; - } - lastUpdateTime = now; - - var player = this; - currentRuntimeTicks = playbackManager.duration(player); - updateTimeDisplay(playbackManager.currentTime(player), currentRuntimeTicks); - } - - function releaseCurrentPlayer() { - - var player = currentPlayer; - - if (player) { - events.off(player, 'playbackstart', onPlaybackStart); - events.off(player, 'statechange', onPlaybackStart); - events.off(player, 'repeatmodechange', onRepeatModeChange); - events.off(player, 'playbackstop', onPlaybackStopped); - events.off(player, 'volumechange', onVolumeChanged); - events.off(player, 'pause', onPlayPauseStateChanged); - events.off(player, 'playing', onPlayPauseStateChanged); - events.off(player, 'timeupdate', onTimeUpdate); - - currentPlayer = null; - hideNowPlayingBar(); - } - } - - function onVolumeChanged(e) { - - if (!isEnabled) { - return; - } - - var player = this; - - updatePlayerVolumeState(player.isMuted(), player.getVolume()); - } - - function bindToPlayer(player) { - - if (player === currentPlayer) { - return; - } - - releaseCurrentPlayer(); - - currentPlayer = player; - - if (!player) { - return; - } - - playbackManager.getPlayerState(player).then(function (state) { - - onStateChanged.call(player, { type: 'init' }, state); - }); - - events.on(player, 'playbackstart', onPlaybackStart); - events.on(player, 'statechange', onPlaybackStart); - events.on(player, 'repeatmodechange', onRepeatModeChange); - events.on(player, 'playbackstop', onPlaybackStopped); - events.on(player, 'volumechange', onVolumeChanged); - events.on(player, 'pause', onPlayPauseStateChanged); - events.on(player, 'playing', onPlayPauseStateChanged); - events.on(player, 'timeupdate', onTimeUpdate); - } - - events.on(playbackManager, 'playerchange', function () { - bindToPlayer(playbackManager.getCurrentPlayer()); - }); - - bindToPlayer(playbackManager.getCurrentPlayer()); - -}); \ No newline at end of file +define(["datetime","userdataButtons","itemHelper","events","browser","imageLoader","playbackManager","nowPlayingHelper","apphost","dom","connectionManager","paper-icon-button-light"],function(datetime,userdataButtons,itemHelper,events,browser,imageLoader,playbackManager,nowPlayingHelper,appHost,dom,connectionManager){"use strict";function getNowPlayingBarHtml(){var html="";return html+='
',html+='
',html+='
',html+='',html+="
",html+='
',html+='
',html+='
',html+="
",html+='
',html+='',html+='',html+='',html+='',html+='
',html+="
",html+='
',html+='',html+='
',html+='',html+="
",html+='',html+='
',html+="
",html+='',html+='',html+="
",html+="
",html+="
"}function onSlideDownComplete(){this.classList.add("hide")}function slideDown(elem){requestAnimationFrame(function(){void elem.offsetWidth,elem.classList.add("nowPlayingBar-hidden"),dom.addEventListener(elem,dom.whichTransitionEvent(),onSlideDownComplete,{once:!0})})}function slideUp(elem){elem.classList.remove("hide"),dom.removeEventListener(elem,dom.whichTransitionEvent(),onSlideDownComplete,{once:!0}),requestAnimationFrame(function(){void elem.offsetWidth,elem.classList.remove("nowPlayingBar-hidden")})}function onPlayPauseClick(){playbackManager.playPause(currentPlayer)}function bindEvents(elem){currentTimeElement=elem.querySelector(".nowPlayingBarCurrentTime"),nowPlayingImageElement=elem.querySelector(".nowPlayingImage"),nowPlayingTextElement=elem.querySelector(".nowPlayingBarText"),nowPlayingUserData=elem.querySelector(".nowPlayingBarUserDataButtons"),muteButton=elem.querySelector(".muteButton"),muteButton.addEventListener("click",function(){currentPlayer&&playbackManager.toggleMute(currentPlayer)}),elem.querySelector(".stopButton").addEventListener("click",function(){currentPlayer&&playbackManager.stop(currentPlayer)});var i,length;for(playPauseButtons=elem.querySelectorAll(".playPauseButton"),i=0,length=playPauseButtons.length;i';return html+=text,html+=""}function seriesImageUrl(item,options){if(!item)throw new Error("item cannot be null!");if("Episode"!==item.Type)return null;if(options=options||{},options.type=options.type||"Primary","Primary"===options.type&&item.SeriesPrimaryImageTag)return options.tag=item.SeriesPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if("Thumb"===options.type){if(item.SeriesThumbImageTag)return options.tag=item.SeriesThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if(item.ParentThumbImageTag)return options.tag=item.ParentThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId,options)}return null}function imageUrl(item,options){if(!item)throw new Error("item cannot be null!");return options=options||{},options.type=options.type||"Primary",item.ImageTags&&item.ImageTags[options.type]?(options.tag=item.ImageTags[options.type],connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId||item.Id,options)):item.AlbumId&&item.AlbumPrimaryImageTag?(options.tag=item.AlbumPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId,options)):null}function updateNowPlayingInfo(state){var nowPlayingItem=state.NowPlayingItem;nowPlayingTextElement.innerHTML=nowPlayingItem?nowPlayingHelper.getNowPlayingNames(nowPlayingItem).map(function(nowPlayingName){return nowPlayingName.item?"
"+getTextActionButton(nowPlayingName.item,nowPlayingName.text)+"
":"
"+nowPlayingName.text+"
"}).join(""):"";var imgHeight=70,url=nowPlayingItem?seriesImageUrl(nowPlayingItem,{height:imgHeight})||imageUrl(nowPlayingItem,{height:imgHeight}):null;url!==currentImgUrl&&(currentImgUrl=url,imageLoader.lazyImage(nowPlayingImageElement,url)),nowPlayingItem.Id?ApiClient.getItem(Dashboard.getCurrentUserId(),nowPlayingItem.Id).then(function(item){userdataButtons.fill({item:item,includePlayed:!1,element:nowPlayingUserData})}):userdataButtons.destroy({element:nowPlayingUserData})}function onPlaybackStart(e,state){console.log("nowplaying event: "+e.type);var player=this;onStateChanged.call(player,e,state)}function onRepeatModeChange(e){var player=this;updateRepeatModeDisplay(playbackManager.getRepeatMode(player))}function showNowPlayingBar(){getNowPlayingBar().then(slideUp)}function hideNowPlayingBar(){isEnabled=!1;var elem=document.getElementsByClassName("nowPlayingBar")[0];elem&&(document.body.classList.contains("hiddenNowPlayingBar")?(dom.removeEventListener(elem,dom.whichTransitionEvent(),onSlideDownComplete,{once:!0}),elem.classList.add("hide"),elem.classList.add("nowPlayingBar-hidden")):slideDown(elem))}function onPlaybackStopped(e,stopInfo){console.log("nowplaying event: "+e.type);"Audio"!==stopInfo.nextMediaType&&hideNowPlayingBar()}function onPlayPauseStateChanged(e){if(isEnabled){var player=this;updatePlayPauseState(player.paused())}}function onStateChanged(event,state){var player=this;return state.NowPlayingItem?player.isLocalPlayer&&state.NowPlayingItem&&"Video"==state.NowPlayingItem.MediaType?void hideNowPlayingBar():(isEnabled=!0,nowPlayingBarElement?void updatePlayerStateInternal(event,state):void getNowPlayingBar().then(function(){updatePlayerStateInternal(event,state)})):void hideNowPlayingBar()}function onTimeUpdate(e){if(isEnabled){var now=(new Date).getTime();if(!(now-lastUpdateTime<700)){lastUpdateTime=now;var player=this;currentRuntimeTicks=playbackManager.duration(player),updateTimeDisplay(playbackManager.currentTime(player),currentRuntimeTicks)}}}function releaseCurrentPlayer(){var player=currentPlayer;player&&(events.off(player,"playbackstart",onPlaybackStart),events.off(player,"statechange",onPlaybackStart),events.off(player,"repeatmodechange",onRepeatModeChange),events.off(player,"playbackstop",onPlaybackStopped),events.off(player,"volumechange",onVolumeChanged),events.off(player,"pause",onPlayPauseStateChanged),events.off(player,"playing",onPlayPauseStateChanged),events.off(player,"timeupdate",onTimeUpdate),currentPlayer=null,hideNowPlayingBar())}function onVolumeChanged(e){if(isEnabled){var player=this;updatePlayerVolumeState(player.isMuted(),player.getVolume())}}function bindToPlayer(player){player!==currentPlayer&&(releaseCurrentPlayer(),currentPlayer=player,player&&(playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}),events.on(player,"playbackstart",onPlaybackStart),events.on(player,"statechange",onPlaybackStart),events.on(player,"repeatmodechange",onRepeatModeChange),events.on(player,"playbackstop",onPlaybackStopped),events.on(player,"volumechange",onVolumeChanged),events.on(player,"pause",onPlayPauseStateChanged),events.on(player,"playing",onPlayPauseStateChanged),events.on(player,"timeupdate",onTimeUpdate)))}var currentPlayer,currentTimeElement,nowPlayingImageElement,nowPlayingTextElement,nowPlayingUserData,muteButton,volumeSlider,volumeSliderContainer,playPauseButtons,positionSlider,toggleRepeatButton,toggleRepeatButtonIcon,isEnabled,nowPlayingBarElement,currentImgUrl,currentPlayerSupportedCommands=[],lastUpdateTime=0,lastPlayerState={},currentRuntimeTicks=0;events.on(playbackManager,"playerchange",function(){bindToPlayer(playbackManager.getCurrentPlayer())}),bindToPlayer(playbackManager.getCurrentPlayer())}); \ No newline at end of file diff --git a/dashboard-ui/scripts/nowplayingpage.js b/dashboard-ui/scripts/nowplayingpage.js index 1ae2364f40..caea403b42 100644 --- a/dashboard-ui/scripts/nowplayingpage.js +++ b/dashboard-ui/scripts/nowplayingpage.js @@ -1,31 +1 @@ -define(['components/remotecontrol', 'emby-button'], function (remotecontrolFactory) { - 'use strict'; - - return function (view, params) { - - var self = this; - - var remoteControl = new remotecontrolFactory(); - remoteControl.init(view, view.querySelector('.remoteControlContent')); - - view.addEventListener('viewbeforeshow', function (e) { - document.body.classList.add('hiddenViewMenuBar'); - document.body.classList.add('hiddenNowPlayingBar'); - - if (remoteControl) { - remoteControl.onShow(); - } - }); - - view.addEventListener('viewbeforehide', function (e) { - - if (remoteControl) { - remoteControl.destroy(); - } - - document.body.classList.remove('hiddenViewMenuBar'); - document.body.classList.remove('hiddenNowPlayingBar'); - }); - }; - -}); \ No newline at end of file +define(["components/remotecontrol","emby-button"],function(remotecontrolFactory){"use strict";return function(view,params){var remoteControl=new remotecontrolFactory;remoteControl.init(view,view.querySelector(".remoteControlContent")),view.addEventListener("viewbeforeshow",function(e){document.body.classList.add("hiddenViewMenuBar"),document.body.classList.add("hiddenNowPlayingBar"),remoteControl&&remoteControl.onShow()}),view.addEventListener("viewbeforehide",function(e){remoteControl&&remoteControl.destroy(),document.body.classList.remove("hiddenViewMenuBar"),document.body.classList.remove("hiddenNowPlayingBar")})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/photos.js b/dashboard-ui/scripts/photos.js index 57f823ef17..f504f53f71 100644 --- a/dashboard-ui/scripts/photos.js +++ b/dashboard-ui/scripts/photos.js @@ -1,164 +1 @@ -define(['jQuery', 'cardBuilder', 'imageLoader', 'emby-itemscontainer'], function ($, cardBuilder, imageLoader) { - 'use strict'; - - var view = 'Poster'; - - var data = {}; - function getQuery() { - - var key = getSavedQueryKey(); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "IsFolder,SortName", - SortOrder: "Ascending", - Fields: "PrimaryImageAspectRatio,SortName", - ImageTypeLimit: 1, - EnableImageTypes: "Primary", - StartIndex: 0, - Limit: LibraryBrowser.getDefaultPageSize() - } - }; - - pageData.query.Recursive = false; - pageData.query.MediaTypes = null; - pageData.query.ParentId = getParameterByName('parentId') || LibraryMenu.getTopParentId(); - - LibraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData.query; - } - - function getSavedQueryKey() { - - return LibraryBrowser.getSavedQueryKey('v1'); - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(); - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - viewButton: false, - showLimit: false - }); - - page.querySelector('.listTopPaging').innerHTML = pagingHtml; - - if (view == "Poster") { - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "square", - context: getParameterByName('context') || 'photos', - overlayText: true, - lazy: true, - coverImage: true, - showTitle: false, - centerText: true - }); - } - - var elem = page.querySelector('.itemsContainer'); - elem.innerHTML = html + pagingHtml; - imageLoader.lazyChildren(elem); - - $('.btnNextPage', page).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page); - }); - - $('.btnPreviousPage', page).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page); - }); - - LibraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - function startSlideshow(page, itemQuery, startItemId) { - - var userId = Dashboard.getCurrentUserId(); - - var localQuery = $.extend({}, itemQuery); - localQuery.StartIndex = 0; - localQuery.Limit = null; - localQuery.MediaTypes = "Photo"; - localQuery.Recursive = true; - localQuery.Filters = "IsNotFolder"; - - ApiClient.getItems(userId, localQuery).then(function (result) { - - showSlideshow(page, result.Items, startItemId); - }); - } - - function showSlideshow(page, items, startItemId) { - - var index = items.map(function (i) { - return i.Id; - - }).indexOf(startItemId); - - if (index == -1) { - index = 0; - } - - require(['slideshow'], function (slideshow) { - - var newSlideShow = new slideshow({ - showTitle: false, - cover: false, - items: items, - startIndex: index, - interval: 7000, - interactive: true - }); - - newSlideShow.show(); - }); - } - - function onListItemClick(e) { - - var page = $(this).parents('.page')[0]; - var info = LibraryBrowser.getListItemInfo(this); - - if (info.mediaType == 'Photo') { - var query = getQuery(); - - Photos.startSlideshow(page, query, info.id); - return false; - } - } - - pageIdOn('pageinit', "photosPage", function () { - - var page = this; - - reloadItems(page, 0); - - $(page).on('click', '.mediaItem', onListItemClick); - - }); - - window.Photos = { - startSlideshow: startSlideshow - }; - -}); \ No newline at end of file +define(["jQuery","cardBuilder","imageLoader","emby-itemscontainer"],function($,cardBuilder,imageLoader){"use strict";function getQuery(){var key=getSavedQueryKey(),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"IsFolder,SortName",SortOrder:"Ascending",Fields:"PrimaryImageAspectRatio,SortName",ImageTypeLimit:1,EnableImageTypes:"Primary",StartIndex:0,Limit:LibraryBrowser.getDefaultPageSize()}},pageData.query.Recursive=!1,pageData.query.MediaTypes=null,pageData.query.ParentId=getParameterByName("parentId")||LibraryMenu.getTopParentId(),LibraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData.query}function getSavedQueryKey(){return LibraryBrowser.getSavedQueryKey("v1")}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery();ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){window.scrollTo(0,0);var html="",pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,viewButton:!1,showLimit:!1});page.querySelector(".listTopPaging").innerHTML=pagingHtml,"Poster"==view&&(html=cardBuilder.getCardsHtml({items:result.Items,shape:"square",context:getParameterByName("context")||"photos",overlayText:!0,lazy:!0,coverImage:!0,showTitle:!1,centerText:!0}));var elem=page.querySelector(".itemsContainer");elem.innerHTML=html+pagingHtml,imageLoader.lazyChildren(elem),$(".btnNextPage",page).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page)}),$(".btnPreviousPage",page).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page)}),LibraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}function startSlideshow(page,itemQuery,startItemId){var userId=Dashboard.getCurrentUserId(),localQuery=$.extend({},itemQuery);localQuery.StartIndex=0,localQuery.Limit=null,localQuery.MediaTypes="Photo",localQuery.Recursive=!0,localQuery.Filters="IsNotFolder",ApiClient.getItems(userId,localQuery).then(function(result){showSlideshow(page,result.Items,startItemId)})}function showSlideshow(page,items,startItemId){var index=items.map(function(i){return i.Id}).indexOf(startItemId);index==-1&&(index=0),require(["slideshow"],function(slideshow){var newSlideShow=new slideshow({showTitle:!1,cover:!1,items:items,startIndex:index,interval:7e3,interactive:!0});newSlideShow.show()})}function onListItemClick(e){var page=$(this).parents(".page")[0],info=LibraryBrowser.getListItemInfo(this);if("Photo"==info.mediaType){var query=getQuery();return Photos.startSlideshow(page,query,info.id),!1}}var view="Poster",data={};pageIdOn("pageinit","photosPage",function(){var page=this;reloadItems(page,0),$(page).on("click",".mediaItem",onListItemClick)}),window.Photos={startSlideshow:startSlideshow}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/playbackconfiguration.js b/dashboard-ui/scripts/playbackconfiguration.js index 3c0443b74d..d568442a28 100644 --- a/dashboard-ui/scripts/playbackconfiguration.js +++ b/dashboard-ui/scripts/playbackconfiguration.js @@ -1,66 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function loadPage(page, config) { - - $('#txtMinResumePct', page).val(config.MinResumePct); - $('#txtMaxResumePct', page).val(config.MaxResumePct); - $('#txtMinResumeDuration', page).val(config.MinResumeDurationSeconds); - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getServerConfiguration().then(function (config) { - - config.MinResumePct = $('#txtMinResumePct', form).val(); - config.MaxResumePct = $('#txtMaxResumePct', form).val(); - config.MinResumeDurationSeconds = $('#txtMinResumeDuration', form).val(); - - ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'cinemamodeconfiguration.html', - name: Globalize.translate('TabCinemaMode') - }, - { - href: 'playbackconfiguration.html', - name: Globalize.translate('TabResumeSettings') - }, - { - href: 'streamingsettings.html', - name: Globalize.translate('TabStreaming') - }]; - } - - $(document).on('pageinit', "#playbackConfigurationPage", function () { - - $('.playbackConfigurationForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#playbackConfigurationPage", function () { - - LibraryMenu.setTabs('playback', 1, getTabs); - Dashboard.showLoadingMsg(); - - var page = this; - - ApiClient.getServerConfiguration().then(function (config) { - - loadPage(page, config); - - }); - - }); - -}); +define(["jQuery"],function($){"use strict";function loadPage(page,config){$("#txtMinResumePct",page).val(config.MinResumePct),$("#txtMaxResumePct",page).val(config.MaxResumePct),$("#txtMinResumeDuration",page).val(config.MinResumeDurationSeconds),Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getServerConfiguration().then(function(config){config.MinResumePct=$("#txtMinResumePct",form).val(),config.MaxResumePct=$("#txtMaxResumePct",form).val(),config.MinResumeDurationSeconds=$("#txtMinResumeDuration",form).val(),ApiClient.updateServerConfiguration(config).then(Dashboard.processServerConfigurationUpdateResult)}),!1}function getTabs(){return[{href:"cinemamodeconfiguration.html",name:Globalize.translate("TabCinemaMode")},{href:"playbackconfiguration.html",name:Globalize.translate("TabResumeSettings")},{href:"streamingsettings.html",name:Globalize.translate("TabStreaming")}]}$(document).on("pageinit","#playbackConfigurationPage",function(){$(".playbackConfigurationForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#playbackConfigurationPage",function(){LibraryMenu.setTabs("playback",1,getTabs),Dashboard.showLoadingMsg();var page=this;ApiClient.getServerConfiguration().then(function(config){loadPage(page,config)})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/playlistedit.js b/dashboard-ui/scripts/playlistedit.js index 67524f392a..e9a721700c 100644 --- a/dashboard-ui/scripts/playlistedit.js +++ b/dashboard-ui/scripts/playlistedit.js @@ -1,117 +1 @@ -define(['jQuery', 'listView', 'imageLoader'], function ($, listView, imageLoader) { - 'use strict'; - - var data = {}; - function getPageData() { - var key = getSavedQueryKey(); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - Fields: "PrimaryImageAspectRatio", - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: 200 - }, - view: LibraryBrowser.getSavedView(key) || 'List' - }; - - pageData.query.ParentId = LibraryMenu.getTopParentId(); - LibraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery() { - - return getPageData().query; - } - - function getSavedQueryKey() { - - return LibraryBrowser.getSavedQueryKey(); - } - - function reloadItems(page, item) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(); - - query.UserId = Dashboard.getCurrentUserId(); - - ApiClient.getJSON(ApiClient.getUrl('Playlists/' + item.Id + '/Items', query)).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - - html += LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false - - }); - - html += listView.getListViewHtml({ - items: result.Items, - sortBy: query.SortBy, - showIndex: false, - showRemoveFromPlaylist: true, - playFromHere: true, - action: 'playallfromhere', - smallIcon: true, - dragHandle: true, - playlistId: item.Id - }); - - var elem = page.querySelector('#childrenContent .itemsContainer'); - elem.classList.add('vertical-list'); - elem.classList.remove('vertical-wrap'); - elem.innerHTML = html; - - imageLoader.lazyChildren(elem); - - $('.btnNextPage', elem).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page, item); - }); - - $('.btnPreviousPage', elem).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page, item); - }); - - Dashboard.hideLoadingMsg(); - }); - } - - function init(page, item) { - - var elem = page.querySelector('#childrenContent .itemsContainer'); - - elem.enableDragReordering(true); - - elem.addEventListener('needsrefresh', function () { - - reloadItems(page, item); - }); - } - - window.PlaylistViewer = { - render: function (page, item) { - - if (!page.playlistInit) { - page.playlistInit = true; - init(page, item); - } - - reloadItems(page, item); - } - }; - -}); \ No newline at end of file +define(["jQuery","listView","imageLoader"],function($,listView,imageLoader){"use strict";function getPageData(){var key=getSavedQueryKey(),pageData=data[key];return pageData||(pageData=data[key]={query:{Fields:"PrimaryImageAspectRatio",EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:200},view:LibraryBrowser.getSavedView(key)||"List"},pageData.query.ParentId=LibraryMenu.getTopParentId(),LibraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(){return getPageData().query}function getSavedQueryKey(){return LibraryBrowser.getSavedQueryKey()}function reloadItems(page,item){Dashboard.showLoadingMsg();var query=getQuery();query.UserId=Dashboard.getCurrentUserId(),ApiClient.getJSON(ApiClient.getUrl("Playlists/"+item.Id+"/Items",query)).then(function(result){window.scrollTo(0,0);var html="";html+=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1}),html+=listView.getListViewHtml({items:result.Items,sortBy:query.SortBy,showIndex:!1,showRemoveFromPlaylist:!0,playFromHere:!0,action:"playallfromhere",smallIcon:!0,dragHandle:!0,playlistId:item.Id});var elem=page.querySelector("#childrenContent .itemsContainer");elem.classList.add("vertical-list"),elem.classList.remove("vertical-wrap"),elem.innerHTML=html,imageLoader.lazyChildren(elem),$(".btnNextPage",elem).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page,item)}),$(".btnPreviousPage",elem).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page,item)}),Dashboard.hideLoadingMsg()})}function init(page,item){var elem=page.querySelector("#childrenContent .itemsContainer");elem.enableDragReordering(!0),elem.addEventListener("needsrefresh",function(){reloadItems(page,item)})}var data={};window.PlaylistViewer={render:function(page,item){page.playlistInit||(page.playlistInit=!0,init(page,item)),reloadItems(page,item)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/playlists.js b/dashboard-ui/scripts/playlists.js index e6452132a6..34430895fd 100644 --- a/dashboard-ui/scripts/playlists.js +++ b/dashboard-ui/scripts/playlists.js @@ -1,225 +1 @@ -define(['listView', 'cardBuilder', 'libraryBrowser', 'apphost', 'imageLoader', 'emby-itemscontainer'], function (listView, cardBuilder, libraryBrowser, appHost, imageLoader) { - 'use strict'; - - return function (view, params) { - - var data = {}; - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Playlist", - Recursive: true, - Fields: "PrimaryImageAspectRatio,SortName,CumulativeRunTimeTicks,CanDelete", - StartIndex: 0, - Limit: LibraryBrowser.getDefaultPageSize() - }, - view: LibraryBrowser.getSavedView(key) || appHost.preferVisualCards ? 'PosterCard' : 'Poster' - }; - - pageData.query.ParentId = LibraryMenu.getTopParentId(); - LibraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey(); - } - return context.savedQueryKey; - } - - function showLoadingMessage() { - - Dashboard.showLoadingMsg(); - } - - function hideLoadingMessage() { - Dashboard.hideLoadingMsg(); - } - - function onViewStyleChange() { - - var viewStyle = getPageData(view).view; - - var itemsContainer = view.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems() { - - showLoadingMessage(); - - var query = getQuery(view); - var promise1 = ApiClient.getItems(Dashboard.getCurrentUserId(), query); - var promise2 = Dashboard.getCurrentUser(); - - Promise.all([promise1, promise2]).then(function (responses) { - - var result = responses[0]; - var user = responses[1]; - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - var viewStyle = getPageData(view).view; - - view.querySelector('.listTopPaging').innerHTML = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - viewButton: false, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: true, - layouts: 'List,Poster,PosterCard,Thumb,ThumbCard', - currentLayout: viewStyle - - }); - - if (result.TotalRecordCount) { - - if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - sortBy: query.SortBy - }); - } - else if (viewStyle == "PosterCard") { - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "square", - showTitle: true, - lazy: true, - coverImage: true, - showItemCounts: true, - cardLayout: true, - vibrant: true - }); - } - else if (viewStyle == "Thumb") { - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - showTitle: true, - centerText: true, - lazy: true, - preferThumb: true, - overlayPlayButton: true - }); - } - else if (viewStyle == "ThumbCard") { - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - showTitle: true, - lazy: true, - preferThumb: true, - cardLayout: true, - showItemCounts: true, - vibrant: true - }); - } - else { - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "square", - showTitle: true, - lazy: true, - coverImage: true, - showItemCounts: true, - centerText: true, - overlayPlayButton: true - }); - } - - view.querySelector('.noItemsMessage').classList.add('hide'); - - } else { - - view.querySelector('.noItemsMessage').classList.remove('hide'); - } - - var elem = view.querySelector('.itemsContainer'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - var btnNextPage = view.querySelector('.btnNextPage'); - if (btnNextPage) { - btnNextPage.addEventListener('click', function () { - query.StartIndex += query.Limit; - reloadItems(); - }); - } - - var btnPreviousPage = view.querySelector('.btnPreviousPage'); - if (btnPreviousPage) { - btnPreviousPage.addEventListener('click', function () { - query.StartIndex -= query.Limit; - reloadItems(); - }); - } - - var btnChangeLayout = view.querySelector('.btnChangeLayout'); - if (btnChangeLayout) { - btnChangeLayout.addEventListener('layoutchange', function (e) { - var layout = e.detail.viewStyle; - getPageData(view).view = layout; - LibraryBrowser.saveViewSetting(getSavedQueryKey(view), layout); - onViewStyleChange(); - reloadItems(); - }); - } - - LibraryBrowser.saveQueryValues(getSavedQueryKey(view), query); - - hideLoadingMessage(); - }); - } - - view.addEventListener('viewbeforeshow', function() { - reloadItems(); - }); - - view.querySelector('.btnNewPlaylist').addEventListener('click', function () { - - require(['playlistEditor'], function (playlistEditor) { - - var serverId = ApiClient.serverInfo().Id; - new playlistEditor().show({ - items: [], - serverId: serverId - }); - }); - }); - - onViewStyleChange(); - - }; -}); \ No newline at end of file +define(["listView","cardBuilder","libraryBrowser","apphost","imageLoader","emby-itemscontainer"],function(listView,cardBuilder,libraryBrowser,appHost,imageLoader){"use strict";return function(view,params){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Playlist",Recursive:!0,Fields:"PrimaryImageAspectRatio,SortName,CumulativeRunTimeTicks,CanDelete",StartIndex:0,Limit:LibraryBrowser.getDefaultPageSize()},view:LibraryBrowser.getSavedView(key)||appHost.preferVisualCards?"PosterCard":"Poster"},pageData.query.ParentId=LibraryMenu.getTopParentId(),LibraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey()),context.savedQueryKey}function showLoadingMessage(){Dashboard.showLoadingMsg()}function hideLoadingMessage(){Dashboard.hideLoadingMsg()}function onViewStyleChange(){var viewStyle=getPageData(view).view,itemsContainer=view.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(){showLoadingMessage();var query=getQuery(view),promise1=ApiClient.getItems(Dashboard.getCurrentUserId(),query),promise2=Dashboard.getCurrentUser();Promise.all([promise1,promise2]).then(function(responses){var result=responses[0];responses[1];window.scrollTo(0,0);var html="",viewStyle=getPageData(view).view;view.querySelector(".listTopPaging").innerHTML=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,viewButton:!1,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!0,layouts:"List,Poster,PosterCard,Thumb,ThumbCard",currentLayout:viewStyle}),result.TotalRecordCount?(html="List"==viewStyle?listView.getListViewHtml({items:result.Items,sortBy:query.SortBy}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"square",showTitle:!0,lazy:!0,coverImage:!0,showItemCounts:!0,cardLayout:!0,vibrant:!0}):"Thumb"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,centerText:!0,lazy:!0,preferThumb:!0,overlayPlayButton:!0}):"ThumbCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",showTitle:!0,lazy:!0,preferThumb:!0,cardLayout:!0,showItemCounts:!0,vibrant:!0}):cardBuilder.getCardsHtml({items:result.Items,shape:"square",showTitle:!0,lazy:!0,coverImage:!0,showItemCounts:!0,centerText:!0,overlayPlayButton:!0}),view.querySelector(".noItemsMessage").classList.add("hide")):view.querySelector(".noItemsMessage").classList.remove("hide");var elem=view.querySelector(".itemsContainer");elem.innerHTML=html,imageLoader.lazyChildren(elem);var btnNextPage=view.querySelector(".btnNextPage");btnNextPage&&btnNextPage.addEventListener("click",function(){query.StartIndex+=query.Limit,reloadItems()});var btnPreviousPage=view.querySelector(".btnPreviousPage");btnPreviousPage&&btnPreviousPage.addEventListener("click",function(){query.StartIndex-=query.Limit,reloadItems()});var btnChangeLayout=view.querySelector(".btnChangeLayout");btnChangeLayout&&btnChangeLayout.addEventListener("layoutchange",function(e){var layout=e.detail.viewStyle;getPageData(view).view=layout,LibraryBrowser.saveViewSetting(getSavedQueryKey(view),layout),onViewStyleChange(),reloadItems()}),LibraryBrowser.saveQueryValues(getSavedQueryKey(view),query),hideLoadingMessage()})}var data={};view.addEventListener("viewbeforeshow",function(){reloadItems()}),view.querySelector(".btnNewPlaylist").addEventListener("click",function(){require(["playlistEditor"],function(playlistEditor){var serverId=ApiClient.serverInfo().Id;(new playlistEditor).show({items:[],serverId:serverId})})}),onViewStyleChange()}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/plugincatalogpage.js b/dashboard-ui/scripts/plugincatalogpage.js index ee9360290b..56775490e7 100644 --- a/dashboard-ui/scripts/plugincatalogpage.js +++ b/dashboard-ui/scripts/plugincatalogpage.js @@ -1,307 +1 @@ -define(['jQuery', 'cardStyle'], function ($) { - 'use strict'; - - // The base query options - var query = { - TargetSystems: 'Server', - IsAdult: false - }; - - function reloadList(page) { - - Dashboard.showLoadingMsg(); - - if (AppInfo.enableAppStorePolicy) { - $('.optionAdultContainer', page).hide(); - } else { - $('.optionAdultContainer', page).show(); - } - - query.IsAppStoreSafe = true; - - var promise1 = ApiClient.getAvailablePlugins(query); - - var promise2 = ApiClient.getInstalledPlugins(); - - Promise.all([promise1, promise2]).then(function (responses) { - - populateList({ - - catalogElement: $('#pluginTiles', page), - noItemsElement: $("#noPlugins", page), - availablePlugins: responses[0], - installedPlugins: responses[1] - - }); - }); - } - function populateList(options) { - populateListInternal(options); - } - - function populateListInternal(options) { - - var availablePlugins = options.availablePlugins; - var installedPlugins = options.installedPlugins; - - var allPlugins = availablePlugins.filter(function (p) { - - p.category = p.category || "General"; - p.categoryDisplayName = Globalize.translate('PluginCategory' + p.category.replace(' ', '')); - - if (options.categories) { - if (options.categories.indexOf(p.category) == -1) { - return false; - } - } - - if (options.targetSystem) { - if (p.targetSystem != options.targetSystem) { - return false; - } - } - - return p.type == "UserInstalled"; - - }); - - availablePlugins = allPlugins.sort(function (a, b) { - - var aName = (a.category); - var bName = (b.category); - - if (aName > bName) { - return 1; - } - if (bName > aName) { - return -1; - } - - aName = (a.name); - bName = (b.name); - - if (aName > bName) { - return 1; - } - if (bName > aName) { - return -1; - } - - return 0; - }); - - var html = ''; - var i, length, plugin; - - var currentCategory; - - if (!options.categories) { - currentCategory = Globalize.translate('HeaderTopPlugins'); - html += '

' + currentCategory + '

'; - var topPlugins = allPlugins.slice(0).sort(function (a, b) { - - if (a.installs > b.installs) { - return -1; - } - if (b.installs > a.installs) { - return 1; - } - - var aName = (a.name); - var bName = (b.name); - - if (aName > bName) { - return 1; - } - if (bName > aName) { - return -1; - } - - return 0; - }); - - html += '
'; - var limit = screen.availWidth >= 1920 ? 15 : 12; - for (i = 0, length = Math.min(topPlugins.length, limit) ; i < length; i++) { - html += getPluginHtml(topPlugins[i], options, installedPlugins); - } - html += '
'; - html += '
'; - html += '
'; - } - - var hasOpenTag = false; - currentCategory = null; - - if (options.showCategory === false) { - html += '
'; - hasOpenTag = true; - } - - for (i = 0, length = availablePlugins.length; i < length; i++) { - - plugin = availablePlugins[i]; - - var category = plugin.categoryDisplayName; - - if (category != currentCategory) { - - if (options.showCategory !== false) { - if (currentCategory) { - hasOpenTag = false; - html += '
'; - html += '
'; - html += '
'; - } - - html += '

' + category + '

'; - html += '
'; - hasOpenTag = true; - } - - currentCategory = category; - } - - html += getPluginHtml(plugin, options, installedPlugins); - - } - - if (hasOpenTag) { - html += '
'; - } - - if (!availablePlugins.length && options.noItemsElement) { - $(options.noItemsElement).hide(); - } - - $(options.catalogElement).html(html); - - Dashboard.hideLoadingMsg(); - } - - function getPluginHtml(plugin, options, installedPlugins) { - - var html = ''; - - var href = plugin.externalUrl ? plugin.externalUrl : "addplugin.html?name=" + encodeURIComponent(plugin.name) + "&guid=" + plugin.guid; - if (options.context) { - href += "&context=" + options.context; - } - var target = plugin.externalUrl ? ' target="_blank"' : ''; - - html += "
"; - - html += '
'; - html += '
'; - - html += '
'; - - html += ''; - if (plugin.thumbImage) { - html += '"; - - html += '
'; - - html += "
"; - html += plugin.name; - html += "
"; - - // html += "
"; - - // if (plugin.avgRating) { - // html += 'star'; - // html += plugin.avgRating.toFixed(1); - // } - - // if (plugin.totalRatings) { - // html += "
"; - // html += " " + Globalize.translate('LabelNumberReviews').replace("{0}", plugin.totalRatings); - // } - // html += "
"; - - // html += "
"; - - var installedPlugin = plugin.isApp ? null : installedPlugins.filter(function (ip) { - return ip.Id == plugin.guid; - })[0]; - - html += "
"; - - if (installedPlugin) { - html += Globalize.translate('LabelVersionInstalled').replace("{0}", installedPlugin.Version); - } else { - html += ' '; - } - html += "
"; - - // cardFooter - html += "
"; - - // cardBox - html += "
"; - - // card - html += "
"; - - return html; - } - - function getTabs() { - return [ - { - href: 'plugins.html', - name: Globalize.translate('TabMyPlugins') - }, - { - href: 'plugincatalog.html', - name: Globalize.translate('TabCatalog') - }]; - } - - $(document).on('pageinit', "#pluginCatalogPage", function () { - - var page = this; - - $('#selectSystem', page).on('change', function () { - - query.TargetSystems = this.value; - reloadList(page); - }); - - $('#chkAdult', page).on('change', function () { - - query.IsAdult = this.checked ? null : false; - reloadList(page); - }); - - }).on('pageshow', "#pluginCatalogPage", function () { - - LibraryMenu.setTabs('plugins', 1, getTabs); - var page = this; - - reloadList(page); - }); - - window.PluginCatalog = { - renderCatalog: populateList - }; - -}); \ No newline at end of file +define(["jQuery","cardStyle"],function($){"use strict";function reloadList(page){Dashboard.showLoadingMsg(),AppInfo.enableAppStorePolicy?$(".optionAdultContainer",page).hide():$(".optionAdultContainer",page).show(),query.IsAppStoreSafe=!0;var promise1=ApiClient.getAvailablePlugins(query),promise2=ApiClient.getInstalledPlugins();Promise.all([promise1,promise2]).then(function(responses){populateList({catalogElement:$("#pluginTiles",page),noItemsElement:$("#noPlugins",page),availablePlugins:responses[0],installedPlugins:responses[1]})})}function populateList(options){populateListInternal(options)}function populateListInternal(options){var availablePlugins=options.availablePlugins,installedPlugins=options.installedPlugins,allPlugins=availablePlugins.filter(function(p){return p.category=p.category||"General",p.categoryDisplayName=Globalize.translate("PluginCategory"+p.category.replace(" ","")),(!options.categories||options.categories.indexOf(p.category)!=-1)&&((!options.targetSystem||p.targetSystem==options.targetSystem)&&"UserInstalled"==p.type)});availablePlugins=allPlugins.sort(function(a,b){var aName=a.category,bName=b.category;return aName>bName?1:bName>aName?-1:(aName=a.name,bName=b.name,aName>bName?1:bName>aName?-1:0)});var i,length,plugin,currentCategory,html="";if(!options.categories){currentCategory=Globalize.translate("HeaderTopPlugins"),html+='

'+currentCategory+"

";var topPlugins=allPlugins.slice(0).sort(function(a,b){if(a.installs>b.installs)return-1;if(b.installs>a.installs)return 1;var aName=a.name,bName=b.name;return aName>bName?1:bName>aName?-1:0});html+='
';var limit=screen.availWidth>=1920?15:12;for(i=0,length=Math.min(topPlugins.length,limit);i",html+="
",html+="
"}var hasOpenTag=!1;for(currentCategory=null,options.showCategory===!1&&(html+='
',hasOpenTag=!0),i=0,length=availablePlugins.length;i",html+="
",html+="
"),html+='

'+category+"

",html+='
',hasOpenTag=!0),currentCategory=category),html+=getPluginHtml(plugin,options,installedPlugins)}hasOpenTag&&(html+="
"),!availablePlugins.length&&options.noItemsElement&&$(options.noItemsElement).hide(),$(options.catalogElement).html(html),Dashboard.hideLoadingMsg()}function getPluginHtml(plugin,options,installedPlugins){var html="",href=plugin.externalUrl?plugin.externalUrl:"addplugin.html?name="+encodeURIComponent(plugin.name)+"&guid="+plugin.guid;options.context&&(href+="&context="+options.context);var target=plugin.externalUrl?' target="_blank"':"";html+="
",html+='
',html+='
',html+='
',html+='",html+=plugin.thumbImage?'",html+='
',html+="
",html+=plugin.name,html+="
";var installedPlugin=plugin.isApp?null:installedPlugins.filter(function(ip){return ip.Id==plugin.guid})[0];return html+="
",html+=installedPlugin?Globalize.translate("LabelVersionInstalled").replace("{0}",installedPlugin.Version):" ",html+="
",html+="
",html+="
",html+="
"}function getTabs(){return[{href:"plugins.html",name:Globalize.translate("TabMyPlugins")},{href:"plugincatalog.html",name:Globalize.translate("TabCatalog")}]}var query={TargetSystems:"Server",IsAdult:!1};$(document).on("pageinit","#pluginCatalogPage",function(){var page=this;$("#selectSystem",page).on("change",function(){query.TargetSystems=this.value,reloadList(page)}),$("#chkAdult",page).on("change",function(){query.IsAdult=!!this.checked&&null,reloadList(page)})}).on("pageshow","#pluginCatalogPage",function(){LibraryMenu.setTabs("plugins",1,getTabs);var page=this;reloadList(page)}),window.PluginCatalog={renderCatalog:populateList}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/pluginspage.js b/dashboard-ui/scripts/pluginspage.js index 55b54601aa..028ed56013 100644 --- a/dashboard-ui/scripts/pluginspage.js +++ b/dashboard-ui/scripts/pluginspage.js @@ -1,250 +1 @@ -define(['jQuery', 'cardStyle'], function ($) { - 'use strict'; - - function deletePlugin(page, uniqueid, name) { - - var msg = Globalize.translate('UninstallPluginConfirmation').replace("{0}", name); - - require(['confirm'], function (confirm) { - confirm(msg, Globalize.translate('UninstallPluginHeader')).then(function () { - Dashboard.showLoadingMsg(); - - ApiClient.uninstallPlugin(uniqueid).then(function () { - - reloadList(page); - }); - }); - }); - } - - function showNoConfigurationMessage() { - Dashboard.alert({ - message: Globalize.translate('NoPluginConfigurationMessage') - }); - } - - function showConnectMessage() { - Dashboard.alert({ - message: Globalize.translate('MessagePluginConfigurationRequiresLocalAccess') - }); - } - - function getPluginCardHtml(plugin, pluginConfigurationPages) { - - var configPage = $.grep(pluginConfigurationPages, function (pluginConfigurationPage) { - return pluginConfigurationPage.PluginId == plugin.Id; - })[0]; - - var html = ''; - - var isConnectMode = Dashboard.isConnectMode(); - var configPageUrl = configPage ? Dashboard.getConfigurationPageUrl(configPage.Name) : null; - - var href = configPage && !isConnectMode ? - configPageUrl : - null; - - html += "
"; - - html += '
'; - html += '
'; - - html += '
'; - - if (href) { - html += ''; - } - else if (!configPageUrl) { - html += '
'; - } - else if (isConnectMode) { - html += '
'; - } - else { - html += '"; - - html += '
'; - - html += '
'; - html += ''; - html += "
"; - - html += "
"; - html += plugin.Name; - html += "
"; - - html += "
"; - html += plugin.Version; - html += "
"; - - // cardFooter - html += "
"; - - // cardBox - html += "
"; - - // card - html += "
"; - - return html; - } - - function renderPlugins(page, plugins, showNoPluginsMessage) { - - ApiClient.getJSON(ApiClient.getUrl("web/configurationpages") + "?pageType=PluginConfiguration").then(function (configPages) { - - populateList(page, plugins, configPages, showNoPluginsMessage); - - }); - } - - function populateList(page, plugins, pluginConfigurationPages, showNoPluginsMessage) { - - plugins = plugins.sort(function (plugin1, plugin2) { - - return (plugin1.Name) > (plugin2.Name) ? 1 : -1; - - }); - - var html = plugins.map(function (p) { - return getPluginCardHtml(p, pluginConfigurationPages); - - }).join(''); - - if (!plugins.length) { - - if (showNoPluginsMessage) { - html += '
'; - - if (AppInfo.enableAppStorePolicy) { - html += '

' + Globalize.translate('MessageNoPluginsDueToAppStore') + '

'; - } else { - html += '

' + Globalize.translate('MessageNoPluginsInstalled') + '

'; - - html += '

'; - html += Globalize.translate('BrowsePluginCatalogMessage'); - html += '

'; - } - html += '
'; - } - - $('.installedPlugins', page).html(html); - } else { - - var elem = $('.installedPlugins', page).addClass('itemsContainer').addClass('vertical-wrap').html(html); - - $('.noConfigPluginCard', elem).on('click', function () { - showNoConfigurationMessage(); - }); - - $('.connectModePluginCard', elem).on('click', function () { - showConnectMessage(); - }); - - $('.btnCardMenu', elem).on('click', function () { - showPluginMenu(page, this); - }); - } - - Dashboard.hideLoadingMsg(); - } - - function showPluginMenu(page, elem) { - - var card = $(elem).parents('.card'); - var id = card.attr('data-id'); - var name = card.attr('data-name'); - var configHref = $('.cardContent', card).attr('href'); - - var menuItems = []; - - if (configHref) { - menuItems.push({ - name: Globalize.translate('ButtonSettings'), - id: 'open', - ironIcon: 'mode-edit' - }); - } - - menuItems.push({ - name: Globalize.translate('ButtonUninstall'), - id: 'delete', - ironIcon: 'delete' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: elem, - callback: function (resultId) { - - switch (resultId) { - - case 'open': - Dashboard.navigate(configHref); - break; - case 'delete': - deletePlugin(page, id, name); - break; - default: - break; - } - } - }); - - }); - } - - function reloadList(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getInstalledPlugins().then(function (plugins) { - - renderPlugins(page, plugins, true); - }); - } - - function getTabs() { - return [ - { - href: 'plugins.html', - name: Globalize.translate('TabMyPlugins') - }, - { - href: 'plugincatalog.html', - name: Globalize.translate('TabCatalog') - }]; - } - - $(document).on('pageshow', "#pluginsPage", function () { - - LibraryMenu.setTabs('plugins', 0, getTabs); - reloadList(this); - }); - - window.PluginsPage = { - renderPlugins: renderPlugins - }; - -}); \ No newline at end of file +define(["jQuery","cardStyle"],function($){"use strict";function deletePlugin(page,uniqueid,name){var msg=Globalize.translate("UninstallPluginConfirmation").replace("{0}",name);require(["confirm"],function(confirm){confirm(msg,Globalize.translate("UninstallPluginHeader")).then(function(){Dashboard.showLoadingMsg(),ApiClient.uninstallPlugin(uniqueid).then(function(){reloadList(page)})})})}function showNoConfigurationMessage(){Dashboard.alert({message:Globalize.translate("NoPluginConfigurationMessage")})}function showConnectMessage(){Dashboard.alert({message:Globalize.translate("MessagePluginConfigurationRequiresLocalAccess")})}function getPluginCardHtml(plugin,pluginConfigurationPages){var configPage=$.grep(pluginConfigurationPages,function(pluginConfigurationPage){return pluginConfigurationPage.PluginId==plugin.Id})[0],html="",isConnectMode=Dashboard.isConnectMode(),configPageUrl=configPage?Dashboard.getConfigurationPageUrl(configPage.Name):null,href=configPage&&!isConnectMode?configPageUrl:null;return html+="
",html+='
',html+='
',html+='
',html+=href?'':configPageUrl?isConnectMode?'
':'
':'",html+='
',html+='
',html+='',html+="
",html+="
",html+=plugin.Name,html+="
",html+="
",html+=plugin.Version,html+="
",html+="
",html+="
",html+="
"}function renderPlugins(page,plugins,showNoPluginsMessage){ApiClient.getJSON(ApiClient.getUrl("web/configurationpages")+"?pageType=PluginConfiguration").then(function(configPages){populateList(page,plugins,configPages,showNoPluginsMessage)})}function populateList(page,plugins,pluginConfigurationPages,showNoPluginsMessage){plugins=plugins.sort(function(plugin1,plugin2){return plugin1.Name>plugin2.Name?1:-1});var html=plugins.map(function(p){return getPluginCardHtml(p,pluginConfigurationPages)}).join("");if(plugins.length){var elem=$(".installedPlugins",page).addClass("itemsContainer").addClass("vertical-wrap").html(html);$(".noConfigPluginCard",elem).on("click",function(){showNoConfigurationMessage()}),$(".connectModePluginCard",elem).on("click",function(){showConnectMessage()}),$(".btnCardMenu",elem).on("click",function(){showPluginMenu(page,this)})}else showNoPluginsMessage&&(html+='
',AppInfo.enableAppStorePolicy?html+="

"+Globalize.translate("MessageNoPluginsDueToAppStore")+"

":(html+="

"+Globalize.translate("MessageNoPluginsInstalled")+"

",html+='

',html+=Globalize.translate("BrowsePluginCatalogMessage"),html+="

"),html+="
"),$(".installedPlugins",page).html(html);Dashboard.hideLoadingMsg()}function showPluginMenu(page,elem){var card=$(elem).parents(".card"),id=card.attr("data-id"),name=card.attr("data-name"),configHref=$(".cardContent",card).attr("href"),menuItems=[];configHref&&menuItems.push({name:Globalize.translate("ButtonSettings"),id:"open",ironIcon:"mode-edit"}),menuItems.push({name:Globalize.translate("ButtonUninstall"),id:"delete",ironIcon:"delete"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:elem,callback:function(resultId){switch(resultId){case"open":Dashboard.navigate(configHref);break;case"delete":deletePlugin(page,id,name)}}})})}function reloadList(page){Dashboard.showLoadingMsg(),ApiClient.getInstalledPlugins().then(function(plugins){renderPlugins(page,plugins,!0)})}function getTabs(){return[{href:"plugins.html",name:Globalize.translate("TabMyPlugins")},{href:"plugincatalog.html",name:Globalize.translate("TabCatalog")}]}$(document).on("pageshow","#pluginsPage",function(){LibraryMenu.setTabs("plugins",0,getTabs),reloadList(this)}),window.PluginsPage={renderPlugins:renderPlugins}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/reports.js b/dashboard-ui/scripts/reports.js index a69c623bf9..a5b94bdb08 100644 --- a/dashboard-ui/scripts/reports.js +++ b/dashboard-ui/scripts/reports.js @@ -1,1054 +1 @@ -define(['jQuery', 'libraryBrowser', 'fnchecked'], function ($, libraryBrowser) { - 'use strict'; - - var defaultSortBy = "SortName"; - var topItems = 5; - - var query = { - StartIndex: 0, - Limit: 100, - IncludeItemTypes: "Movie", - HasQueryLimit: true, - GroupBy: "None", - ReportView: "ReportData", - DisplayType: "Screen", - }; - - function getTable(result) { - var html = ''; - //Report table - html += ''; - html += ''; - - //Report headers - result.Headers.map(function (header) { - var cellHtml = ''; - html += cellHtml; - }); - - html += ''; - //Report body - html += ''; - if (result.IsGrouped === false) { - - result.Rows.map(function (row) { - html += getRow(result.Headers, row); - }); - } - else { - - result.Groups.map(function (group) { - html += ''; - html += ''; - html += ''; - group.Rows.map(function (row) { - html += getRow(result.Headers, row); - }); - html += ''; - html += ''; - html += ''; - }); - } - - html += ''; - html += '
'; - - if (header.ShowHeaderLabel) { - if (header.SortField) { - cellHtml += ''; - } - - cellHtml += (header.Name || ' '); - if (header.SortField) { - cellHtml += ''; - if (header.SortField === defaultSortBy) { - - if (query.SortOrder === "Descending") { - cellHtml += ''; - } else { - cellHtml += ''; - } - } - } - } - cellHtml += '
' + (group.Name || ' ') + '
' + ' ' + '
'; - return html; - } - - function getRow(rHeaders, rRow) { - var html = ''; - html += ''; - - for (var j = 0; j < rHeaders.length; j++) { - var rHeader = rHeaders[j]; - var rItem = rRow.Columns[j]; - html += getItem(rHeader, rRow, rItem); - } - html += ''; - return html; - } - - function getItem(rHeader, rRow, rItem) { - var html = ''; - html += ''; - switch (rHeader.ItemViewType) { - case "None": - html += rItem.Name; - break; - case "Detail": - var id = rRow.Id; - if (rItem.Id) - id = rItem.Id; - html += '' + rItem.Name + ''; - break; - case "Edit": - html += '' + rItem.Name + ''; - break; - case "List": - html += '' + rItem.Name + ''; - break; - case "ItemByNameDetails": - html += '' + rItem.Name + ''; - break; - case "EmbeddedImage": - if (rRow.HasEmbeddedImage) { - html += '
'; - } - break; - case "SubtitleImage": - if (rRow.HasSubtitles) { - html += '
'; - } - break; - case "TrailersImage": - if (rRow.HasLocalTrailer) { - html += '
'; - } - break; - case "SpecialsImage": - if (rRow.HasSpecials) { - html += '
'; - } - break; - case "LockDataImage": - if (rRow.HasLockData) { - html += 'lock'; - } - break; - case "TagsPrimaryImage": - if (!rRow.HasImageTagsPrimary) { - html += ''; - } - break; - case "TagsBackdropImage": - if (!rRow.HasImageTagsBackdrop) { - if (rRow.RowType !== "Episode" && rRow.RowType !== "Season" && rRow.MediaType !== "Audio" && rRow.RowType !== "TvChannel" && rRow.RowType !== "MusicAlbum") { - html += ''; - } - } - break; - case "TagsLogoImage": - if (!rRow.HasImageTagsLogo) { - if (rRow.RowType === "Movie" || rRow.RowType === "Trailer" || rRow.RowType === "Series" || rRow.RowType === "MusicArtist" || rRow.RowType === "BoxSet") { - html += ''; - } - } - break; - case "UserPrimaryImage": - if (rRow.UserId) { - var userImage = ApiClient.getUserImageUrl(rRow.UserId, { - height: 24, - type: 'Primary' - - }); - if (userImage) { - html += ''; - } else { - html += ''; - } - } - break; - case "StatusImage": - if (rRow.HasLockData) { - html += 'lock'; - } - - if (!rRow.HasLocalTrailer && rRow.RowType === "Movie") { - html += 'videocam'; - } - - if (!rRow.HasImageTagsPrimary) { - html += ''; - } - - if (!rRow.HasImageTagsBackdrop) { - if (rRow.RowType !== "Episode" && rRow.RowType !== "Season" && rRow.MediaType !== "Audio" && rRow.RowType !== "TvChannel" && rRow.RowType !== "MusicAlbum") { - html += ''; - } - } - - if (!rRow.HasImageTagsLogo) { - if (rRow.RowType === "Movie" || rRow.RowType === "Trailer" || rRow.RowType === "Series" || rRow.RowType === "MusicArtist" || rRow.RowType === "BoxSet") { - html += ''; - } - } - break; - default: - html += rItem.Name; - } - html += ''; - return html; - } - - function ExportReport(page, e) { - - query.UserId = Dashboard.getCurrentUserId(); - query.HasQueryLimit = false; - var url = ApiClient.getUrl("Reports/Items/Download", query); - - if (url) { - window.location.href = url; - } - } - - function loadGroupByFilters(page) { - - query.UserId = Dashboard.getCurrentUserId(); - var url = ""; - - url = ApiClient.getUrl("Reports/Headers", query); - ApiClient.getJSON(url).then(function (result) { - var selected = "None"; - - $('#selectReportGroup', page).find('option').remove().end(); - $('#selectReportGroup', page).append(''); - - result.map(function (header) { - if ((header.DisplayType === "Screen" || header.DisplayType === "ScreenExport") && header.CanGroup) { - if (header.FieldName.length > 0) { - var option = ''; - $('#selectReportGroup', page).append(option); - if (query.GroupBy === header.FieldName) - selected = header.FieldName; - } - } - }); - $('#selectPageSize', page).val(selected); - - }); - } - - function renderItems(page, result) { - - window.scrollTo(0, 0); - var html = ''; - - if (query.ReportView === "ReportData") { - $('#selectIncludeItemTypesBox', page).show(); - $('#tabFilter', page).show(); - } - else { - $('#selectIncludeItemTypesBox', page).hide(); - $('#tabFilterBox', page).hide(); - $('#tabFilter', page).hide(); - } - - var pagingHtml = libraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - updatePageSizeSetting: false, - viewButton: true, - showLimit: false - }); - - if (query.ReportView === "ReportData" || query.ReportView === "ReportActivities") { - - - $('.listTopPaging', page).html(pagingHtml).trigger('create'); - // page.querySelector('.listTopPaging').innerHTML = pagingHtml; - $('.listTopPaging', page).show(); - - $('.listBottomPaging', page).html(pagingHtml).trigger('create'); - $('.listBottomPaging', page).show(); - - $('.btnNextPage', page).on('click', function () { - query.StartIndex += query.Limit; - reloadItems(page); - }); - $('.btnNextPage', page).show(); - - $('.btnPreviousPage', page).on('click', function () { - query.StartIndex -= query.Limit; - reloadItems(page); - }); - $('.btnPreviousPage', page).show(); - - $('#btnReportExport', page).show(); - $('#selectPageSizeBox', page).show(); - $('#selectReportGroupingBox', page).show(); - $('#grpReportsColumns', page).show(); - - html += getTable(result); - - $('.reporContainer', page).html(html).trigger('create'); - - $('.lnkColumnSort', page).on('click', function () { - - var order = this.getAttribute('data-sortfield'); - - if (query.SortBy === order) { - - if (query.SortOrder === "Descending") { - - query.SortOrder = "Ascending"; - query.SortBy = defaultSortBy; - - } else { - - query.SortOrder = "Descending"; - query.SortBy = order; - } - - } else { - - query.SortOrder = "Ascending"; - query.SortBy = order; - } - - query.StartIndex = 0; - - reloadItems(page); - }); - } - - $('#GroupStatus', page).hide(); - $('#GroupAirDays', page).hide(); - $('#GroupEpisodes', page).hide(); - switch (query.IncludeItemTypes) { - case "Series": - case "Season": - $('#GroupStatus', page).show(); - $('#GroupAirDays', page).show(); - break; - case "Episode": - $('#GroupStatus', page).show(); - $('#GroupAirDays', page).show(); - $('#GroupEpisodes', page).show(); - break; - } - $('.viewPanel', page).refresh; - } - - function reloadItems(page) { - Dashboard.showLoadingMsg(); - - query.UserId = Dashboard.getCurrentUserId(); - var url = ""; - - switch (query.ReportView) { - case "ReportData": - query.HasQueryLimit = true; - url = ApiClient.getUrl("Reports/Items", query); - break; - case "ReportActivities": - query.HasQueryLimit = true; - url = ApiClient.getUrl("Reports/Activities", query); - break; - } - - ApiClient.getJSON(url).then(function (result) { - updateFilterControls(page); - renderItems(page, result); - }); - - - Dashboard.hideLoadingMsg(); - } - - function updateFilterControls(page) { - $('.chkStandardFilter', page).each(function () { - - var filters = "," + (query.Filters || ""); - var filterName = this.getAttribute('data-filter'); - - this.checked = filters.indexOf(',' + filterName) != -1; - - }); - - - $('.chkVideoTypeFilter', page).each(function () { - - var filters = "," + (query.VideoTypes || ""); - var filterName = this.getAttribute('data-filter'); - - this.checked = filters.indexOf(',' + filterName) != -1; - - }); - - $('.chkStatus', page).each(function () { - - var filters = "," + (query.SeriesStatus || ""); - var filterName = this.getAttribute('data-filter'); - - this.checked = filters.indexOf(',' + filterName) != -1; - - }); - - $('.chkAirDays', page).each(function () { - - var filters = "," + (query.AirDays || ""); - var filterName = this.getAttribute('data-filter'); - - this.checked = filters.indexOf(',' + filterName) != -1; - - }); - - $('#chk3D', page).checked(query.Is3D == true); - $('#chkHD', page).checked(query.IsHD == true); - $('#chkSD', page).checked(query.IsHD == false); - - $('#chkSubtitle', page).checked(query.HasSubtitles == true); - $('#chkTrailer', page).checked(query.HasTrailer == true); - $('#chkMissingTrailer', page).checked(query.HasTrailer == false); - $('#chkSpecialFeature', page).checked(query.HasSpecialFeature == true); - $('#chkThemeSong', page).checked(query.HasThemeSong == true); - $('#chkThemeVideo', page).checked(query.HasThemeVideo == true); - - $('#selectPageSize', page).val(query.Limit); - - //Management - $('#chkMissingRating', page).checked(query.HasOfficialRating == false); - $('#chkMissingOverview', page).checked(query.HasOverview == false); - $('#chkIsLocked', page).checked(query.IsLocked == true); - $('#chkMissingImdbId', page).checked(query.HasImdbId == false); - $('#chkMissingTmdbId', page).checked(query.HasTmdbId == false); - $('#chkMissingTvdbId', page).checked(query.HasTvdbId == false); - - //Episodes - $('#chkSpecialEpisode', page).checked(query.ParentIndexNumber == 0); - $('#chkMissingEpisode', page).checked(query.IsMissing == true); - $('#chkFutureEpisode', page).checked(query.IsUnaired == true); - - $('#selectIncludeItemTypes').val(query.IncludeItemTypes); - - // isfavorite - if (query.IsFavorite == true) { - $('#isFavorite').val("true"); - } - else if (query.IsFavorite == false) { - $('#isFavorite').val("false"); - } - else { - $('#isFavorite').val("-"); - } - - - } - - var filtersLoaded; - function reloadFiltersIfNeeded(page) { - if (!filtersLoaded) { - - filtersLoaded = true; - - QueryReportFilters.loadFilters(page, Dashboard.getCurrentUserId(), query, function () { - - reloadItems(page); - }); - - QueryReportColumns.loadColumns(page, Dashboard.getCurrentUserId(), query, function () { - - reloadItems(page); - }); - } - } - - $(document).on('pageinit', "#libraryReportManagerPage", function () { - - var page = this; - - $('#selectIncludeItemTypes', page).on('change', function () { - - query.StartIndex = 0; - query.ReportView = $('#selectViewType', page).val(); - query.IncludeItemTypes = this.value; - query.SortOrder = "Ascending"; - query.ReportColumns = null; - $('.btnReportExport', page).hide(); - filtersLoaded = false; - loadGroupByFilters(page); - reloadFiltersIfNeeded(page); - reloadItems(page); - }); - - $('#selectViewType', page).on('change', function () { - - query.StartIndex = 0; - query.ReportView = this.value; - query.IncludeItemTypes = $('#selectIncludeItemTypes', page).val(); - query.SortOrder = "Ascending"; - filtersLoaded = false; - query.ReportColumns = null; - loadGroupByFilters(page); - reloadFiltersIfNeeded(page); - reloadItems(page); - }); - - $('#selectReportGroup', page).on('change', function () { - query.GroupBy = this.value; - query.StartIndex = 0; - reloadItems(page); - }); - - $('#btnReportExportCsv', page).on('click', function (e) { - - query.ExportType = "CSV"; - ExportReport(page, e); - }); - - $('#btnReportExportExcel', page).on('click', function (e) { - - query.ExportType = "Excel"; - ExportReport(page, e); - }); - - $('#btnResetReportColumns', page).on('click', function (e) { - - query.ReportColumns = null; - query.StartIndex = 0; - filtersLoaded = false; - reloadFiltersIfNeeded(page); - reloadItems(page); - }); - - $('.viewPanel', page).on('panelopen', function () { - reloadFiltersIfNeeded(page); - }); - - $('#selectPageSize', page).on('change', function () { - query.Limit = parseInt(this.value); - query.StartIndex = 0; - reloadItems(page); - }); - - $('#isFavorite', page).on('change', function () { - - if (this.value == "true") { - query.IsFavorite = true; - } - else if (this.value == "false") { - query.IsFavorite = false; - } - else { - query.IsFavorite = null; - } - query.StartIndex = 0; - reloadItems(page); - }); - - $('.chkStandardFilter', this).on('change', function () { - - var filterName = this.getAttribute('data-filter'); - var filters = query.Filters || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.StartIndex = 0; - query.Filters = filters; - - reloadItems(page); - }); - - $('.chkVideoTypeFilter', this).on('change', function () { - - var filterName = this.getAttribute('data-filter'); - var filters = query.VideoTypes || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.StartIndex = 0; - query.VideoTypes = filters; - - reloadItems(page); - }); - - $('#chk3D', this).on('change', function () { - - query.StartIndex = 0; - query.Is3D = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkHD', this).on('change', function () { - - query.StartIndex = 0; - query.IsHD = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkSD', this).on('change', function () { - - query.StartIndex = 0; - query.IsHD = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkSubtitle', this).on('change', function () { - - query.StartIndex = 0; - query.HasSubtitles = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkTrailer', this).on('change', function () { - - query.StartIndex = 0; - query.HasTrailer = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkMissingTrailer', this).on('change', function () { - - query.StartIndex = 0; - query.HasTrailer = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkSpecialFeature', this).on('change', function () { - - query.StartIndex = 0; - query.HasSpecialFeature = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkThemeSong', this).on('change', function () { - - query.StartIndex = 0; - query.HasThemeSong = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkThemeVideo', this).on('change', function () { - - query.StartIndex = 0; - query.HasThemeVideo = this.checked ? true : null; - - reloadItems(page); - }); - - $('#radioBasicFilters', this).on('change', function () { - - if (this.checked) { - $('.basicFilters', page).show(); - $('.advancedFilters', page).hide(); - } else { - $('.basicFilters', page).hide(); - } - }); - - $('#radioAdvancedFilters', this).on('change', function () { - - if (this.checked) { - $('.advancedFilters', page).show(); - $('.basicFilters', page).hide(); - } else { - $('.advancedFilters', page).hide(); - } - }); - - //Management - $('#chkIsLocked', page).on('change', function () { - - query.StartIndex = 0; - query.IsLocked = this.checked ? true : null; - - reloadItems(page); - }); - - $('#chkMissingOverview', page).on('change', function () { - - query.StartIndex = 0; - query.HasOverview = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkMissingEpisode', page).on('change', function () { - - query.StartIndex = 0; - query.IsMissing = this.checked ? true : false; - - reloadItems(page); - }); - - $('#chkMissingRating', page).on('change', function () { - - query.StartIndex = 0; - query.HasOfficialRating = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkMissingImdbId', page).on('change', function () { - - query.StartIndex = 0; - query.HasImdbId = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkMissingTmdbId', page).on('change', function () { - - query.StartIndex = 0; - query.HasTmdbId = this.checked ? false : null; - - reloadItems(page); - }); - - $('#chkMissingTvdbId', page).on('change', function () { - - query.StartIndex = 0; - query.HasTvdbId = this.checked ? false : null; - - reloadItems(page); - }); - - //Episodes - $('#chkMissingEpisode', page).on('change', function () { - - query.StartIndex = 0; - query.IsMissing = this.checked ? true : false; - - reloadItems(page); - }); - - $('#chkFutureEpisode', page).on('change', function () { - - query.StartIndex = 0; - - if (this.checked) { - query.IsUnaired = true; - query.IsVirtualUnaired = null; - } else { - query.IsUnaired = null; - query.IsVirtualUnaired = false; - } - - - reloadItems(page); - }); - - $('#chkSpecialEpisode', page).on('change', function () { - - query.ParentIndexNumber = this.checked ? 0 : null; - - reloadItems(page); - }); - - $('.chkAirDays', this).on('change', function () { - - var filterName = this.getAttribute('data-filter'); - var filters = query.AirDays || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.AirDays = filters; - query.StartIndex = 0; - reloadItems(page); - }); - - $('.chkStatus', this).on('change', function () { - - var filterName = this.getAttribute('data-filter'); - var filters = query.SeriesStatus || ""; - - filters = (',' + filters).replace(',' + filterName, '').substring(1); - - if (this.checked) { - filters = filters ? (filters + ',' + filterName) : filterName; - } - - query.SeriesStatus = filters; - query.StartIndex = 0; - reloadItems(page); - }); - - $(page.getElementsByClassName('viewTabButton')).on('click', function () { - - var parent = $(this).parents('.viewPanel'); - $('.viewTabButton', parent).removeClass('ui-btn-active'); - this.classList.add('ui-btn-active'); - - $('.viewTab', parent).addClass('hide'); - $('.' + this.getAttribute('data-tab'), parent).removeClass('hide'); - }); - }) - .on('pageshow', "#libraryReportManagerPage", function () { - - query.UserId = Dashboard.getCurrentUserId(); - var page = this; - query.SortOrder = "Ascending"; - - QueryReportFilters.onPageShow(page, query); - QueryReportColumns.onPageShow(page, query); - $('#selectIncludeItemTypes', page).val(query.IncludeItemTypes).trigger('change'); - - updateFilterControls(page); - - filtersLoaded = false; - updateFilterControls(this); - }); - - function renderOptions(page, selector, cssClass, items) { - - var elem; - - if (items.length) { - - elem = $(selector, page).show(); - - } else { - elem = $(selector, page).hide(); - } - - var html = ''; - - // style="margin: -.2em -.8em;" - html += '
'; - - var index = 0; - var idPrefix = 'chk' + selector.substring(1); - - html += items.map(function (filter) { - - var itemHtml = ''; - - var id = idPrefix + index; - var label = filter; - var value = filter; - var checked = false; - if (filter.FieldName) { - label = filter.Name; - value = filter.FieldName; - checked = filter.Visible; - } - itemHtml += ''; - itemHtml += ''),cellHtml+=header.Name||" ",header.SortField&&(cellHtml+="",header.SortField===defaultSortBy&&(cellHtml+="Descending"===query.SortOrder?'':''))),cellHtml+="",html+=cellHtml}),html+="",html+="",result.IsGrouped===!1?result.Rows.map(function(row){html+=getRow(result.Headers,row)}):result.Groups.map(function(group){html+='',html+=''+(group.Name||" ")+"",html+="",group.Rows.map(function(row){html+=getRow(result.Headers,row)}),html+="",html+=' ',html+=""}),html+="",html+=""}function getRow(rHeaders,rRow){var html="";html+="";for(var j=0;j'+rItem.Name+"";break;case"Edit":html+=''+rItem.Name+"";break;case"List":html+=''+rItem.Name+"";break;case"ItemByNameDetails":html+=''+rItem.Name+"";break;case"EmbeddedImage":rRow.HasEmbeddedImage&&(html+='
');break;case"SubtitleImage":rRow.HasSubtitles&&(html+='
');break;case"TrailersImage":rRow.HasLocalTrailer&&(html+='
');break;case"SpecialsImage":rRow.HasSpecials&&(html+='
');break;case"LockDataImage":rRow.HasLockData&&(html+='lock');break;case"TagsPrimaryImage":rRow.HasImageTagsPrimary||(html+='');break;case"TagsBackdropImage":rRow.HasImageTagsBackdrop||"Episode"!==rRow.RowType&&"Season"!==rRow.RowType&&"Audio"!==rRow.MediaType&&"TvChannel"!==rRow.RowType&&"MusicAlbum"!==rRow.RowType&&(html+='');break;case"TagsLogoImage":rRow.HasImageTagsLogo||"Movie"!==rRow.RowType&&"Trailer"!==rRow.RowType&&"Series"!==rRow.RowType&&"MusicArtist"!==rRow.RowType&&"BoxSet"!==rRow.RowType||(html+='');break;case"UserPrimaryImage":if(rRow.UserId){var userImage=ApiClient.getUserImageUrl(rRow.UserId,{height:24,type:"Primary"});html+=userImage?'':""}break;case"StatusImage":rRow.HasLockData&&(html+='lock'),rRow.HasLocalTrailer||"Movie"!==rRow.RowType||(html+='videocam'),rRow.HasImageTagsPrimary||(html+=''),rRow.HasImageTagsBackdrop||"Episode"!==rRow.RowType&&"Season"!==rRow.RowType&&"Audio"!==rRow.MediaType&&"TvChannel"!==rRow.RowType&&"MusicAlbum"!==rRow.RowType&&(html+=''),rRow.HasImageTagsLogo||"Movie"!==rRow.RowType&&"Trailer"!==rRow.RowType&&"Series"!==rRow.RowType&&"MusicArtist"!==rRow.RowType&&"BoxSet"!==rRow.RowType||(html+='');break;default:html+=rItem.Name}return html+=""}function ExportReport(page,e){query.UserId=Dashboard.getCurrentUserId(),query.HasQueryLimit=!1;var url=ApiClient.getUrl("Reports/Items/Download",query);url&&(window.location.href=url)}function loadGroupByFilters(page){query.UserId=Dashboard.getCurrentUserId();var url="";url=ApiClient.getUrl("Reports/Headers",query),ApiClient.getJSON(url).then(function(result){var selected="None";$("#selectReportGroup",page).find("option").remove().end(),$("#selectReportGroup",page).append(''),result.map(function(header){if(("Screen"===header.DisplayType||"ScreenExport"===header.DisplayType)&&header.CanGroup&&header.FieldName.length>0){var option='";$("#selectReportGroup",page).append(option),query.GroupBy===header.FieldName&&(selected=header.FieldName)}}),$("#selectPageSize",page).val(selected)})}function renderItems(page,result){window.scrollTo(0,0);var html="";"ReportData"===query.ReportView?($("#selectIncludeItemTypesBox",page).show(),$("#tabFilter",page).show()):($("#selectIncludeItemTypesBox",page).hide(),$("#tabFilterBox",page).hide(),$("#tabFilter",page).hide());var pagingHtml=libraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,updatePageSizeSetting:!1,viewButton:!0,showLimit:!1});switch("ReportData"!==query.ReportView&&"ReportActivities"!==query.ReportView||($(".listTopPaging",page).html(pagingHtml).trigger("create"),$(".listTopPaging",page).show(),$(".listBottomPaging",page).html(pagingHtml).trigger("create"),$(".listBottomPaging",page).show(),$(".btnNextPage",page).on("click",function(){query.StartIndex+=query.Limit,reloadItems(page)}),$(".btnNextPage",page).show(),$(".btnPreviousPage",page).on("click",function(){query.StartIndex-=query.Limit,reloadItems(page)}),$(".btnPreviousPage",page).show(),$("#btnReportExport",page).show(),$("#selectPageSizeBox",page).show(),$("#selectReportGroupingBox",page).show(),$("#grpReportsColumns",page).show(),html+=getTable(result),$(".reporContainer",page).html(html).trigger("create"),$(".lnkColumnSort",page).on("click",function(){var order=this.getAttribute("data-sortfield");query.SortBy===order?"Descending"===query.SortOrder?(query.SortOrder="Ascending",query.SortBy=defaultSortBy):(query.SortOrder="Descending",query.SortBy=order):(query.SortOrder="Ascending",query.SortBy=order),query.StartIndex=0,reloadItems(page)})),$("#GroupStatus",page).hide(),$("#GroupAirDays",page).hide(),$("#GroupEpisodes",page).hide(),query.IncludeItemTypes){case"Series":case"Season":$("#GroupStatus",page).show(),$("#GroupAirDays",page).show();break;case"Episode":$("#GroupStatus",page).show(),$("#GroupAirDays",page).show(),$("#GroupEpisodes",page).show()}$(".viewPanel",page).refresh}function reloadItems(page){Dashboard.showLoadingMsg(),query.UserId=Dashboard.getCurrentUserId();var url="";switch(query.ReportView){case"ReportData":query.HasQueryLimit=!0,url=ApiClient.getUrl("Reports/Items",query);break;case"ReportActivities":query.HasQueryLimit=!0,url=ApiClient.getUrl("Reports/Activities",query)}ApiClient.getJSON(url).then(function(result){updateFilterControls(page),renderItems(page,result)}),Dashboard.hideLoadingMsg()}function updateFilterControls(page){$(".chkStandardFilter",page).each(function(){var filters=","+(query.Filters||""),filterName=this.getAttribute("data-filter");this.checked=filters.indexOf(","+filterName)!=-1}),$(".chkVideoTypeFilter",page).each(function(){var filters=","+(query.VideoTypes||""),filterName=this.getAttribute("data-filter");this.checked=filters.indexOf(","+filterName)!=-1}),$(".chkStatus",page).each(function(){var filters=","+(query.SeriesStatus||""),filterName=this.getAttribute("data-filter");this.checked=filters.indexOf(","+filterName)!=-1}),$(".chkAirDays",page).each(function(){var filters=","+(query.AirDays||""),filterName=this.getAttribute("data-filter");this.checked=filters.indexOf(","+filterName)!=-1}),$("#chk3D",page).checked(1==query.Is3D),$("#chkHD",page).checked(1==query.IsHD),$("#chkSD",page).checked(0==query.IsHD),$("#chkSubtitle",page).checked(1==query.HasSubtitles),$("#chkTrailer",page).checked(1==query.HasTrailer),$("#chkMissingTrailer",page).checked(0==query.HasTrailer),$("#chkSpecialFeature",page).checked(1==query.HasSpecialFeature),$("#chkThemeSong",page).checked(1==query.HasThemeSong),$("#chkThemeVideo",page).checked(1==query.HasThemeVideo),$("#selectPageSize",page).val(query.Limit),$("#chkMissingRating",page).checked(0==query.HasOfficialRating),$("#chkMissingOverview",page).checked(0==query.HasOverview),$("#chkIsLocked",page).checked(1==query.IsLocked),$("#chkMissingImdbId",page).checked(0==query.HasImdbId),$("#chkMissingTmdbId",page).checked(0==query.HasTmdbId),$("#chkMissingTvdbId",page).checked(0==query.HasTvdbId),$("#chkSpecialEpisode",page).checked(0==query.ParentIndexNumber),$("#chkMissingEpisode",page).checked(1==query.IsMissing),$("#chkFutureEpisode",page).checked(1==query.IsUnaired),$("#selectIncludeItemTypes").val(query.IncludeItemTypes),1==query.IsFavorite?$("#isFavorite").val("true"):0==query.IsFavorite?$("#isFavorite").val("false"):$("#isFavorite").val("-")}function reloadFiltersIfNeeded(page){filtersLoaded||(filtersLoaded=!0,QueryReportFilters.loadFilters(page,Dashboard.getCurrentUserId(),query,function(){reloadItems(page)}),QueryReportColumns.loadColumns(page,Dashboard.getCurrentUserId(),query,function(){reloadItems(page)}))}function renderOptions(page,selector,cssClass,items){var elem;elem=items.length?$(selector,page).show():$(selector,page).hide();var html="";html+='
';var index=0,idPrefix="chk"+selector.substring(1);html+=items.map(function(filter){var itemHtml="",id=idPrefix+index,label=filter,value=filter,checked=!1;return filter.FieldName&&(label=filter.Name,value=filter.FieldName,checked=filter.Visible),itemHtml+='",itemHtml+='"; - - if (trigger.MaxRuntimeMs) { - html += '
'; - - var hours = trigger.MaxRuntimeMs / 3600000; - - if (hours == 1) { - html += Globalize.translate('ValueTimeLimitSingleHour'); - } else { - html += Globalize.translate('ValueTimeLimitMultiHour', hours); - } - html += '
'; - } - - html += '
'; - - html += ''; - - html += '
'; - } - - html += '
'; - - context.querySelector('.taskTriggers').innerHTML = html; - }, - - getTriggerFriendlyName: function (trigger) { - - if (trigger.Type == 'DailyTrigger') { - return 'Daily at ' + ScheduledTaskPage.getDisplayTime(trigger.TimeOfDayTicks); - } - - if (trigger.Type == 'WeeklyTrigger') { - - return trigger.DayOfWeek + 's at ' + ScheduledTaskPage.getDisplayTime(trigger.TimeOfDayTicks); - } - - if (trigger.Type == 'SystemEventTrigger') { - - if (trigger.SystemEvent == 'WakeFromSleep') { - return 'On wake from sleep'; - } - } - - if (trigger.Type == 'IntervalTrigger') { - - var hours = trigger.IntervalTicks / 36000000000; - - if (hours == .25) { - return "Every 15 minutes"; - } - if (hours == .5) { - return "Every 30 minutes"; - } - if (hours == .75) { - return "Every 45 minutes"; - } - if (hours == 1) { - return "Every hour"; - } - - return 'Every ' + hours + ' hours'; - } - - if (trigger.Type == 'StartupTrigger') { - return 'On application startup'; - } - - return trigger.Type; - }, - - getDisplayTime: function (ticks) { - - var hours = ticks / 36000000000; - - if (hours < 1) { - hours = 0; - } - - hours = Math.floor(hours); - - ticks -= (hours * 36000000000); - - var minutes = Math.floor((ticks / 600000000)); - - var suffix = "am"; - - if (hours > 11) { - suffix = "pm"; - } - - hours = hours % 12; - - if (hours == 0) { - hours = 12; - } - - if (minutes < 10) { - minutes = '0' + minutes; - } - - return hours + ':' + minutes + ' ' + suffix; - }, - - showAddTriggerPopup: function () { - - var page = $.mobile.activePage; - - $('#selectTriggerType', page).val('DailyTrigger').trigger('change'); - - $('#popupAddTrigger', page).on("popupafteropen", function () { - $('#addTriggerForm input:first', this).focus(); - }).popup("open").on("popupafterclose", function () { - - $('#addTriggerForm', page).off("submit"); - $(this).off("popupafterclose"); - }); - }, - - confirmDeleteTrigger: function (index) { - - require(['confirm'], function (confirm) { - confirm(Globalize.translate('MessageDeleteTaskTrigger'), Globalize.translate('HeaderDeleteTaskTrigger')).then(function () { - ScheduledTaskPage.deleteTrigger(index); - }); - }); - }, - - deleteTrigger: function (index) { - - Dashboard.showLoadingMsg(); - - var id = getParameterByName('id'); - - - ApiClient.getScheduledTask(id).then(function (task) { - - task.Triggers.remove(index); - - ApiClient.updateScheduledTaskTriggers(task.Id, task.Triggers).then(function () { - - ScheduledTaskPage.refreshScheduledTask(); - - }); - - }); - }, - - refreshTriggerFields: function (triggerType) { - - var page = $.mobile.activePage; - - if (triggerType == 'DailyTrigger') { - - $('#fldTimeOfDay', page).show(); - $('#fldDayOfWeek', page).hide(); - $('#fldSelectSystemEvent', page).hide(); - $('#fldSelectInterval', page).hide(); - $('#txtTimeOfDay', page).attr('required', 'required'); - } - - else if (triggerType == 'WeeklyTrigger') { - $('#fldTimeOfDay', page).show(); - $('#fldDayOfWeek', page).show(); - $('#fldSelectSystemEvent', page).hide(); - $('#fldSelectInterval', page).hide(); - $('#txtTimeOfDay', page).attr('required', 'required'); - } - - else if (triggerType == 'SystemEventTrigger') { - $('#fldTimeOfDay', page).hide(); - $('#fldDayOfWeek', page).hide(); - $('#fldSelectSystemEvent', page).show(); - $('#fldSelectInterval', page).hide(); - $('#txtTimeOfDay', page).removeAttr('required'); - } - - else if (triggerType == 'IntervalTrigger') { - $('#fldTimeOfDay', page).hide(); - $('#fldDayOfWeek', page).hide(); - $('#fldSelectSystemEvent', page).hide(); - $('#fldSelectInterval', page).show(); - $('#txtTimeOfDay', page).removeAttr('required'); - } - - else if (triggerType == 'StartupTrigger') { - $('#fldTimeOfDay', page).hide(); - $('#fldDayOfWeek', page).hide(); - $('#fldSelectSystemEvent', page).hide(); - $('#fldSelectInterval', page).hide(); - $('#txtTimeOfDay', page).removeAttr('required'); - } - }, - - getTriggerToAdd: function () { - - var page = $.mobile.activePage; - - var trigger = { - Type: $('#selectTriggerType', page).val() - }; - - if (trigger.Type == 'DailyTrigger') { - trigger.TimeOfDayTicks = ScheduledTaskPage.getTimeOfDayTicks($('#txtTimeOfDay', page).val()); - } - - else if (trigger.Type == 'WeeklyTrigger') { - trigger.DayOfWeek = $('#selectDayOfWeek', page).val(); - trigger.TimeOfDayTicks = ScheduledTaskPage.getTimeOfDayTicks($('#txtTimeOfDay', page).val()); - } - - else if (trigger.Type == 'SystemEventTrigger') { - trigger.SystemEvent = $('#selectSystemEvent', page).val(); - } - - else if (trigger.Type == 'IntervalTrigger') { - trigger.IntervalTicks = $('#selectInterval', page).val(); - } - - var timeLimit = $('#txtTimeLimit', page).val() || '0'; - timeLimit = parseFloat(timeLimit) * 3600000; - - trigger.MaxRuntimeMs = timeLimit || null; - - return trigger; - }, - - getTimeOfDayTicks: function (val) { - - var vals = val.split(':'); - - var hours = vals[0]; - var minutes = vals[1].split(' ')[0]; - - // Add hours - var ticks = hours * 60 * 60 * 1000 * 10000; - - ticks += minutes * 60 * 1000 * 10000; - - return ticks; - } - }; - - (function () { - - function onSubmit() { - - Dashboard.showLoadingMsg(); - - var id = getParameterByName('id'); - - ApiClient.getScheduledTask(id).then(function (task) { - - task.Triggers.push(ScheduledTaskPage.getTriggerToAdd()); - - ApiClient.updateScheduledTaskTriggers(task.Id, task.Triggers).then(function () { - - $('#popupAddTrigger').popup('close'); - - ScheduledTaskPage.refreshScheduledTask(); - - }); - - }); - - return false; - } - - $(document).on('pageinit', "#scheduledTaskPage", function () { - - var page = this; - - $('.addTriggerForm').off('submit', onSubmit).on('submit', onSubmit); - - page.querySelector('.timeFieldExample').innerHTML = Globalize.translate('ValueExample', '1:00 PM'); - - }).on('pageshow', "#scheduledTaskPage", function () { - - ScheduledTaskPage.refreshScheduledTask(); - }); - - })(); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";Array.prototype.remove=function(from,to){var rest=this.slice((to||from)+1||this.length);return this.length=from<0?this.length+from:from,this.push.apply(this,rest)},window.ScheduledTaskPage={refreshScheduledTask:function(){Dashboard.showLoadingMsg();var id=getParameterByName("id");ApiClient.getScheduledTask(id).then(ScheduledTaskPage.loadScheduledTask)},loadScheduledTask:function(task){var page=$($.mobile.activePage)[0];$(".taskName",page).html(task.Name),$("#pTaskDescription",page).html(task.Description),require(["listViewStyle"],function(){ScheduledTaskPage.loadTaskTriggers(page,task)}),Dashboard.hideLoadingMsg()},loadTaskTriggers:function(context,task){var html="";html+='
';for(var i=0,length=task.Triggers.length;i',html+='schedule',html+=trigger.MaxRuntimeMs?'
':'
',html+="
"+ScheduledTaskPage.getTriggerFriendlyName(trigger)+"
",trigger.MaxRuntimeMs){html+='
';var hours=trigger.MaxRuntimeMs/36e5;html+=1==hours?Globalize.translate("ValueTimeLimitSingleHour"):Globalize.translate("ValueTimeLimitMultiHour",hours),html+="
"}html+="
",html+='',html+="
"}html+="
",context.querySelector(".taskTriggers").innerHTML=html},getTriggerFriendlyName:function(trigger){if("DailyTrigger"==trigger.Type)return"Daily at "+ScheduledTaskPage.getDisplayTime(trigger.TimeOfDayTicks);if("WeeklyTrigger"==trigger.Type)return trigger.DayOfWeek+"s at "+ScheduledTaskPage.getDisplayTime(trigger.TimeOfDayTicks);if("SystemEventTrigger"==trigger.Type&&"WakeFromSleep"==trigger.SystemEvent)return"On wake from sleep";if("IntervalTrigger"==trigger.Type){var hours=trigger.IntervalTicks/36e9;return.25==hours?"Every 15 minutes":.5==hours?"Every 30 minutes":.75==hours?"Every 45 minutes":1==hours?"Every hour":"Every "+hours+" hours"}return"StartupTrigger"==trigger.Type?"On application startup":trigger.Type},getDisplayTime:function(ticks){var hours=ticks/36e9;hours<1&&(hours=0),hours=Math.floor(hours),ticks-=36e9*hours;var minutes=Math.floor(ticks/6e8),suffix="am";return hours>11&&(suffix="pm"),hours%=12,0==hours&&(hours=12),minutes<10&&(minutes="0"+minutes),hours+":"+minutes+" "+suffix},showAddTriggerPopup:function(){var page=$.mobile.activePage;$("#selectTriggerType",page).val("DailyTrigger").trigger("change"),$("#popupAddTrigger",page).on("popupafteropen",function(){$("#addTriggerForm input:first",this).focus()}).popup("open").on("popupafterclose",function(){$("#addTriggerForm",page).off("submit"),$(this).off("popupafterclose")})},confirmDeleteTrigger:function(index){require(["confirm"],function(confirm){confirm(Globalize.translate("MessageDeleteTaskTrigger"),Globalize.translate("HeaderDeleteTaskTrigger")).then(function(){ScheduledTaskPage.deleteTrigger(index)})})},deleteTrigger:function(index){Dashboard.showLoadingMsg();var id=getParameterByName("id");ApiClient.getScheduledTask(id).then(function(task){task.Triggers.remove(index),ApiClient.updateScheduledTaskTriggers(task.Id,task.Triggers).then(function(){ScheduledTaskPage.refreshScheduledTask()})})},refreshTriggerFields:function(triggerType){var page=$.mobile.activePage;"DailyTrigger"==triggerType?($("#fldTimeOfDay",page).show(),$("#fldDayOfWeek",page).hide(),$("#fldSelectSystemEvent",page).hide(),$("#fldSelectInterval",page).hide(),$("#txtTimeOfDay",page).attr("required","required")):"WeeklyTrigger"==triggerType?($("#fldTimeOfDay",page).show(),$("#fldDayOfWeek",page).show(),$("#fldSelectSystemEvent",page).hide(),$("#fldSelectInterval",page).hide(),$("#txtTimeOfDay",page).attr("required","required")):"SystemEventTrigger"==triggerType?($("#fldTimeOfDay",page).hide(),$("#fldDayOfWeek",page).hide(),$("#fldSelectSystemEvent",page).show(),$("#fldSelectInterval",page).hide(),$("#txtTimeOfDay",page).removeAttr("required")):"IntervalTrigger"==triggerType?($("#fldTimeOfDay",page).hide(),$("#fldDayOfWeek",page).hide(),$("#fldSelectSystemEvent",page).hide(),$("#fldSelectInterval",page).show(),$("#txtTimeOfDay",page).removeAttr("required")):"StartupTrigger"==triggerType&&($("#fldTimeOfDay",page).hide(),$("#fldDayOfWeek",page).hide(),$("#fldSelectSystemEvent",page).hide(),$("#fldSelectInterval",page).hide(),$("#txtTimeOfDay",page).removeAttr("required"))},getTriggerToAdd:function(){var page=$.mobile.activePage,trigger={Type:$("#selectTriggerType",page).val()};"DailyTrigger"==trigger.Type?trigger.TimeOfDayTicks=ScheduledTaskPage.getTimeOfDayTicks($("#txtTimeOfDay",page).val()):"WeeklyTrigger"==trigger.Type?(trigger.DayOfWeek=$("#selectDayOfWeek",page).val(),trigger.TimeOfDayTicks=ScheduledTaskPage.getTimeOfDayTicks($("#txtTimeOfDay",page).val())):"SystemEventTrigger"==trigger.Type?trigger.SystemEvent=$("#selectSystemEvent",page).val():"IntervalTrigger"==trigger.Type&&(trigger.IntervalTicks=$("#selectInterval",page).val());var timeLimit=$("#txtTimeLimit",page).val()||"0";return timeLimit=36e5*parseFloat(timeLimit),trigger.MaxRuntimeMs=timeLimit||null,trigger},getTimeOfDayTicks:function(val){var vals=val.split(":"),hours=vals[0],minutes=vals[1].split(" ")[0],ticks=60*hours*60*1e3*1e4;return ticks+=60*minutes*1e3*1e4}},function(){function onSubmit(){Dashboard.showLoadingMsg();var id=getParameterByName("id");return ApiClient.getScheduledTask(id).then(function(task){task.Triggers.push(ScheduledTaskPage.getTriggerToAdd()),ApiClient.updateScheduledTaskTriggers(task.Id,task.Triggers).then(function(){$("#popupAddTrigger").popup("close"),ScheduledTaskPage.refreshScheduledTask()})}),!1}$(document).on("pageinit","#scheduledTaskPage",function(){var page=this;$(".addTriggerForm").off("submit",onSubmit).on("submit",onSubmit),page.querySelector(".timeFieldExample").innerHTML=Globalize.translate("ValueExample","1:00 PM")}).on("pageshow","#scheduledTaskPage",function(){ScheduledTaskPage.refreshScheduledTask()})}()}); \ No newline at end of file diff --git a/dashboard-ui/scripts/scheduledtaskspage.js b/dashboard-ui/scripts/scheduledtaskspage.js index fb581fe95d..632058698b 100644 --- a/dashboard-ui/scripts/scheduledtaskspage.js +++ b/dashboard-ui/scripts/scheduledtaskspage.js @@ -1,301 +1 @@ -define(['jQuery', 'humanedate', 'listViewStyle'], function ($) { - 'use strict'; - - function reloadList(page) { - - ApiClient.getScheduledTasks({ isHidden: false }).then(function (tasks) { - - populateList(page, tasks); - - Dashboard.hideLoadingMsg(); - }); - } - - function populateList(page, tasks) { - tasks = tasks.sort(function (a, b) { - - a = a.Category + " " + a.Name; - b = b.Category + " " + b.Name; - - if (a == b) { - return 0; - } - - if (a < b) { - return -1; - } - - return 1; - }); - - var html = ""; - - var currentCategory; - - for (var i = 0, length = tasks.length; i < length; i++) { - - var task = tasks[i]; - - if (task.Category != currentCategory) { - currentCategory = task.Category; - - if (currentCategory) { - html += '
'; - html += '
'; - } - html += '
'; - html += '

'; - html += currentCategory; - html += '

'; - - html += '
'; - } - - html += '
'; - - html += ""; - html += 'schedule'; - html += ""; - - html += ''; - - if (task.State == "Idle") { - - html += ''; - } - else if (task.State == "Running") { - - html += ''; - - } else { - - html += ''; - } - - html += '
'; - } - - if (tasks.length) { - html += '
'; - html += '
'; - } - - var divScheduledTasks = page.querySelector('.divScheduledTasks'); - divScheduledTasks.innerHTML = html; - } - - function humane_elapsed(firstDateStr, secondDateStr) { - var dt1 = new Date(firstDateStr); - var dt2 = new Date(secondDateStr); - var seconds = (dt2.getTime() - dt1.getTime()) / 1000; - var numdays = Math.floor((seconds % 31536000) / 86400); - var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600); - var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60); - var numseconds = Math.round((((seconds % 31536000) % 86400) % 3600) % 60); - - var elapsedStr = ''; - elapsedStr += numdays == 1 ? numdays + ' day ' : ''; - elapsedStr += numdays > 1 ? numdays + ' days ' : ''; - elapsedStr += numhours == 1 ? numhours + ' hour ' : ''; - elapsedStr += numhours > 1 ? numhours + ' hours ' : ''; - elapsedStr += numminutes == 1 ? numminutes + ' minute ' : ''; - elapsedStr += numminutes > 1 ? numminutes + ' minutes ' : ''; - elapsedStr += elapsedStr.length > 0 ? 'and ' : ''; - elapsedStr += numseconds == 1 ? numseconds + ' second' : ''; - elapsedStr += numseconds == 0 || numseconds > 1 ? numseconds + ' seconds' : ''; - - return elapsedStr; - - } - - function getTaskProgressHtml(task) { - var html = ''; - - if (task.State == "Idle") { - - if (task.LastExecutionResult) { - - html += Globalize.translate('LabelScheduledTaskLastRan').replace("{0}", humane_date(task.LastExecutionResult.EndTimeUtc)) - .replace("{1}", humane_elapsed(task.LastExecutionResult.StartTimeUtc, task.LastExecutionResult.EndTimeUtc)); - - if (task.LastExecutionResult.Status == "Failed") { - html += " (" + Globalize.translate('LabelFailed') + ")"; - } - else if (task.LastExecutionResult.Status == "Cancelled") { - html += " (" + Globalize.translate('LabelCancelled') + ")"; - } - else if (task.LastExecutionResult.Status == "Aborted") { - html += " " + Globalize.translate('LabelAbortedByServerShutdown') + ""; - } - } - } - else if (task.State == "Running") { - - var progress = (task.CurrentProgressPercentage || 0).toFixed(1); - - html += '
'; - html += '
'; - html += '
'; - html += '
'; - html += '
'; - - html += "" + progress + "%"; - html += '
'; - - } else { - - html += "" + Globalize.translate('LabelStopping') + ""; - } - - return html; - } - - function onWebSocketMessage(e, msg) { - if (msg.MessageType == "ScheduledTasksInfo") { - - var tasks = msg.Data; - - var page = $($.mobile.activePage)[0]; - - updateTasks(page, tasks); - } - } - - function updateTasks(page, tasks) { - for (var i = 0, length = tasks.length; i < length; i++) { - - var task = tasks[i]; - - page.querySelector('#taskProgress' + task.Id).innerHTML = getTaskProgressHtml(task); - - var btnTask = page.querySelector('#btnTask' + task.Id); - - updateTaskButton(btnTask, task.State); - } - } - - function updateTaskButton(elem, state) { - - if (state == "Idle") { - - elem.classList.add('btnStartTask'); - elem.classList.remove('btnStopTask'); - elem.classList.remove('hide'); - elem.querySelector('i').innerHTML = 'play_arrow'; - elem.title = Globalize.translate('ButtonStart'); - } - else if (state == "Running") { - - elem.classList.remove('btnStartTask'); - elem.classList.add('btnStopTask'); - elem.classList.remove('hide'); - elem.querySelector('i').innerHTML = 'stop'; - elem.title = Globalize.translate('ButtonStop'); - - } else { - - elem.classList.add('btnStartTask'); - elem.classList.remove('btnStopTask'); - elem.classList.add('hide'); - elem.querySelector('i').innerHTML = 'play_arrow'; - elem.title = Globalize.translate('ButtonStart'); - } - - var item = $(elem).parents('.listItem')[0]; - item.setAttribute('data-status', state); - } - - function onWebSocketConnectionOpen() { - - var page = $($.mobile.activePage)[0]; - - startInterval(); - reloadList(page); - } - - var pollInterval; - function onPollIntervalFired() { - - var page = $($.mobile.activePage)[0]; - - if (!ApiClient.isWebSocketOpen()) { - reloadList(page); - } - } - - function startInterval() { - if (ApiClient.isWebSocketOpen()) { - ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "1000,1000"); - } - if (pollInterval) { - clearInterval(pollInterval); - } - pollInterval = setInterval(onPollIntervalFired, 5000); - } - - function stopInterval() { - if (ApiClient.isWebSocketOpen()) { - ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); - } - if (pollInterval) { - clearInterval(pollInterval); - } - } - - $(document).on('pageinit', "#scheduledTasksPage", function () { - - var page = this; - - $('.divScheduledTasks', page).on('click', '.btnStartTask', function () { - - var button = this; - var id = button.getAttribute('data-taskid'); - ApiClient.startScheduledTask(id).then(function () { - - updateTaskButton(button, "Running"); - reloadList(page); - }); - - }).on('click', '.btnStopTask', function () { - - var button = this; - var id = button.getAttribute('data-taskid'); - ApiClient.stopScheduledTask(id).then(function () { - - updateTaskButton(button, ""); - reloadList(page); - }); - }); - - }).on('pageshow', "#scheduledTasksPage", function () { - - var page = this; - - Dashboard.showLoadingMsg(); - - startInterval(); - - reloadList(page); - - Events.on(ApiClient, "websocketmessage", onWebSocketMessage); - Events.on(ApiClient, "websocketopen", onWebSocketConnectionOpen); - - }).on('pagebeforehide', "#scheduledTasksPage", function () { - - var page = this; - - Events.off(ApiClient, "websocketmessage", onWebSocketMessage); - Events.off(ApiClient, "websocketopen", onWebSocketConnectionOpen); - stopInterval(); - }); - -}); \ No newline at end of file +define(["jQuery","humanedate","listViewStyle"],function($){"use strict";function reloadList(page){ApiClient.getScheduledTasks({isHidden:!1}).then(function(tasks){populateList(page,tasks),Dashboard.hideLoadingMsg()})}function populateList(page,tasks){tasks=tasks.sort(function(a,b){return a=a.Category+" "+a.Name,b=b.Category+" "+b.Name,a==b?0:a",html+="
"),html+='
',html+="

",html+=currentCategory,html+="

",html+='
'),html+='
',html+="",html+='schedule',html+="",html+='",html+="Idle"==task.State?'':"Running"==task.State?'':'',html+="
"}tasks.length&&(html+="
",html+="
");var divScheduledTasks=page.querySelector(".divScheduledTasks");divScheduledTasks.innerHTML=html}function humane_elapsed(firstDateStr,secondDateStr){var dt1=new Date(firstDateStr),dt2=new Date(secondDateStr),seconds=(dt2.getTime()-dt1.getTime())/1e3,numdays=Math.floor(seconds%31536e3/86400),numhours=Math.floor(seconds%31536e3%86400/3600),numminutes=Math.floor(seconds%31536e3%86400%3600/60),numseconds=Math.round(seconds%31536e3%86400%3600%60),elapsedStr="";return elapsedStr+=1==numdays?numdays+" day ":"",elapsedStr+=numdays>1?numdays+" days ":"",elapsedStr+=1==numhours?numhours+" hour ":"",elapsedStr+=numhours>1?numhours+" hours ":"",elapsedStr+=1==numminutes?numminutes+" minute ":"",elapsedStr+=numminutes>1?numminutes+" minutes ":"",elapsedStr+=elapsedStr.length>0?"and ":"",elapsedStr+=1==numseconds?numseconds+" second":"",elapsedStr+=0==numseconds||numseconds>1?numseconds+" seconds":""}function getTaskProgressHtml(task){var html="";if("Idle"==task.State)task.LastExecutionResult&&(html+=Globalize.translate("LabelScheduledTaskLastRan").replace("{0}",humane_date(task.LastExecutionResult.EndTimeUtc)).replace("{1}",humane_elapsed(task.LastExecutionResult.StartTimeUtc,task.LastExecutionResult.EndTimeUtc)),"Failed"==task.LastExecutionResult.Status?html+=" ("+Globalize.translate("LabelFailed")+")":"Cancelled"==task.LastExecutionResult.Status?html+=" ("+Globalize.translate("LabelCancelled")+")":"Aborted"==task.LastExecutionResult.Status&&(html+=" "+Globalize.translate("LabelAbortedByServerShutdown")+""));else if("Running"==task.State){var progress=(task.CurrentProgressPercentage||0).toFixed(1);html+='
',html+='
',html+='
',html+="
",html+="
",html+=""+progress+"%",html+="
"}else html+=""+Globalize.translate("LabelStopping")+"";return html}function onWebSocketMessage(e,msg){if("ScheduledTasksInfo"==msg.MessageType){var tasks=msg.Data,page=$($.mobile.activePage)[0];updateTasks(page,tasks)}}function updateTasks(page,tasks){for(var i=0,length=tasks.length;i'; - itemHtml += i.Name; - itemHtml += '
'; - return itemHtml; - - }).join(''); - - page.querySelector('.searchSuggestions').innerHTML = html; - }); - } - - return function (view, params) { - - var textSuggestions = view.querySelector('.textSuggestions'); - var searchResults = view.querySelector('.searchResults'); - var searchHintTimeout; - - function clearSearchHintTimeout() { - - if (searchHintTimeout) { - - clearTimeout(searchHintTimeout); - searchHintTimeout = null; - } - } - - function showTextSuggestions() { - textSuggestions.classList.remove('hide'); - } - - function getAdditionalTextLines(hint) { - - if (hint.Type == "Audio") { - - return [[hint.AlbumArtist, hint.Album].join(" - ")]; - - } - else if (hint.Type == "MusicAlbum") { - - return [hint.AlbumArtist]; - - } - else if (hint.Type == "MusicArtist") { - - return [Globalize.translate('LabelArtist')]; - - } - else if (hint.Type == "Movie") { - - return [Globalize.translate('LabelMovie')]; - - } - else if (hint.Type == "MusicVideo") { - - return [Globalize.translate('LabelMusicVideo')]; - } - else if (hint.Type == "Episode") { - - return [Globalize.translate('LabelEpisode')]; - - } - else if (hint.Type == "Series") { - - return [Globalize.translate('Series')]; - } - else if (hint.Type == "BoxSet") { - - return [Globalize.translate('LabelCollection')]; - } - else if (hint.ChannelName) { - - return [hint.ChannelName]; - } - - return [hint.Type]; - } - - function renderSearchResultsInOverlay(hints) { - - // Massage the objects to look like regular items - hints = hints.map(function (i) { - - i.Id = i.ItemId; - i.ImageTags = {}; - i.UserData = {}; - - if (i.PrimaryImageTag) { - i.ImageTags.Primary = i.PrimaryImageTag; - } - return i; - }); - - var html = cardBuilder.getCardsHtml({ - items: hints, - shape: "auto", - overlayText: false, - showTitle: true, - centerImage: true, - centerText: true, - textLines: getAdditionalTextLines, - overlayMoreButton: true, - serverId: ApiClient.serverInfo().Id - }); - - if (!hints.length) { - html = '

' + Globalize.translate('NoResultsFound') + '

'; - } - - var itemsContainer = searchResults; - itemsContainer.innerHTML = html; - searchResults.classList.remove('hide'); - textSuggestions.classList.add('hide'); - imageLoader.lazyChildren(itemsContainer); - } - - function requestSearchHintsForOverlay(searchTerm) { - - var currentTimeout = searchHintTimeout; - Dashboard.showLoadingMsg(); - - ApiClient.getSearchHints({ - - userId: Dashboard.getCurrentUserId(), - searchTerm: (searchTerm || '').trim(), - limit: 30 - - }).then(function (result) { - - if (currentTimeout == searchHintTimeout) { - renderSearchResultsInOverlay(result.SearchHints); - } - - Dashboard.hideLoadingMsg(); - }, function () { - Dashboard.hideLoadingMsg(); - }); - } - - function onSearchChange(val) { - - if (!val) { - clearSearchHintTimeout(); - searchResults.classList.add('hide'); - searchResults.innerHTML = ''; - showTextSuggestions(); - return; - } - - clearSearchHintTimeout(); - - searchHintTimeout = setTimeout(function () { - requestSearchHintsForOverlay(val); - }, 300); - } - - showTextSuggestions(); - loadSuggestions(view); - - view.querySelector('.txtSearch').addEventListener('input', function () { - onSearchChange(this.value); - }); - - view.querySelector('.btnBack').addEventListener('click', function () { - embyRouter.back(); - }); - - view.addEventListener('viewbeforeshow', function (e) { - document.body.classList.add('hiddenViewMenuBar'); - }); - - view.addEventListener('viewbeforehide', function (e) { - - document.body.classList.remove('hiddenViewMenuBar'); - }); - - }; -}); \ No newline at end of file +define(["libraryBrowser","focusManager","embyRouter","cardBuilder","imageLoader","emby-input","paper-icon-button-light","material-icons","emby-itemscontainer"],function(libraryBrowser,focusManager,embyRouter,cardBuilder,imageLoader){"use strict";function loadSuggestions(page){var options={SortBy:"IsFavoriteOrLiked,Random",IncludeItemTypes:"Movie,Series,MusicArtist",Limit:20,Recursive:!0,ImageTypeLimit:0,EnableImages:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){var html=result.Items.map(function(i){var href=LibraryBrowser.getHref(i),itemHtml='"}).join("");page.querySelector(".searchSuggestions").innerHTML=html})}return function(view,params){function clearSearchHintTimeout(){searchHintTimeout&&(clearTimeout(searchHintTimeout),searchHintTimeout=null)}function showTextSuggestions(){textSuggestions.classList.remove("hide")}function getAdditionalTextLines(hint){return"Audio"==hint.Type?[[hint.AlbumArtist,hint.Album].join(" - ")]:"MusicAlbum"==hint.Type?[hint.AlbumArtist]:"MusicArtist"==hint.Type?[Globalize.translate("LabelArtist")]:"Movie"==hint.Type?[Globalize.translate("LabelMovie")]:"MusicVideo"==hint.Type?[Globalize.translate("LabelMusicVideo")]:"Episode"==hint.Type?[Globalize.translate("LabelEpisode")]:"Series"==hint.Type?[Globalize.translate("Series")]:"BoxSet"==hint.Type?[Globalize.translate("LabelCollection")]:hint.ChannelName?[hint.ChannelName]:[hint.Type]}function renderSearchResultsInOverlay(hints){hints=hints.map(function(i){return i.Id=i.ItemId,i.ImageTags={},i.UserData={},i.PrimaryImageTag&&(i.ImageTags.Primary=i.PrimaryImageTag),i});var html=cardBuilder.getCardsHtml({items:hints,shape:"auto",overlayText:!1,showTitle:!0,centerImage:!0,centerText:!0,textLines:getAdditionalTextLines,overlayMoreButton:!0,serverId:ApiClient.serverInfo().Id});hints.length||(html='

'+Globalize.translate("NoResultsFound")+"

");var itemsContainer=searchResults;itemsContainer.innerHTML=html,searchResults.classList.remove("hide"),textSuggestions.classList.add("hide"),imageLoader.lazyChildren(itemsContainer)}function requestSearchHintsForOverlay(searchTerm){var currentTimeout=searchHintTimeout;Dashboard.showLoadingMsg(),ApiClient.getSearchHints({userId:Dashboard.getCurrentUserId(),searchTerm:(searchTerm||"").trim(),limit:30}).then(function(result){currentTimeout==searchHintTimeout&&renderSearchResultsInOverlay(result.SearchHints),Dashboard.hideLoadingMsg()},function(){Dashboard.hideLoadingMsg()})}function onSearchChange(val){return val?(clearSearchHintTimeout(),void(searchHintTimeout=setTimeout(function(){requestSearchHintsForOverlay(val)},300))):(clearSearchHintTimeout(),searchResults.classList.add("hide"),searchResults.innerHTML="",void showTextSuggestions())}var searchHintTimeout,textSuggestions=view.querySelector(".textSuggestions"),searchResults=view.querySelector(".searchResults");showTextSuggestions(),loadSuggestions(view),view.querySelector(".txtSearch").addEventListener("input",function(){onSearchChange(this.value)}),view.querySelector(".btnBack").addEventListener("click",function(){embyRouter.back()}),view.addEventListener("viewbeforeshow",function(e){document.body.classList.add("hiddenViewMenuBar")}),view.addEventListener("viewbeforehide",function(e){document.body.classList.remove("hiddenViewMenuBar")})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/secondaryitems.js b/dashboard-ui/scripts/secondaryitems.js index ce844b8929..c46e9d9e95 100644 --- a/dashboard-ui/scripts/secondaryitems.js +++ b/dashboard-ui/scripts/secondaryitems.js @@ -1,277 +1 @@ -define(['libraryBrowser', 'listView', 'cardBuilder', 'imageLoader', 'emby-itemscontainer'], function (libraryBrowser, listView, cardBuilder, imageLoader) { - 'use strict'; - - return function (view, params) { - - var data = {}; - - function addCurrentItemToQuery(query, item) { - - if (params.parentId) { - query.ParentId = params.parentId; - } - - if (item.Type == "Person") { - query.PersonIds = item.Id; - } - else if (item.Type == "Genre") { - query.Genres = item.Name; - } - else if (item.Type == "MusicGenre") { - query.Genres = item.Name; - } - else if (item.Type == "GameGenre") { - query.Genres = item.Name; - } - else if (item.Type == "Studio") { - query.StudioIds = item.Id; - } - else if (item.Type == "MusicArtist") { - query.ArtistIds = item.Id; - } else { - query.ParentId = item.Id; - } - } - - function getQuery(parentItem) { - - var key = getSavedQueryKey(); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - Recursive: params.recursive !== 'false', - Fields: "PrimaryImageAspectRatio,SortName,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: libraryBrowser.getDefaultPageSize() - } - }; - - var type = params.type; - if (type) { - pageData.query.IncludeItemTypes = type; - - if (type == 'Audio') { - pageData.query.SortBy = 'Album,SortName'; - } - } - - var filters = params.filters; - if (type) { - pageData.query.Filters = filters; - } - - if (parentItem) { - addCurrentItemToQuery(pageData.query, parentItem); - } - - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData.query; - } - - function getSavedQueryKey() { - - return libraryBrowser.getSavedQueryKey(); - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - function onListItemClick(e) { - - var mediaItem = parentWithClass(e.target, 'mediaItem'); - if (mediaItem) { - var info = libraryBrowser.getListItemInfo(mediaItem); - - if (info.mediaType == 'Photo') { - var query = getQuery(); - - require(['scripts/photos'], function () { - Photos.startSlideshow(view, query, info.id); - }); - return false; - } - } - } - - function onViewStyleChange(parentItem) { - - var query = getQuery(parentItem); - - var itemsContainer = view.querySelector('#items'); - - if (query.IncludeItemTypes == "Audio") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - - } else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - } - - function reloadItems(parentItem) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(parentItem); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - var html = ''; - var pagingHtml = libraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false - }); - - var i, length; - var elems; - - elems = view.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - var itemsContainer = view.querySelector('#items'); - - if (query.IncludeItemTypes == "Audio") { - - html = listView.getListViewHtml({ - items: result.Items, - playFromHere: true, - action: 'playallfromhere', - smallIcon: true - }); - - } else { - - var posterOptions = { - items: result.Items, - shape: "auto", - centerText: true, - lazy: true - }; - - if (query.IncludeItemTypes == "MusicAlbum") { - posterOptions.overlayText = false; - posterOptions.showParentTitle = true; - posterOptions.showTitle = true; - posterOptions.overlayPlayButton = true; - } - else if (query.IncludeItemTypes == "MusicArtist") { - posterOptions.overlayText = false; - posterOptions.overlayPlayButton = true; - } - else if (query.IncludeItemTypes == "Episode") { - posterOptions.overlayText = false; - posterOptions.showParentTitle = true; - posterOptions.showTitle = true; - posterOptions.overlayPlayButton = true; - } - - // Poster - html = cardBuilder.getCardsHtml(posterOptions); - } - - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(view); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(view); - } - - elems = view.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = view.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - Dashboard.hideLoadingMsg(); - }); - } - - view.addEventListener('click', onListItemClick); - - function getItemPromise() { - - var id = params.genreId || params.studioId || params.artistId || params.personId || params.parentId; - - if (id) { - return ApiClient.getItem(Dashboard.getCurrentUserId(), id); - } - - var name = params.genre; - - if (name) { - return ApiClient.getGenre(name, Dashboard.getCurrentUserId()); - } - - name = params.musicgenre; - - if (name) { - return ApiClient.getMusicGenre(name, Dashboard.getCurrentUserId()); - } - - name = params.gamegenre; - - if (name) { - return ApiClient.getGameGenre(name, Dashboard.getCurrentUserId()); - } - - return null; - } - - view.addEventListener('viewbeforeshow', function (e) { - - var parentPromise = getItemPromise(); - - if (parentPromise) { - parentPromise.then(function (parent) { - LibraryMenu.setTitle(parent.Name); - - onViewStyleChange(parent); - reloadItems(parent); - }); - } - - else { - onViewStyleChange(); - reloadItems(); - } - }); - }; - - -}); \ No newline at end of file +define(["libraryBrowser","listView","cardBuilder","imageLoader","emby-itemscontainer"],function(libraryBrowser,listView,cardBuilder,imageLoader){"use strict";return function(view,params){function addCurrentItemToQuery(query,item){params.parentId&&(query.ParentId=params.parentId),"Person"==item.Type?query.PersonIds=item.Id:"Genre"==item.Type?query.Genres=item.Name:"MusicGenre"==item.Type?query.Genres=item.Name:"GameGenre"==item.Type?query.Genres=item.Name:"Studio"==item.Type?query.StudioIds=item.Id:"MusicArtist"==item.Type?query.ArtistIds=item.Id:query.ParentId=item.Id}function getQuery(parentItem){var key=getSavedQueryKey(),pageData=data[key];if(!pageData){pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",Recursive:"false"!==params.recursive,Fields:"PrimaryImageAspectRatio,SortName,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:libraryBrowser.getDefaultPageSize()}};var type=params.type;type&&(pageData.query.IncludeItemTypes=type,"Audio"==type&&(pageData.query.SortBy="Album,SortName"));var filters=params.filters;type&&(pageData.query.Filters=filters),parentItem&&addCurrentItemToQuery(pageData.query,parentItem),libraryBrowser.loadSavedQueryValues(key,pageData.query)}return pageData.query}function getSavedQueryKey(){return libraryBrowser.getSavedQueryKey()}function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}function onListItemClick(e){var mediaItem=parentWithClass(e.target,"mediaItem");if(mediaItem){var info=libraryBrowser.getListItemInfo(mediaItem);if("Photo"==info.mediaType){var query=getQuery();return require(["scripts/photos"],function(){Photos.startSlideshow(view,query,info.id)}),!1}}}function onViewStyleChange(parentItem){var query=getQuery(parentItem),itemsContainer=view.querySelector("#items");"Audio"==query.IncludeItemTypes?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap"))}function reloadItems(parentItem){Dashboard.showLoadingMsg();var query=getQuery(parentItem);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(view)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(view)}window.scrollTo(0,0);var i,length,elems,html="",pagingHtml=libraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1});for(elems=view.querySelectorAll(".paging"),i=0,length=elems.length;i'; - html += '
'; - - html += "
"; - html += '' + icon + ''; - html += '' + item.Name + ''; - html += "
"; - - html += "
"; - - html += ""; - } - - return html; - } - - function loadlibraryButtons(elem, userId, index) { - - return getUserViews(userId).then(function (items) { - - var html = '
'; - - if (index) { - html += '

' + Globalize.translate('HeaderMyMedia') + '

'; - } - html += '
'; - html += getLibraryButtonsHtml(items); - html += '
'; - - return getAppInfo().then(function (infoHtml) { - - elem.innerHTML = html + infoHtml; - }); - }); - } - - /** - * Returns a random integer between min (inclusive) and max (inclusive) - * Using Math.round() will give you a non-uniform distribution! - */ - function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; - } - - function getAppInfo() { - - var frequency = 86400000; - - if (AppInfo.isNativeApp) { - frequency = 172800000; - } - - var cacheKey = 'lastappinfopresent5'; - var lastDatePresented = parseInt(appSettings.get(cacheKey) || '0'); - - // Don't show the first time, right after installation - if (!lastDatePresented) { - appSettings.set(cacheKey, new Date().getTime()); - return Promise.resolve(''); - } - - if ((new Date().getTime() - lastDatePresented) < frequency) { - return Promise.resolve(''); - } - - return Dashboard.getPluginSecurityInfo().then(function (pluginSecurityInfo) { - - appSettings.set(cacheKey, new Date().getTime()); - - if (pluginSecurityInfo.IsMBSupporter) { - return ''; - } - - var infos = [getPremiereInfo]; - - if (!browserInfo.safari || !AppInfo.isNativeApp) { - infos.push(getTheaterInfo); - } - - return infos[getRandomInt(0, infos.length - 1)](); - }); - } - - function getCard(img, target, shape) { - - shape = shape || 'backdropCard'; - var html = '
'; - - if (target) { - html += ''; - } else { - html += ''; - } - - html += '
'; - - return html; - } - - function getTheaterInfo() { - - var html = ''; - html += '
'; - html += '

Discover Emby Theater

'; - - var nameText = AppInfo.isNativeApp ? 'Emby Theater' : 'Emby Theater'; - html += '

A beautiful app for your TV and large screen tablet. ' + nameText + ' runs on Windows, Xbox One, Raspberry Pi, Samsung Smart TVs, Sony PS4, Web Browsers, and more.

'; - html += '
'; - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater1.png', 'https://emby.media/download'); - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater2.png', 'https://emby.media/download'); - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater3.png', 'https://emby.media/download'); - html += '
'; - html += '
'; - html += '
'; - return html; - } - - function getPremiereInfo() { - - var html = ''; - html += '
'; - html += '

Discover Emby Premiere

'; - - var cardTarget = AppInfo.isNativeApp ? '' : 'https://emby.media/premiere'; - var learnMoreText = AppInfo.isNativeApp ? '' : 'Learn more'; - - html += '

Design beautiful Cover Art, enjoy free access to Emby apps, and more. ' + learnMoreText + '

'; - html += '
'; - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater1.png', cardTarget); - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater2.png', cardTarget); - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater3.png', cardTarget); - html += '
'; - html += '
'; - html += '
'; - return html; - } - - function getUpgradeMobileLayoutsInfo() { - var html = ''; - html += '
'; - html += '

Unlock Improved Layouts with Emby Premiere

'; - - var cardTarget = AppInfo.isNativeApp ? '' : 'https://emby.media/premiere'; - var learnMoreText = AppInfo.isNativeApp ? '' : 'Learn more'; - - html += '

Combined horizontal and vertical swiping, better detail layouts, and more. ' + learnMoreText + '

'; - html += '
'; - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/ms1.png', cardTarget, 'portraitCard'); - html += getCard('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/ms2.png', cardTarget, 'portraitCard'); - html += '
'; - html += '
'; - html += '
'; - return html; - } - - function renderLatestSection(elem, user, parent) { - - var options = { - - Limit: 12, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb", - ParentId: parent.Id - }; - - return ApiClient.getJSON(ApiClient.getUrl('Users/' + user.Id + '/Items/Latest', options)).then(function (items) { - - var html = ''; - - var scrollX = enableScrollX(); - - if (items.length) { - - html += '
'; - html += '

' + Globalize.translate('LatestFromLibrary', parent.Name) + '

'; - html += ''; - html += '
'; - - if (scrollX) { - html += '
'; - } else { - html += '
'; - } - - var viewType = parent.CollectionType; - - var shape = viewType === 'movies' ? - getPortraitShape() : - viewType === 'music' ? - getSquareShape() : - getThumbShape(); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = supportsImageAnalysis && (viewType === 'music' || viewType === 'movies' || viewType === 'tvshows' || !viewType); - - html += cardBuilder.getCardsHtml({ - items: items, - shape: shape, - preferThumb: viewType !== 'movies' && viewType !== 'music', - showUnplayedIndicator: false, - showChildCountIndicator: true, - context: 'home', - overlayText: false, - centerText: !cardLayout, - overlayPlayButton: viewType !== 'photos', - allowBottomPadding: !enableScrollX() && !cardLayout, - cardLayout: cardLayout, - showTitle: viewType === 'music' || !viewType || (cardLayout && (viewType === 'movies' || viewType === 'tvshows')), - showYear: cardLayout && viewType === 'movies', - showSeriesYear: cardLayout && viewType === 'tvshows', - showParentTitle: viewType === 'music' || !viewType || (cardLayout && (viewType === 'tvshows')), - vibrant: supportsImageAnalysis && cardLayout, - lines: 2 - }); - html += '
'; - } - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - }); - } - - function loadRecentlyAdded(elem, user) { - - elem.classList.remove('homePageSection'); - - return getUserViews(user.Id).then(function (items) { - - var excludeViewTypes = ['playlists', 'livetv', 'boxsets', 'channels']; - var excludeItemTypes = ['Channel']; - - for (var i = 0, length = items.length; i < length; i++) { - - var item = items[i]; - - if (user.Configuration.LatestItemsExcludes.indexOf(item.Id) !== -1) { - continue; - } - - if (excludeViewTypes.indexOf(item.CollectionType || []) !== -1) { - continue; - } - - // not implemented yet - if (excludeItemTypes.indexOf(item.Type) !== -1) { - continue; - } - - var frag = document.createElement('div'); - frag.classList.add('homePageSection'); - elem.appendChild(frag); - - renderLatestSection(frag, user, item); - } - }); - } - - function loadLatestChannelMedia(elem, userId) { - - var screenWidth = dom.getWindowSize().innerWidth; - - var options = { - - Limit: screenWidth >= 2400 ? 10 : (screenWidth >= 1600 ? 10 : (screenWidth >= 1440 ? 8 : (screenWidth >= 800 ? 7 : 6))), - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - Filters: "IsUnplayed", - UserId: userId - }; - - return ApiClient.getJSON(ApiClient.getUrl("Channels/Items/Latest", options)).then(function (result) { - - var html = ''; - - if (result.Items.length) { - html += '

' + Globalize.translate('HeaderLatestChannelMedia') + '

'; - html += '
'; - - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: 'auto', - showTitle: true, - centerText: true, - lazy: true, - showDetailsMenu: true, - overlayPlayButton: true - }); - html += '
'; - } - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - }); - } - - function loadLibraryTiles(elem, user, shape) { - - return getUserViews(user.Id).then(function (items) { - - var html = ''; - - html += '
'; - - if (items.length) { - - html += '
'; - html += '

' + Globalize.translate('HeaderMyMedia') + '

'; - html += '
'; - - var scrollX = enableScrollX() && dom.getWindowSize().innerWidth >= 500; - - if (scrollX) { - html += '
'; - } else { - html += '
'; - } - - html += cardBuilder.getCardsHtml({ - items: items, - shape: scrollX ? 'overflowSmallBackdrop' : shape, - showTitle: true, - centerText: true, - overlayText: false, - lazy: true, - transition: false, - allowBottomPadding: !enableScrollX() - }); - html += '
'; - } - - html += '
'; - - return getAppInfo().then(function (infoHtml) { - - elem.innerHTML = html + infoHtml; - imageLoader.lazyChildren(elem); - }); - }); - } - - function loadResume(elem, userId) { - - var screenWidth = dom.getWindowSize().innerWidth; - - var limit; - - if (enableScrollX()) { - - limit = 12; - - } else { - - limit = screenWidth >= 1920 ? 8 : (screenWidth >= 1600 ? 8 : (screenWidth >= 1200 ? 9 : 6)); - limit = Math.min(limit, 5); - } - - var options = { - - SortBy: "DatePlayed", - SortOrder: "Descending", - Filters: "IsResumable", - Limit: limit, - Recursive: true, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - CollapseBoxSetItems: false, - ExcludeLocationTypes: "Virtual", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - EnableTotalRecordCount: false - }; - - return ApiClient.getItems(userId, options).then(function (result) { - - var html = ''; - - if (result.Items.length) { - html += '

' + Globalize.translate('HeaderContinueWatching') + '

'; - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = supportsImageAnalysis; - - html += cardBuilder.getCardsHtml({ - items: result.Items, - preferThumb: true, - shape: getThumbShape(), - overlayText: false, - showTitle: true, - showParentTitle: true, - lazy: true, - showDetailsMenu: true, - overlayPlayButton: true, - context: 'home', - centerText: !cardLayout, - allowBottomPadding: false, - cardLayout: cardLayout, - showYear: true, - lines: 2, - vibrant: cardLayout && supportsImageAnalysis - }); - html += '
'; - } - - elem.innerHTML = html; - - imageLoader.lazyChildren(elem); - }); - } - - function loadNextUp(elem, userId) { - - var query = { - - Limit: enableScrollX() ? 20 : 10, - Fields: "PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo", - UserId: userId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb" - }; - - ApiClient.getNextUpEpisodes(query).then(function (result) { - - var html = ''; - - if (result.Items.length) { - html += '

' + Globalize.translate('HeaderNextUp') + '

'; - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: result.Items, - preferThumb: true, - shape: getThumbShape(), - overlayText: false, - showTitle: true, - showParentTitle: true, - lazy: true, - overlayPlayButton: true, - context: 'home', - centerText: !supportsImageAnalysis, - allowBottomPadding: !enableScrollX(), - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - }); - html += '
'; - } - - elem.innerHTML = html; - - imageLoader.lazyChildren(elem); - }); - } - - function loadLatestChannelItems(elem, userId, options) { - - options = Object.assign(options || {}, { - - UserId: userId, - SupportsLatestItems: true - }); - - return ApiClient.getJSON(ApiClient.getUrl("Channels", options)).then(function (result) { - - var channels = result.Items; - - var channelsHtml = channels.map(function (c) { - - return '
'; - - }).join(''); - - elem.innerHTML = channelsHtml; - - for (var i = 0, length = channels.length; i < length; i++) { - - var channel = channels[i]; - - loadLatestChannelItemsFromChannel(elem, channel, i); - } - - }); - } - - function loadLatestChannelItemsFromChannel(page, channel, index) { - - var screenWidth = dom.getWindowSize().innerWidth; - - var options = { - - Limit: screenWidth >= 1600 ? 10 : (screenWidth >= 1440 ? 5 : (screenWidth >= 800 ? 6 : 6)), - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - Filters: "IsUnplayed", - UserId: Dashboard.getCurrentUserId(), - ChannelIds: channel.Id - }; - - ApiClient.getJSON(ApiClient.getUrl("Channels/Items/Latest", options)).then(function (result) { - - var html = ''; - - if (result.Items.length) { - - html += '
'; - - html += '
'; - var text = Globalize.translate('HeaderLatestFromChannel').replace('{0}', channel.Name); - html += '

' + text + '

'; - html += ''; - html += '
'; - - html += '
'; - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: 'autohome', - defaultShape: 'square', - showTitle: true, - centerText: true, - lazy: true, - showDetailsMenu: true, - overlayPlayButton: true - }); - html += '
'; - html += '
'; - } - - var elem = page.querySelector('#channel' + channel.Id + ''); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - }); - } - - function loadLatestLiveTvRecordings(elem, userId) { - - return ApiClient.getLiveTvRecordings({ - - userId: userId, - limit: 5, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - IsInProgress: false, - EnableTotalRecordCount: false, - IsLibraryItem: false - - }).then(function (result) { - - var html = ''; - - if (result.Items.length) { - - html += '
'; - html += '

' + Globalize.translate('HeaderLatestTvRecordings') + '

'; - html += ''; - html += '
'; - } - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: result.Items, - shape: enableScrollX() ? 'autooverflow' : 'auto', - showTitle: true, - showParentTitle: true, - coverImage: true, - lazy: true, - showDetailsMenu: true, - centerText: !supportsImageAnalysis, - overlayText: false, - overlayPlayButton: true, - allowBottomPadding: !enableScrollX(), - preferThumb: true, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - html += '
'; - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - }); - } - - window.Sections = { - loadRecentlyAdded: loadRecentlyAdded, - loadLatestChannelMedia: loadLatestChannelMedia, - loadLibraryTiles: loadLibraryTiles, - loadResume: loadResume, - loadNextUp: loadNextUp, - loadLatestChannelItems: loadLatestChannelItems, - loadLatestLiveTvRecordings: loadLatestLiveTvRecordings, - loadlibraryButtons: loadlibraryButtons - }; - - return window.Sections; -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","appSettings","components/groupedcards","dom","apphost","imageLoader","scrollStyles","emby-button","paper-icon-button-light","emby-itemscontainer"],function(libraryBrowser,cardBuilder,appSettings,groupedcards,dom,appHost,imageLoader){"use strict";function getUserViews(userId){return ApiClient.getUserViews({},userId).then(function(result){return result.Items})}function enableScrollX(){return browserInfo.mobile}function getSquareShape(){return enableScrollX()?"overflowSquare":"square"}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function getPortraitShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getLibraryButtonsHtml(items){for(var html="",i=0,length=items.length;i',html+='
',html+="
",html+=''+icon+"",html+=''+item.Name+"",html+="
",html+="
",html+=""}return html}function loadlibraryButtons(elem,userId,index){return getUserViews(userId).then(function(items){var html="
";return index&&(html+='

'+Globalize.translate("HeaderMyMedia")+"

"),html+='
',html+=getLibraryButtonsHtml(items),html+="
",getAppInfo().then(function(infoHtml){elem.innerHTML=html+infoHtml})})}function getRandomInt(min,max){return Math.floor(Math.random()*(max-min+1))+min}function getAppInfo(){var frequency=864e5;AppInfo.isNativeApp&&(frequency=1728e5);var cacheKey="lastappinfopresent5",lastDatePresented=parseInt(appSettings.get(cacheKey)||"0");return lastDatePresented?(new Date).getTime()-lastDatePresented
';return html+=target?'':'",html+="
"}function getTheaterInfo(){var html="";html+="
",html+='

Discover Emby Theater

';var nameText=AppInfo.isNativeApp?"Emby Theater":'Emby Theater';return html+="

A beautiful app for your TV and large screen tablet. "+nameText+" runs on Windows, Xbox One, Raspberry Pi, Samsung Smart TVs, Sony PS4, Web Browsers, and more.

",html+='
',html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater1.png","https://emby.media/download"),html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater2.png","https://emby.media/download"),html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater3.png","https://emby.media/download"),html+="
",html+="
",html+="
"}function getPremiereInfo(){var html="";html+="
",html+='

Discover Emby Premiere

';var cardTarget=AppInfo.isNativeApp?"":"https://emby.media/premiere",learnMoreText=AppInfo.isNativeApp?"":'Learn more';return html+="

Design beautiful Cover Art, enjoy free access to Emby apps, and more. "+learnMoreText+"

",html+='
',html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater1.png",cardTarget),html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater2.png",cardTarget),html+=getCard("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/apps/theater3.png",cardTarget),html+="
",html+="
",html+="
"}function renderLatestSection(elem,user,parent){var options={Limit:12,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",ParentId:parent.Id};return ApiClient.getJSON(ApiClient.getUrl("Users/"+user.Id+"/Items/Latest",options)).then(function(items){var html="",scrollX=enableScrollX();if(items.length){html+="
",html+='

'+Globalize.translate("LatestFromLibrary",parent.Name)+"

",html+='",html+="
",html+=scrollX?'
':'
';var viewType=parent.CollectionType,shape="movies"===viewType?getPortraitShape():"music"===viewType?getSquareShape():getThumbShape(),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis&&("music"===viewType||"movies"===viewType||"tvshows"===viewType||!viewType);html+=cardBuilder.getCardsHtml({items:items,shape:shape,preferThumb:"movies"!==viewType&&"music"!==viewType,showUnplayedIndicator:!1,showChildCountIndicator:!0,context:"home",overlayText:!1,centerText:!cardLayout,overlayPlayButton:"photos"!==viewType,allowBottomPadding:!enableScrollX()&&!cardLayout,cardLayout:cardLayout,showTitle:"music"===viewType||!viewType||cardLayout&&("movies"===viewType||"tvshows"===viewType),showYear:cardLayout&&"movies"===viewType,showSeriesYear:cardLayout&&"tvshows"===viewType,showParentTitle:"music"===viewType||!viewType||cardLayout&&"tvshows"===viewType,vibrant:supportsImageAnalysis&&cardLayout,lines:2}),html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadRecentlyAdded(elem,user){return elem.classList.remove("homePageSection"),getUserViews(user.Id).then(function(items){for(var excludeViewTypes=["playlists","livetv","boxsets","channels"],excludeItemTypes=["Channel"],i=0,length=items.length;i=2400?10:screenWidth>=1600?10:screenWidth>=1440?8:screenWidth>=800?7:6,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",Filters:"IsUnplayed",UserId:userId};return ApiClient.getJSON(ApiClient.getUrl("Channels/Items/Latest",options)).then(function(result){var html="";result.Items.length&&(html+='

'+Globalize.translate("HeaderLatestChannelMedia")+"

",html+='
',html+=cardBuilder.getCardsHtml({items:result.Items,shape:"auto",showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0}),html+="
"),elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadLibraryTiles(elem,user,shape){return getUserViews(user.Id).then(function(items){var html="";if(html+="
",items.length){html+="
",html+='

'+Globalize.translate("HeaderMyMedia")+"

",html+="
";var scrollX=enableScrollX()&&dom.getWindowSize().innerWidth>=500;html+=scrollX?'
':'
',html+=cardBuilder.getCardsHtml({items:items,shape:scrollX?"overflowSmallBackdrop":shape,showTitle:!0,centerText:!0,overlayText:!1,lazy:!0,transition:!1,allowBottomPadding:!enableScrollX()}),html+="
"}return html+="
",getAppInfo().then(function(infoHtml){elem.innerHTML=html+infoHtml,imageLoader.lazyChildren(elem)})})}function loadResume(elem,userId){var limit,screenWidth=dom.getWindowSize().innerWidth;enableScrollX()?limit=12:(limit=screenWidth>=1920?8:screenWidth>=1600?8:screenWidth>=1200?9:6,limit=Math.min(limit,5));var options={SortBy:"DatePlayed",SortOrder:"Descending",Filters:"IsResumable",Limit:limit,Recursive:!0,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",CollapseBoxSetItems:!1,ExcludeLocationTypes:"Virtual",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};return ApiClient.getItems(userId,options).then(function(result){var html="";if(result.Items.length){html+='

'+Globalize.translate("HeaderContinueWatching")+"

",html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis;html+=cardBuilder.getCardsHtml({items:result.Items,preferThumb:!0,shape:getThumbShape(),overlayText:!1,showTitle:!0,showParentTitle:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0,context:"home",centerText:!cardLayout,allowBottomPadding:!1,cardLayout:cardLayout,showYear:!0,lines:2,vibrant:cardLayout&&supportsImageAnalysis}),html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadNextUp(elem,userId){var query={Limit:enableScrollX()?20:10,Fields:"PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo",UserId:userId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb"};ApiClient.getNextUpEpisodes(query).then(function(result){var html="";if(result.Items.length){html+='

'+Globalize.translate("HeaderNextUp")+"

",html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:result.Items,preferThumb:!0,shape:getThumbShape(),overlayText:!1,showTitle:!0,showParentTitle:!0,lazy:!0,overlayPlayButton:!0,context:"home",centerText:!supportsImageAnalysis,allowBottomPadding:!enableScrollX(),cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadLatestChannelItems(elem,userId,options){return options=Object.assign(options||{},{UserId:userId,SupportsLatestItems:!0}),ApiClient.getJSON(ApiClient.getUrl("Channels",options)).then(function(result){var channels=result.Items,channelsHtml=channels.map(function(c){return'
'}).join("");elem.innerHTML=channelsHtml;for(var i=0,length=channels.length;i=1600?10:screenWidth>=1440?5:6,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",Filters:"IsUnplayed",UserId:Dashboard.getCurrentUserId(),ChannelIds:channel.Id};ApiClient.getJSON(ApiClient.getUrl("Channels/Items/Latest",options)).then(function(result){var html="";if(result.Items.length){html+='
',html+="
";var text=Globalize.translate("HeaderLatestFromChannel").replace("{0}",channel.Name);html+='

'+text+"

",html+='",html+="
",html+='
',html+=cardBuilder.getCardsHtml({items:result.Items,shape:"autohome",defaultShape:"square",showTitle:!0,centerText:!0,lazy:!0,showDetailsMenu:!0,overlayPlayButton:!0}),html+="
",html+="
"}var elem=page.querySelector("#channel"+channel.Id);elem.innerHTML=html,imageLoader.lazyChildren(elem)})}function loadLatestLiveTvRecordings(elem,userId){return ApiClient.getLiveTvRecordings({userId:userId,limit:5,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",IsInProgress:!1,EnableTotalRecordCount:!1,IsLibraryItem:!1}).then(function(result){var html="";result.Items.length&&(html+="
",html+='

'+Globalize.translate("HeaderLatestTvRecordings")+"

",html+='",html+="
"),html+=enableScrollX()?'
':'
';var supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:result.Items,shape:enableScrollX()?"autooverflow":"auto",showTitle:!0,showParentTitle:!0,coverImage:!0,lazy:!0,showDetailsMenu:!0,centerText:!supportsImageAnalysis,overlayText:!1,overlayPlayButton:!0,allowBottomPadding:!enableScrollX(),preferThumb:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
",elem.innerHTML=html,imageLoader.lazyChildren(elem)})}return window.Sections={loadRecentlyAdded:loadRecentlyAdded,loadLatestChannelMedia:loadLatestChannelMedia,loadLibraryTiles:loadLibraryTiles,loadResume:loadResume,loadNextUp:loadNextUp,loadLatestChannelItems:loadLatestChannelItems,loadLatestLiveTvRecordings:loadLatestLiveTvRecordings,loadlibraryButtons:loadlibraryButtons},window.Sections}); \ No newline at end of file diff --git a/dashboard-ui/scripts/selectserver.js b/dashboard-ui/scripts/selectserver.js index 4418247d84..2dbbdeec01 100644 --- a/dashboard-ui/scripts/selectserver.js +++ b/dashboard-ui/scripts/selectserver.js @@ -1,388 +1 @@ -define(['appSettings', 'paper-icon-button-light'], function (appSettings) { - 'use strict'; - - function updatePageStyle(page) { - - if (getParameterByName('showuser') == '1') { - page.classList.add('libraryPage'); - page.classList.add('noSecondaryNavPage'); - page.classList.remove('standalonePage'); - } else { - page.classList.add('standalonePage'); - page.classList.remove('noSecondaryNavPage'); - page.classList.remove('libraryPage'); - } - } - - function showServerConnectionFailure() { - - alertText(Globalize.translate('MessageUnableToConnectToServer'), Globalize.translate("HeaderConnectionFailure")); - } - - function getServerHtml(server) { - - var html = ''; - - html += '
'; - - html += ''; - - html += ''; - - if (server.Id) { - html += ''; - } - - html += '
'; - - return html; - } - - function renderServers(page, servers) { - - if (servers.length) { - page.querySelector('.noServersMessage').classList.add('hide'); - page.querySelector('.serverList').classList.remove('hide'); - } else { - page.querySelector('.serverList').classList.add('hide'); - page.querySelector('.noServersMessage').classList.remove('hide'); - } - - var html = ''; - - html += servers.map(getServerHtml).join(''); - - page.querySelector('.serverList').innerHTML = html; - } - - function alertText(text, title) { - alertTextWithOptions({ - title: title, - text: text - }); - } - - function alertTextWithOptions(options) { - require(['alert'], function (alert) { - alert(options); - }); - } - - function showGeneralError() { - - Dashboard.hideLoadingMsg(); - alertText(Globalize.translate('DefaultErrorMessage')); - } - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - return function (view, params) { - - var cachedServers; - - function connectToServer(page, server) { - - Dashboard.showLoadingMsg(); - - ConnectionManager.connectToServer(server, { - - enableAutoLogin: appSettings.enableAutoLogin() - - }).then(function (result) { - - Dashboard.hideLoadingMsg(); - - var apiClient = result.ApiClient; - - switch (result.State) { - - case MediaBrowser.ConnectionState.SignedIn: - { - Dashboard.onServerChanged(apiClient.getCurrentUserId(), apiClient.accessToken(), apiClient); - Dashboard.navigate('home.html'); - } - break; - case MediaBrowser.ConnectionState.ServerSignIn: - { - Dashboard.onServerChanged(null, null, apiClient); - Dashboard.navigate('login.html?serverid=' + result.Servers[0].Id); - } - break; - case MediaBrowser.ConnectionState.ServerUpdateNeeded: - { - alertTextWithOptions({ - text: Globalize.translate('core#ServerUpdateNeeded', 'https://emby.media'), - html: Globalize.translate('core#ServerUpdateNeeded', 'https://emby.media') - }); - } - break; - default: - showServerConnectionFailure(); - break; - } - - }); - } - - function acceptInvitation(page, id) { - - Dashboard.showLoadingMsg(); - - // Add/Update connect info - ConnectionManager.acceptServer(id).then(function () { - - Dashboard.hideLoadingMsg(); - loadPage(page); - - }, function () { - - showGeneralError(); - }); - } - - function deleteServer(page, serverId) { - - Dashboard.showLoadingMsg(); - - // Add/Update connect info - ConnectionManager.deleteServer(serverId).then(function () { - - Dashboard.hideLoadingMsg(); - - loadPage(page); - - }, function () { - - showGeneralError(); - - }); - } - - function rejectInvitation(page, id) { - - Dashboard.showLoadingMsg(); - - // Add/Update connect info - ConnectionManager.rejectServer(id).then(function () { - - Dashboard.hideLoadingMsg(); - - loadPage(page); - - }, function () { - - showGeneralError(); - - }); - } - - function showServerMenu(elem) { - - var card = parentWithClass(elem, 'serverItem'); - var page = parentWithClass(elem, 'page'); - var serverId = card.getAttribute('data-id'); - - var menuItems = []; - - menuItems.push({ - name: Globalize.translate('ButtonDelete'), - id: 'delete' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: elem, - callback: function (id) { - - switch (id) { - - case 'delete': - deleteServer(page, serverId); - break; - default: - break; - } - } - }); - - }); - } - - function showPendingInviteMenu(elem) { - - var card = parentWithClass(elem, 'inviteItem'); - var page = parentWithClass(elem, 'page'); - var invitationId = card.getAttribute('data-id'); - - var menuItems = []; - - menuItems.push({ - name: Globalize.translate('ButtonAccept'), - id: 'accept' - }); - - menuItems.push({ - name: Globalize.translate('ButtonReject'), - id: 'reject' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: elem, - callback: function (id) { - - switch (id) { - - case 'accept': - acceptInvitation(page, invitationId); - break; - case 'reject': - rejectInvitation(page, invitationId); - break; - default: - break; - } - } - }); - - }); - } - - function getPendingInviteHtml(invite) { - - var html = ''; - - html += '
'; - - html += ''; - - html += '
'; - - html += '
'; - html += invite.Name; - html += '
'; - - html += '
'; - - html += ''; - - html += '
'; - - return html; - } - - function renderInvitations(page, list) { - - if (list.length) { - page.querySelector('.invitationSection').classList.remove('hide'); - } else { - page.querySelector('.invitationSection').classList.add('hide'); - } - - var html = list.map(getPendingInviteHtml).join(''); - - page.querySelector('.invitationList').innerHTML = html; - } - - function loadInvitations(page) { - - if (ConnectionManager.isLoggedIntoConnect()) { - - ConnectionManager.getUserInvitations().then(function (list) { - - renderInvitations(page, list); - - }); - - } else { - - renderInvitations(page, []); - } - - } - - function loadPage(page) { - - Dashboard.showLoadingMsg(); - - ConnectionManager.getAvailableServers().then(function (servers) { - - servers = servers.slice(0); - cachedServers = servers; - - renderServers(page, servers); - - Dashboard.hideLoadingMsg(); - }); - - loadInvitations(page); - - if (ConnectionManager.isLoggedIntoConnect()) { - page.querySelector('.connectLogin').classList.add('hide'); - } else { - page.querySelector('.connectLogin').classList.remove('hide'); - } - } - - view.querySelector('.invitationList').addEventListener('click', function (e) { - - var btnInviteMenu = parentWithClass(e.target, 'btnInviteMenu'); - if (btnInviteMenu) { - showPendingInviteMenu(btnInviteMenu); - } - }); - view.querySelector('.serverList').addEventListener('click', function (e) { - - var lnkServer = parentWithClass(e.target, 'lnkServer'); - if (lnkServer) { - var item = parentWithClass(lnkServer, 'serverItem'); - var id = item.getAttribute('data-id'); - - var server = cachedServers.filter(function (s) { - return s.Id == id; - })[0]; - - connectToServer(view, server); - } - - var btnServerMenu = parentWithClass(e.target, 'btnServerMenu'); - if (btnServerMenu) { - showServerMenu(btnServerMenu); - } - }); - - view.addEventListener('viewbeforeshow', function () { - updatePageStyle(this); - }); - view.addEventListener('viewshow', function () { - loadPage(this); - }); - }; -}); \ No newline at end of file +define(["appSettings","paper-icon-button-light"],function(appSettings){"use strict";function updatePageStyle(page){"1"==getParameterByName("showuser")?(page.classList.add("libraryPage"),page.classList.add("noSecondaryNavPage"),page.classList.remove("standalonePage")):(page.classList.add("standalonePage"),page.classList.remove("noSecondaryNavPage"),page.classList.remove("libraryPage"))}function showServerConnectionFailure(){alertText(Globalize.translate("MessageUnableToConnectToServer"),Globalize.translate("HeaderConnectionFailure"))}function getServerHtml(server){var html="";return html+='
',html+='',html+='",server.Id&&(html+='"),html+="
"}function renderServers(page,servers){servers.length?(page.querySelector(".noServersMessage").classList.add("hide"),page.querySelector(".serverList").classList.remove("hide")):(page.querySelector(".serverList").classList.add("hide"),page.querySelector(".noServersMessage").classList.remove("hide"));var html="";html+=servers.map(getServerHtml).join(""),page.querySelector(".serverList").innerHTML=html}function alertText(text,title){alertTextWithOptions({title:title,text:text})}function alertTextWithOptions(options){require(["alert"],function(alert){alert(options)})}function showGeneralError(){Dashboard.hideLoadingMsg(),alertText(Globalize.translate("DefaultErrorMessage"))}function parentWithClass(elem,className){for(;!elem.classList||!elem.classList.contains(className);)if(elem=elem.parentNode,!elem)return null;return elem}return function(view,params){function connectToServer(page,server){Dashboard.showLoadingMsg(),ConnectionManager.connectToServer(server,{enableAutoLogin:appSettings.enableAutoLogin()}).then(function(result){Dashboard.hideLoadingMsg();var apiClient=result.ApiClient;switch(result.State){case MediaBrowser.ConnectionState.SignedIn:Dashboard.onServerChanged(apiClient.getCurrentUserId(),apiClient.accessToken(),apiClient),Dashboard.navigate("home.html");break;case MediaBrowser.ConnectionState.ServerSignIn:Dashboard.onServerChanged(null,null,apiClient),Dashboard.navigate("login.html?serverid="+result.Servers[0].Id);break;case MediaBrowser.ConnectionState.ServerUpdateNeeded:alertTextWithOptions({text:Globalize.translate("core#ServerUpdateNeeded","https://emby.media"),html:Globalize.translate("core#ServerUpdateNeeded",'https://emby.media')});break;default:showServerConnectionFailure()}})}function acceptInvitation(page,id){Dashboard.showLoadingMsg(),ConnectionManager.acceptServer(id).then(function(){Dashboard.hideLoadingMsg(),loadPage(page)},function(){showGeneralError()})}function deleteServer(page,serverId){Dashboard.showLoadingMsg(),ConnectionManager.deleteServer(serverId).then(function(){Dashboard.hideLoadingMsg(),loadPage(page)},function(){showGeneralError()})}function rejectInvitation(page,id){Dashboard.showLoadingMsg(),ConnectionManager.rejectServer(id).then(function(){Dashboard.hideLoadingMsg(),loadPage(page)},function(){showGeneralError()})}function showServerMenu(elem){var card=parentWithClass(elem,"serverItem"),page=parentWithClass(elem,"page"),serverId=card.getAttribute("data-id"),menuItems=[];menuItems.push({name:Globalize.translate("ButtonDelete"),id:"delete"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:elem,callback:function(id){switch(id){case"delete":deleteServer(page,serverId)}}})})}function showPendingInviteMenu(elem){var card=parentWithClass(elem,"inviteItem"),page=parentWithClass(elem,"page"),invitationId=card.getAttribute("data-id"),menuItems=[];menuItems.push({name:Globalize.translate("ButtonAccept"),id:"accept"}),menuItems.push({name:Globalize.translate("ButtonReject"),id:"reject"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:elem,callback:function(id){switch(id){case"accept":acceptInvitation(page,invitationId);break;case"reject":rejectInvitation(page,invitationId)}}})})}function getPendingInviteHtml(invite){var html="";return html+='
',html+='',html+='
',html+="
",html+=invite.Name,html+="
",html+="
",html+='",html+="
"}function renderInvitations(page,list){list.length?page.querySelector(".invitationSection").classList.remove("hide"):page.querySelector(".invitationSection").classList.add("hide");var html=list.map(getPendingInviteHtml).join("");page.querySelector(".invitationList").innerHTML=html}function loadInvitations(page){ConnectionManager.isLoggedIntoConnect()?ConnectionManager.getUserInvitations().then(function(list){renderInvitations(page,list)}):renderInvitations(page,[])}function loadPage(page){Dashboard.showLoadingMsg(),ConnectionManager.getAvailableServers().then(function(servers){servers=servers.slice(0),cachedServers=servers,renderServers(page,servers),Dashboard.hideLoadingMsg()}),loadInvitations(page),ConnectionManager.isLoggedIntoConnect()?page.querySelector(".connectLogin").classList.add("hide"):page.querySelector(".connectLogin").classList.remove("hide")}var cachedServers;view.querySelector(".invitationList").addEventListener("click",function(e){var btnInviteMenu=parentWithClass(e.target,"btnInviteMenu");btnInviteMenu&&showPendingInviteMenu(btnInviteMenu)}),view.querySelector(".serverList").addEventListener("click",function(e){var lnkServer=parentWithClass(e.target,"lnkServer");if(lnkServer){var item=parentWithClass(lnkServer,"serverItem"),id=item.getAttribute("data-id"),server=cachedServers.filter(function(s){return s.Id==id})[0];connectToServer(view,server)}var btnServerMenu=parentWithClass(e.target,"btnServerMenu");btnServerMenu&&showServerMenu(btnServerMenu)}),view.addEventListener("viewbeforeshow",function(){updatePageStyle(this)}),view.addEventListener("viewshow",function(){loadPage(this)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/serversecurity.js b/dashboard-ui/scripts/serversecurity.js index 44256a7a73..d0cc2a1ddc 100644 --- a/dashboard-ui/scripts/serversecurity.js +++ b/dashboard-ui/scripts/serversecurity.js @@ -1,158 +1 @@ -define(['datetime', 'jQuery'], function (datetime, $) { - 'use strict'; - - function revoke(page, key) { - - require(['confirm'], function (confirm) { - - confirm(Globalize.translate('MessageConfirmRevokeApiKey'), Globalize.translate('HeaderConfirmRevokeApiKey')).then(function () { - Dashboard.showLoadingMsg(); - - ApiClient.ajax({ - type: "DELETE", - url: ApiClient.getUrl('Auth/Keys/' + key) - - }).then(function () { - - loadData(page); - }); - }); - - }); - } - - function renderKeys(page, keys, users) { - - var rows = keys.map(function (item) { - - var html = ''; - - html += ''; - - html += ''; - html += ''; - html += ''; - - html += ''; - html += (item.AccessToken); - html += ''; - - html += ''; - html += (item.AppName || ''); - html += ''; - - html += ''; - html += (item.DeviceName || ''); - html += ''; - - html += ''; - - var user = users.filter(function (u) { - - return u.Id == item.UserId; - })[0]; - - if (user) { - html += user.Name; - } - - html += ''; - - html += ''; - - var date = datetime.parseISO8601Date(item.DateCreated, true); - - html += datetime.toLocaleDateString(date) + ' ' + datetime.getDisplayTime(date); - - html += ''; - - html += ''; - - return html; - - }).join(''); - - var elem = $('.resultBody', page).html(rows).parents('.tblApiKeys').table("refresh").trigger('create'); - - $('.btnRevoke', elem).on('click', function () { - - revoke(page, this.getAttribute('data-token')); - }); - - Dashboard.hideLoadingMsg(); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getUsers().then(function (users) { - - ApiClient.getJSON(ApiClient.getUrl('Auth/Keys')).then(function (result) { - - renderKeys(page, result.Items, users); - }); - }); - } - - function showNewKeyPrompt(page) { - require(['prompt'], function (prompt) { - - // HeaderNewApiKeyHelp not used - - prompt({ - title: Globalize.translate('HeaderNewApiKey'), - label: Globalize.translate('LabelAppName'), - description: Globalize.translate('LabelAppNameExample') - - }).then(function (value) { - - ApiClient.ajax({ - type: "POST", - url: ApiClient.getUrl('Auth/Keys', { - - App: value - - }) - - }).then(function () { - - loadData(page); - }); - }); - - }); - } - - function getTabs() { - return [ - { - href: 'dashboardhosting.html', - name: Globalize.translate('TabHosting') - }, - { - href: 'serversecurity.html', - name: Globalize.translate('TabSecurity') - }]; - } - - pageIdOn('pageinit', "serverSecurityPage", function () { - - var page = this; - - $('.btnNewKey', page).on('click', function () { - - showNewKeyPrompt(page); - - }); - - }); - pageIdOn('pagebeforeshow', "serverSecurityPage", function () { - - LibraryMenu.setTabs('adminadvanced', 1, getTabs); - var page = this; - - loadData(page); - }); - -}); \ No newline at end of file +define(["datetime","jQuery"],function(datetime,$){"use strict";function revoke(page,key){require(["confirm"],function(confirm){confirm(Globalize.translate("MessageConfirmRevokeApiKey"),Globalize.translate("HeaderConfirmRevokeApiKey")).then(function(){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Auth/Keys/"+key)}).then(function(){loadData(page)})})})}function renderKeys(page,keys,users){var rows=keys.map(function(item){var html="";html+="",html+="",html+='",html+="",html+='',html+=item.AccessToken,html+="",html+='',html+=item.AppName||"",html+="",html+='',html+=item.DeviceName||"",html+="",html+='';var user=users.filter(function(u){return u.Id==item.UserId})[0];user&&(html+=user.Name),html+="",html+='';var date=datetime.parseISO8601Date(item.DateCreated,!0);return html+=datetime.toLocaleDateString(date)+" "+datetime.getDisplayTime(date),html+="",html+=""}).join(""),elem=$(".resultBody",page).html(rows).parents(".tblApiKeys").table("refresh").trigger("create");$(".btnRevoke",elem).on("click",function(){revoke(page,this.getAttribute("data-token"))}),Dashboard.hideLoadingMsg()}function loadData(page){Dashboard.showLoadingMsg(),ApiClient.getUsers().then(function(users){ApiClient.getJSON(ApiClient.getUrl("Auth/Keys")).then(function(result){renderKeys(page,result.Items,users)})})}function showNewKeyPrompt(page){require(["prompt"],function(prompt){prompt({title:Globalize.translate("HeaderNewApiKey"),label:Globalize.translate("LabelAppName"),description:Globalize.translate("LabelAppNameExample")}).then(function(value){ApiClient.ajax({type:"POST",url:ApiClient.getUrl("Auth/Keys",{App:value})}).then(function(){loadData(page)})})})}function getTabs(){return[{href:"dashboardhosting.html",name:Globalize.translate("TabHosting")},{href:"serversecurity.html",name:Globalize.translate("TabSecurity")}]}pageIdOn("pageinit","serverSecurityPage",function(){var page=this;$(".btnNewKey",page).on("click",function(){showNewKeyPrompt(page)})}),pageIdOn("pagebeforeshow","serverSecurityPage",function(){LibraryMenu.setTabs("adminadvanced",1,getTabs);var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/shared.js b/dashboard-ui/scripts/shared.js index c81e8c8bcb..e5e1afdce1 100644 --- a/dashboard-ui/scripts/shared.js +++ b/dashboard-ui/scripts/shared.js @@ -1,91 +1 @@ -define(['jQuery', 'libraryBrowser', 'imageLoader', 'indicators'], function ($, libraryBrowser, imageLoader, indicators) { - 'use strict'; - - var currentItem; - - function reload(page) { - - var id = getParameterByName('id'); - - Dashboard.showLoadingMsg(); - - ApiClient.getJSON(ApiClient.getUrl('Social/Shares/Public/' + id + '/Item')).then(function (item) { - - reloadFromItem(page, item); - }); - } - - function reloadFromItem(page, item) { - - currentItem = item; - - libraryBrowser.renderName(item, $('.itemName', page)[0], false); - libraryBrowser.renderParentName(item, $('.parentName', page)[0]); - libraryBrowser.renderDetailPageBackdrop(page, item, imageLoader); - - renderImage(page, item); - - setInitialCollapsibleState(page, item); - ItemDetailPage.renderDetails(page, item, null, true); - - Dashboard.hideLoadingMsg(); - } - - function setInitialCollapsibleState(page, item) { - - $('.collectionItems', page).empty(); - - if (item.MediaSources && item.MediaSources.length) { - ItemDetailPage.renderMediaSources(page, null, item); - } - - var chapters = item.Chapters || []; - - if (!chapters.length) { - $('#scenesCollapsible', page).hide(); - } else { - $('#scenesCollapsible', page).show(); - ItemDetailPage.renderScenes(page, item, null, 3, true); - } - - if (!item.People || !item.People.length) { - $('#castCollapsible', page).hide(); - } else { - $('#castCollapsible', page).show(); - ItemDetailPage.renderCast(page, item, null, 6, true); - } - - ItemDetailPage.renderCriticReviews(page, item, 1); - } - - function renderImage(page, item) { - libraryBrowser.renderDetailImage(page.querySelector('.detailImageContainer'), item, false, null, imageLoader, indicators); - } - - $(document).on('pageinit', "#publicSharedItemPage", function () { - - var page = this; - - $(page).on("click", ".moreScenes", function () { - - ItemDetailPage.renderScenes(page, currentItem, null, null, true); - - }).on("click", ".morePeople", function () { - - ItemDetailPage.renderCast(page, currentItem, null, null, true); - - }).on("click", ".moreCriticReviews", function () { - - ItemDetailPage.renderCriticReviews(page, currentItem); - - }); - - }).on('pageshow', "#publicSharedItemPage", function () { - - var page = this; - - reload(page); - - }); - -}); \ No newline at end of file +define(["jQuery","libraryBrowser","imageLoader","indicators"],function($,libraryBrowser,imageLoader,indicators){"use strict";function reload(page){var id=getParameterByName("id");Dashboard.showLoadingMsg(),ApiClient.getJSON(ApiClient.getUrl("Social/Shares/Public/"+id+"/Item")).then(function(item){reloadFromItem(page,item)})}function reloadFromItem(page,item){currentItem=item,libraryBrowser.renderName(item,$(".itemName",page)[0],!1),libraryBrowser.renderParentName(item,$(".parentName",page)[0]),libraryBrowser.renderDetailPageBackdrop(page,item,imageLoader),renderImage(page,item),setInitialCollapsibleState(page,item),ItemDetailPage.renderDetails(page,item,null,!0),Dashboard.hideLoadingMsg()}function setInitialCollapsibleState(page,item){$(".collectionItems",page).empty(),item.MediaSources&&item.MediaSources.length&&ItemDetailPage.renderMediaSources(page,null,item);var chapters=item.Chapters||[];chapters.length?($("#scenesCollapsible",page).show(),ItemDetailPage.renderScenes(page,item,null,3,!0)):$("#scenesCollapsible",page).hide(),item.People&&item.People.length?($("#castCollapsible",page).show(),ItemDetailPage.renderCast(page,item,null,6,!0)):$("#castCollapsible",page).hide(),ItemDetailPage.renderCriticReviews(page,item,1)}function renderImage(page,item){libraryBrowser.renderDetailImage(page.querySelector(".detailImageContainer"),item,!1,null,imageLoader,indicators)}var currentItem;$(document).on("pageinit","#publicSharedItemPage",function(){var page=this;$(page).on("click",".moreScenes",function(){ItemDetailPage.renderScenes(page,currentItem,null,null,!0)}).on("click",".morePeople",function(){ItemDetailPage.renderCast(page,currentItem,null,null,!0)}).on("click",".moreCriticReviews",function(){ItemDetailPage.renderCriticReviews(page,currentItem)})}).on("pageshow","#publicSharedItemPage",function(){var page=this;reload(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/site.js b/dashboard-ui/scripts/site.js index 755f2a7fe4..d7c076db63 100644 --- a/dashboard-ui/scripts/site.js +++ b/dashboard-ui/scripts/site.js @@ -1,2684 +1,2 @@ -function getWindowLocationSearch(win) { - 'use strict'; - - var search = (win || window).location.search; - - if (!search) { - - var index = window.location.href.indexOf('?'); - if (index != -1) { - search = window.location.href.substring(index); - } - } - - return search || ''; -} - -function getParameterByName(name, url) { - 'use strict'; - - name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); - var regexS = "[\\?&]" + name + "=([^&#]*)"; - var regex = new RegExp(regexS, "i"); - - var results = regex.exec(url || getWindowLocationSearch()); - if (results == null) - return ""; - else - return decodeURIComponent(results[1].replace(/\+/g, " ")); -} - -var Dashboard = { - - isConnectMode: function () { - - if (AppInfo.isNativeApp) { - return true; - } - - var url = window.location.href.toLowerCase(); - - return url.indexOf('mediabrowser.tv') != -1 || - url.indexOf('emby.media') != -1; - }, - - isRunningInCordova: function () { - - return window.appMode == 'cordova'; - }, - - onRequestFail: function (e, data) { - - if (data.status == 401) { - - if (data.errorCode == "ParentalControl") { - - var currentView = ViewManager.currentView(); - // Bounce to the login screen, but not if a password entry fails, obviously - if (currentView && !currentView.classList.contains('.standalonePage')) { - - Dashboard.alert({ - message: Globalize.translate('MessageLoggedOutParentalControl'), - callback: function () { - Dashboard.logout(false); - } - }); - } - - } - } - }, - - getCurrentUser: function () { - - return window.ApiClient.getCurrentUser(); - }, - - serverAddress: function () { - - if (Dashboard.isConnectMode()) { - var apiClient = window.ApiClient; - - if (apiClient) { - return apiClient.serverAddress(); - } - - return null; - } - - // Try to get the server address from the browser url - // This will preserve protocol, hostname, port and subdirectory - var urlLower = window.location.href.toLowerCase(); - var index = urlLower.lastIndexOf('/web'); - - if (index != -1) { - return urlLower.substring(0, index); - } - - // If the above failed, just piece it together manually - var loc = window.location; - - var address = loc.protocol + '//' + loc.hostname; - - if (loc.port) { - address += ':' + loc.port; - } - - return address; - }, - - getCurrentUserId: function () { - - var apiClient = window.ApiClient; - - if (apiClient) { - return apiClient.getCurrentUserId(); - } - - return null; - }, - - onServerChanged: function (userId, accessToken, apiClient) { - - apiClient = apiClient || window.ApiClient; - - window.ApiClient = apiClient; - }, - - logout: function (logoutWithServer) { - - function onLogoutDone() { - - var loginPage; - - if (Dashboard.isConnectMode()) { - loginPage = 'connectlogin.html'; - window.ApiClient = null; - } else { - loginPage = 'login.html'; - } - Dashboard.navigate(loginPage); - } - - if (logoutWithServer === false) { - onLogoutDone(); - } else { - ConnectionManager.logout().then(onLogoutDone); - } - }, - - getConfigurationPageUrl: function (name) { - return "configurationpage?name=" + encodeURIComponent(name); - }, - - navigate: function (url, preserveQueryString) { - - if (!url) { - throw new Error('url cannot be null or empty'); - } - - var queryString = getWindowLocationSearch(); - if (preserveQueryString && queryString) { - url += queryString; - } - - return Emby.Page.show(url); - }, - - showLoadingMsg: function () { - - Dashboard.loadingVisible = true; - - require(['loading'], function (loading) { - if (Dashboard.loadingVisible) { - loading.show(); - } else { - loading.hide(); - } - }); - }, - - hideLoadingMsg: function () { - - Dashboard.loadingVisible = false; - - require(['loading'], function (loading) { - if (Dashboard.loadingVisible) { - loading.show(); - } else { - loading.hide(); - } - }); - }, - - processPluginConfigurationUpdateResult: function () { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('MessageSettingsSaved')); - }); - }, - - processServerConfigurationUpdateResult: function (result) { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('MessageSettingsSaved')); - }); - }, - - processErrorResponse: function (response) { - - Dashboard.hideLoadingMsg(); - - var status = '' + response.status; - - if (response.statusText) { - status = response.statusText; - } - - Dashboard.alert({ - title: status, - message: response.headers ? response.headers.get('X-Application-Error-Code') : null - }); - }, - - alert: function (options) { - - if (typeof options == "string") { - - require(['toast'], function (toast) { - - toast({ - text: options - }); - - }); - - return; - } - - require(['alert'], function (alert) { - alert({ - title: options.title || Globalize.translate('HeaderAlert'), - text: options.message - }).then(options.callback || function () { }); - }); - }, - - restartServer: function () { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return; - } - - Dashboard.suppressAjaxErrors = true; - Dashboard.showLoadingMsg(); - - apiClient.restartServer().then(function () { - - setTimeout(function () { - Dashboard.reloadPageWhenServerAvailable(); - }, 250); - - }, function () { - Dashboard.suppressAjaxErrors = false; - }); - }, - - reloadPageWhenServerAvailable: function (retryCount) { - - var apiClient = window.ApiClient; - - if (!apiClient) { - return; - } - - // Don't use apiclient method because we don't want it reporting authentication under the old version - apiClient.getJSON(apiClient.getUrl("System/Info")).then(function (info) { - - // If this is back to false, the restart completed - if (!info.HasPendingRestart) { - window.location.reload(true); - } else { - Dashboard.retryReload(retryCount); - } - - }, function () { - Dashboard.retryReload(retryCount); - }); - }, - - retryReload: function (retryCount) { - setTimeout(function () { - - retryCount = retryCount || 0; - retryCount++; - - if (retryCount < 10) { - Dashboard.reloadPageWhenServerAvailable(retryCount); - } else { - Dashboard.suppressAjaxErrors = false; - } - }, 500); - }, - - showUserFlyout: function () { - - Dashboard.navigate('mypreferencesmenu.html'); - }, - - getPluginSecurityInfo: function () { - - var apiClient = window.ApiClient; - - if (!apiClient) { - - return Promise.reject(); - } - - var cachedInfo = Dashboard.pluginSecurityInfo; - if (cachedInfo) { - return Promise.resolve(cachedInfo); - } - - return apiClient.ajax({ - type: "GET", - url: apiClient.getUrl("Plugins/SecurityInfo"), - dataType: 'json', - - error: function () { - // Don't show normal dashboard errors - } - - }).then(function (result) { - Dashboard.pluginSecurityInfo = result; - return result; - }); - }, - - resetPluginSecurityInfo: function () { - Dashboard.pluginSecurityInfo = null; - }, - - ensureHeader: function (page) { - - if (page.classList.contains('standalonePage') && !page.classList.contains('noHeaderPage')) { - - Dashboard.renderHeader(page); - } - }, - - renderHeader: function (page) { - - var header = page.querySelector('.header'); - - if (!header) { - var headerHtml = ''; - - headerHtml += ''; - page.insertAdjacentHTML('afterbegin', headerHtml); - } - }, - - getToolsLinkHtml: function (item) { - - var menuHtml = ''; - var pageIds = item.pageIds ? item.pageIds.join(',') : ''; - pageIds = pageIds ? (' data-pageids="' + pageIds + '"') : ''; - menuHtml += ''; - - menuHtml += ''; - menuHtml += item.name; - menuHtml += ''; - menuHtml += ''; - return menuHtml; - }, - - getToolsMenuHtml: function (page) { - - var items = Dashboard.getToolsMenuLinks(page); - - var i, length, item; - var menuHtml = ''; - menuHtml += '
'; - for (i = 0, length = items.length; i < length; i++) { - - item = items[i]; - - if (item.divider) { - menuHtml += "
"; - } - - if (item.href) { - - menuHtml += Dashboard.getToolsLinkHtml(item); - } else { - - menuHtml += '
'; - menuHtml += item.name; - menuHtml += '
'; - } - } - menuHtml += '
'; - - return menuHtml; - }, - - getToolsMenuLinks: function () { - - return [{ - name: Globalize.translate('TabServer') - }, { - name: Globalize.translate('TabDashboard'), - href: "dashboard.html", - pageIds: ['dashboardPage'], - icon: 'dashboard' - }, { - name: Globalize.translate('TabSettings'), - href: "dashboardgeneral.html", - pageIds: ['dashboardGeneralPage'], - icon: 'settings' - }, { - name: Globalize.translate('TabDevices'), - href: "devices.html", - pageIds: ['devicesPage', 'devicePage'], - icon: 'tablet' - }, { - name: Globalize.translate('TabUsers'), - href: "userprofiles.html", - pageIds: ['userProfilesPage', 'newUserPage', 'editUserPage', 'userLibraryAccessPage', 'userParentalControlPage', 'userPasswordPage'], - icon: 'people' - }, { - name: 'Emby Premiere', - href: "supporterkey.html", - pageIds: ['supporterKeyPage'], - icon: 'star' - }, { - divider: true, - name: Globalize.translate('TabLibrary'), - href: "library.html", - pageIds: ['mediaLibraryPage', 'librarySettingsPage', 'libraryDisplayPage', 'metadataImagesConfigurationPage', 'metadataNfoPage'], - icon: 'folder', - color: '#38c' - }, { - name: Globalize.translate('TabSubtitles'), - href: "metadatasubtitles.html", - pageIds: ['metadataSubtitlesPage'], - icon: 'closed_caption' - }, { - name: Globalize.translate('TabPlayback'), - icon: 'play_circle_filled', - color: '#E5342E', - href: "cinemamodeconfiguration.html", - pageIds: ['cinemaModeConfigurationPage', 'playbackConfigurationPage', 'streamingSettingsPage'] - }, { - name: Globalize.translate('TabSync'), - icon: 'sync', - href: "syncactivity.html", - pageIds: ['syncActivityPage', 'syncJobPage', 'devicesUploadPage', 'syncSettingsPage'], - color: '#009688' - }, { - name: Globalize.translate('TabTranscoding'), - icon: 'transform', - href: "encodingsettings.html", - pageIds: ['encodingSettingsPage'] - }, { - divider: true, - name: Globalize.translate('TabExtras') - }, { - name: Globalize.translate('TabAutoOrganize'), - color: '#01C0DD', - href: "autoorganizelog.html", - pageIds: ['libraryFileOrganizerPage', 'libraryFileOrganizerSmartMatchPage', 'libraryFileOrganizerLogPage'], - icon: 'folder' - }, { - name: Globalize.translate('DLNA'), - href: "dlnasettings.html", - pageIds: ['dlnaSettingsPage', 'dlnaProfilesPage', 'dlnaProfilePage'], - icon: 'settings' - }, { - name: Globalize.translate('TabLiveTV'), - href: "livetvstatus.html", - pageIds: ['liveTvStatusPage', 'liveTvSettingsPage', 'liveTvTunerProviderHdHomerunPage', 'liveTvTunerProviderM3UPage', 'liveTvTunerProviderSatPage'], - icon: 'dvr' - }, { - name: Globalize.translate('TabNotifications'), - icon: 'notifications', - color: 'brown', - href: "notificationsettings.html", - pageIds: ['notificationSettingsPage', 'notificationSettingPage'] - }, { - name: Globalize.translate('TabPlugins'), - icon: 'add_shopping_cart', - color: '#9D22B1', - href: "plugins.html", - pageIds: ['pluginsPage', 'pluginCatalogPage'] - }, { - divider: true, - name: Globalize.translate('TabExpert') - }, { - name: Globalize.translate('TabAdvanced'), - icon: 'settings', - href: "dashboardhosting.html", - color: '#F16834', - pageIds: ['dashboardHostingPage', 'serverSecurityPage'] - }, { - name: Globalize.translate('TabLogs'), - href: "log.html", - pageIds: ['logPage'], - icon: 'folder_open' - }, { - name: Globalize.translate('TabScheduledTasks'), - href: "scheduledtasks.html", - pageIds: ['scheduledTasksPage', 'scheduledTaskPage'], - icon: 'schedule' - }, { - name: Globalize.translate('MetadataManager'), - href: "edititemmetadata.html", - pageIds: [], - icon: 'mode_edit' - }, { - name: Globalize.translate('ButtonReports'), - href: "reports.html", - pageIds: [], - icon: 'insert_chart' - }]; - - }, - - getSupportedRemoteCommands: function () { - - // Full list - // https://github.com/MediaBrowser/MediaBrowser/blob/master/MediaBrowser.Model/Session/GeneralCommand.cs - return [ - "GoHome", - "GoToSettings", - "VolumeUp", - "VolumeDown", - "Mute", - "Unmute", - "ToggleMute", - "SetVolume", - "SetAudioStreamIndex", - "SetSubtitleStreamIndex", - "DisplayContent", - "GoToSearch", - "DisplayMessage", - "SetRepeatMode" - ]; - - }, - - capabilities: function () { - - var caps = { - PlayableMediaTypes: ['Audio', 'Video'], - - SupportedCommands: Dashboard.getSupportedRemoteCommands(), - - // Need to use this rather than AppInfo.isNativeApp because the property isn't set yet at the time we call this - SupportsPersistentIdentifier: Dashboard.isRunningInCordova(), - - SupportsMediaControl: true, - SupportedLiveMediaTypes: ['Audio', 'Video'] - }; - - if (Dashboard.isRunningInCordova() && !browserInfo.safari) { - caps.SupportsSync = true; - caps.SupportsContentUploading = true; - } - - return caps; - }, - - normalizeImageOptions: function (options) { - - if (AppInfo.hasLowImageBandwidth) { - - options.enableImageEnhancers = false; - } - - var setQuality; - if (options.maxWidth) { - setQuality = true; - } - - if (options.width) { - setQuality = true; - } - - if (options.maxHeight) { - setQuality = true; - } - - if (options.height) { - setQuality = true; - } - - if (setQuality) { - var quality = 90; - - var isBackdrop = (options.type || '').toLowerCase() == 'backdrop'; - if (isBackdrop) { - quality -= 10; - } - - if (browserInfo.slow) { - quality -= 40; - } - - if (AppInfo.hasLowImageBandwidth && !isBackdrop) { - - quality -= 10; - } - options.quality = quality; - } - } -}; - -var AppInfo = {}; - -(function () { - 'use strict'; - - function setAppInfo() { - - var isCordova = Dashboard.isRunningInCordova(); - - AppInfo.enableHomeTabs = true; - AppInfo.enableAutoSave = browserInfo.touch; - - AppInfo.enableAppStorePolicy = isCordova; - - var isIOS = browserInfo.ipad || browserInfo.iphone; - var isAndroid = browserInfo.android; - - if (isIOS) { - - AppInfo.hasLowImageBandwidth = true; - } - - if (isCordova) { - AppInfo.isNativeApp = true; - AppInfo.enableHomeTabs = false; - - if (isAndroid) { - AppInfo.supportsExternalPlayers = true; - } - } - else { - AppInfo.enableSupporterMembership = true; - } - - // This currently isn't working on android, unfortunately - AppInfo.supportsFileInput = !(AppInfo.isNativeApp && isAndroid); - - if (isCordova && isIOS) { - AppInfo.moreIcon = 'more-horiz'; - } else { - AppInfo.moreIcon = 'more-vert'; - } - - AppInfo.supportsUserDisplayLanguageSetting = Dashboard.isConnectMode(); - } - - function initializeApiClient(apiClient) { - - if (AppInfo.enableAppStorePolicy) { - apiClient.getAvailablePlugins = function () { - return Promise.resolve([]); - }; - apiClient.getInstalledPlugins = function () { - return Promise.resolve([]); - }; - } - - apiClient.normalizeImageOptions = Dashboard.normalizeImageOptions; - - Events.off(apiClient, 'requestfail', Dashboard.onRequestFail); - Events.on(apiClient, 'requestfail', Dashboard.onRequestFail); - } - - function onApiClientCreated(e, newApiClient) { - initializeApiClient(newApiClient); - - // This is not included in jQuery slim - if (window.$) { - $.ajax = newApiClient.ajax; - } - } - - function defineConnectionManager(connectionManager) { - - window.ConnectionManager = connectionManager; - - define('connectionManager', [], function () { - return connectionManager; - }); - } - - var localApiClient; - function bindConnectionManagerEvents(connectionManager, events, userSettings) { - - window.Events = events; - events.on(ConnectionManager, 'apiclientcreated', onApiClientCreated); - - connectionManager.currentApiClient = function () { - - if (!localApiClient) { - var server = connectionManager.getLastUsedServer(); - if (server) { - localApiClient = connectionManager.getApiClient(server.Id); - } - } - return localApiClient; - }; - - //events.on(connectionManager, 'apiclientcreated', function (e, newApiClient) { - - // //$(newApiClient).on("websocketmessage", Dashboard.onWebSocketMessageReceived).on('requestfail', Dashboard.onRequestFail); - // newApiClient.normalizeImageOptions = normalizeImageOptions; - //}); - - // Use this instead of the event because it will fire and wait for the promise before firing events to all listeners - connectionManager.onLocalUserSignedIn = function (user) { - localApiClient = connectionManager.getApiClient(user.ServerId); - window.ApiClient = localApiClient; - return userSettings.setUserInfo(user.Id, localApiClient); - }; - - events.on(connectionManager, 'localusersignedout', function () { - userSettings.setUserInfo(null, null); - }); - } - - //localStorage.clear(); - function createConnectionManager() { - - return new Promise(function (resolve, reject) { - - require(['connectionManagerFactory', 'apphost', 'credentialprovider', 'events', 'userSettings'], function (connectionManagerExports, apphost, credentialProvider, events, userSettings) { - - window.MediaBrowser = Object.assign(window.MediaBrowser || {}, connectionManagerExports); - - var credentialProviderInstance = new credentialProvider(); - - var promises = [apphost.getSyncProfile(), apphost.appInfo()]; - - Promise.all(promises).then(function (responses) { - - var deviceProfile = responses[0]; - var appInfo = responses[1]; - - var capabilities = Dashboard.capabilities(); - capabilities.DeviceProfile = deviceProfile; - - var connectionManager = new MediaBrowser.ConnectionManager(credentialProviderInstance, appInfo.appName, appInfo.appVersion, appInfo.deviceName, appInfo.deviceId, capabilities, window.devicePixelRatio); - - defineConnectionManager(connectionManager); - bindConnectionManagerEvents(connectionManager, events, userSettings); - - if (Dashboard.isConnectMode()) { - - resolve(); - - } else { - - console.log('loading ApiClient singleton'); - - return getRequirePromise(['apiclient']).then(function (apiClientFactory) { - - console.log('creating ApiClient singleton'); - - var apiClient = new apiClientFactory(Dashboard.serverAddress(), appInfo.appName, appInfo.appVersion, appInfo.deviceName, appInfo.deviceId, window.devicePixelRatio); - apiClient.enableAutomaticNetworking = false; - connectionManager.addApiClient(apiClient); - require(['css!' + apiClient.getUrl('Branding/Css')]); - window.ApiClient = apiClient; - localApiClient = apiClient; - console.log('loaded ApiClient singleton'); - resolve(); - }); - } - }); - }); - }); - } - - function setDocumentClasses(browser) { - - var elem = document.documentElement; - - if (!AppInfo.enableSupporterMembership) { - elem.classList.add('supporterMembershipDisabled'); - } - } - - function loadTheme() { - - var name = getParameterByName('theme'); - if (name) { - require(['themes/' + name + '/theme']); - return; - } - - if (AppInfo.isNativeApp) { - return; - } - - var date = new Date(); - var month = date.getMonth(); - var day = date.getDate(); - - if (month == 9 && day >= 30) { - require(['themes/halloween/theme']); - return; - } - - //if (month == 11 && day >= 20 && day <= 25) { - // require(['themes/holiday/theme']); - // return; - //} - } - - function returnFirstDependency(obj) { - return obj; - } - - function getBowerPath() { - - return "bower_components"; - } - - function getLayoutManager(layoutManager) { - - layoutManager.init(); - return layoutManager; - } - - function getAppStorage(basePath) { - - try { - localStorage.setItem('_test', '0'); - localStorage.removeItem('_test'); - return basePath + "/appstorage-localstorage"; - } catch (e) { - return basePath + "/appstorage-memory"; - } - } - - function createWindowHeadroom() { - // construct an instance of Headroom, passing the element - var headroom = new Headroom([], { - // or scroll tolerance per direction - tolerance: { - down: 0, - up: 0 - }, - classes: { - //pinned: 'appfooter--pinned', - //unpinned: 'appfooter--unpinned', - //initial: 'appfooter-headroom' - } - }); - // initialise - headroom.init(); - return headroom; - } - - function createMainContentHammer(Hammer) { - - var hammer = new Hammer(document.querySelector('.mainDrawerPanelContent'), null); - return hammer; - } - - function createSharedAppFooter(appFooter) { - var footer = new appFooter({}); - return footer; - } - - function initRequire() { - - var urlArgs = "v=" + (window.dashboardVersion || new Date().getDate()); - - var bowerPath = getBowerPath(); - - var apiClientBowerPath = bowerPath + "/emby-apiclient"; - var embyWebComponentsBowerPath = bowerPath + '/emby-webcomponents'; - - var paths = { - velocity: bowerPath + "/velocity/velocity.min", - vibrant: bowerPath + "/vibrant/dist/vibrant", - ironCardList: 'components/ironcardlist/ironcardlist', - scrollThreshold: 'components/scrollthreshold', - playlisteditor: 'components/playlisteditor/playlisteditor', - medialibrarycreator: 'components/medialibrarycreator/medialibrarycreator', - medialibraryeditor: 'components/medialibraryeditor/medialibraryeditor', - howler: bowerPath + '/howlerjs/howler.min', - sortable: bowerPath + '/Sortable/Sortable.min', - isMobile: bowerPath + '/isMobile/isMobile.min', - headroom: bowerPath + '/headroomjs/dist/headroom', - masonry: bowerPath + '/masonry/dist/masonry.pkgd.min', - humanedate: 'components/humanedate', - libraryBrowser: 'scripts/librarybrowser', - chromecasthelpers: 'components/chromecasthelpers', - events: apiClientBowerPath + '/events', - credentialprovider: apiClientBowerPath + '/credentials', - apiclient: apiClientBowerPath + '/apiclient', - connectionManagerFactory: bowerPath + '/emby-apiclient/connectionmanager', - visibleinviewport: embyWebComponentsBowerPath + "/visibleinviewport", - browserdeviceprofile: embyWebComponentsBowerPath + "/browserdeviceprofile", - browser: embyWebComponentsBowerPath + "/browser", - inputManager: embyWebComponentsBowerPath + "/inputmanager", - qualityoptions: embyWebComponentsBowerPath + "/qualityoptions", - hammer: bowerPath + "/hammerjs/hammer.min", - pageJs: embyWebComponentsBowerPath + '/pagejs/page', - focusManager: embyWebComponentsBowerPath + "/focusmanager", - datetime: embyWebComponentsBowerPath + "/datetime", - globalize: embyWebComponentsBowerPath + "/globalize", - itemHelper: embyWebComponentsBowerPath + '/itemhelper', - itemShortcuts: embyWebComponentsBowerPath + "/shortcuts", - serverNotifications: embyWebComponentsBowerPath + '/servernotifications', - playbackManager: embyWebComponentsBowerPath + '/playback/playbackmanager', - nowPlayingHelper: embyWebComponentsBowerPath + '/playback/nowplayinghelper', - pluginManager: embyWebComponentsBowerPath + '/pluginmanager', - packageManager: embyWebComponentsBowerPath + '/packagemanager', - webAnimations: bowerPath + '/web-animations-js/web-animations-next-lite.min' - }; - - paths.hlsjs = bowerPath + "/hlsjs/dist/hls.min"; - - define("webActionSheet", [embyWebComponentsBowerPath + "/actionsheet/actionsheet"], returnFirstDependency); - - if (Dashboard.isRunningInCordova()) { - paths.sharingMenu = "cordova/sharingwidget"; - } else { - - define("sharingMenu", [embyWebComponentsBowerPath + "/sharing/sharingmenu"], returnFirstDependency); - } - - paths.wakeonlan = apiClientBowerPath + "/wakeonlan"; - - define("libjass", [bowerPath + "/libjass/libjass.min", "css!" + bowerPath + "/libjass/libjass"], returnFirstDependency); - - if (window.IntersectionObserver) { - define("lazyLoader", [embyWebComponentsBowerPath + "/lazyloader/lazyloader-intersectionobserver"], returnFirstDependency); - } else { - define("lazyLoader", [embyWebComponentsBowerPath + "/lazyloader/lazyloader-scroll"], returnFirstDependency); - } - define("imageLoader", [embyWebComponentsBowerPath + "/images/imagehelper"], returnFirstDependency); - define("appfooter", ["components/appfooter/appfooter"], returnFirstDependency); - define("dockedtabs", ["components/dockedtabs/dockedtabs"], returnFirstDependency); - define("directorybrowser", ["components/directorybrowser/directorybrowser"], returnFirstDependency); - define("metadataEditor", [embyWebComponentsBowerPath + "/metadataeditor/metadataeditor"], returnFirstDependency); - define("personEditor", [embyWebComponentsBowerPath + "/metadataeditor/personeditor"], returnFirstDependency); - define("playerSelectionMenu", [embyWebComponentsBowerPath + "/playback/playerselection"], returnFirstDependency); - define("playerSettingsMenu", [embyWebComponentsBowerPath + "/playback/playersettingsmenu"], returnFirstDependency); - - define("libraryMenu", ["scripts/librarymenu"], returnFirstDependency); - - define("emby-collapse", [embyWebComponentsBowerPath + "/emby-collapse/emby-collapse"], returnFirstDependency); - define("emby-button", [embyWebComponentsBowerPath + "/emby-button/emby-button"], returnFirstDependency); - define("emby-itemscontainer", [embyWebComponentsBowerPath + "/emby-itemscontainer/emby-itemscontainer"], returnFirstDependency); - define("emby-tabs", [embyWebComponentsBowerPath + "/emby-tabs/emby-tabs"], returnFirstDependency); - define("itemHoverMenu", [embyWebComponentsBowerPath + "/itemhovermenu/itemhovermenu"], returnFirstDependency); - define("multiSelect", [embyWebComponentsBowerPath + "/multiselect/multiselect"], returnFirstDependency); - define("alphaPicker", [embyWebComponentsBowerPath + "/alphapicker/alphapicker"], returnFirstDependency); - define("paper-icon-button-light", [embyWebComponentsBowerPath + "/emby-button/paper-icon-button-light"]); - - define("connectHelper", [embyWebComponentsBowerPath + "/emby-connect/connecthelper"], returnFirstDependency); - - define("emby-input", [embyWebComponentsBowerPath + "/emby-input/emby-input"], returnFirstDependency); - define("emby-select", [embyWebComponentsBowerPath + "/emby-select/emby-select"], returnFirstDependency); - define("emby-slider", [embyWebComponentsBowerPath + "/emby-slider/emby-slider"], returnFirstDependency); - define("emby-checkbox", [embyWebComponentsBowerPath + "/emby-checkbox/emby-checkbox"], returnFirstDependency); - define("emby-toggle", [embyWebComponentsBowerPath + "/emby-toggle/emby-toggle"], returnFirstDependency); - define("emby-radio", [embyWebComponentsBowerPath + "/emby-radio/emby-radio"], returnFirstDependency); - define("emby-textarea", [embyWebComponentsBowerPath + "/emby-textarea/emby-textarea"], returnFirstDependency); - define("collectionEditor", [embyWebComponentsBowerPath + "/collectioneditor/collectioneditor"], returnFirstDependency); - define("playlistEditor", [embyWebComponentsBowerPath + "/playlisteditor/playlisteditor"], returnFirstDependency); - define("recordingCreator", [embyWebComponentsBowerPath + "/recordingcreator/recordingcreator"], returnFirstDependency); - define("recordingEditor", [embyWebComponentsBowerPath + "/recordingcreator/recordingeditor"], returnFirstDependency); - define("seriesRecordingEditor", [embyWebComponentsBowerPath + "/recordingcreator/seriesrecordingeditor"], returnFirstDependency); - define("recordingFields", [embyWebComponentsBowerPath + "/recordingcreator/recordingfields"], returnFirstDependency); - define("recordingHelper", [embyWebComponentsBowerPath + "/recordingcreator/recordinghelper"], returnFirstDependency); - define("subtitleEditor", [embyWebComponentsBowerPath + "/subtitleeditor/subtitleeditor"], returnFirstDependency); - define("itemIdentifier", [embyWebComponentsBowerPath + "/itemidentifier/itemidentifier"], returnFirstDependency); - define("mediaInfo", [embyWebComponentsBowerPath + "/mediainfo/mediainfo"], returnFirstDependency); - define("itemContextMenu", [embyWebComponentsBowerPath + "/itemcontextmenu"], returnFirstDependency); - define("imageEditor", [embyWebComponentsBowerPath + "/imageeditor/imageeditor"], returnFirstDependency); - define("dom", [embyWebComponentsBowerPath + "/dom"], returnFirstDependency); - - define("fullscreen-doubleclick", [embyWebComponentsBowerPath + "/fullscreen/fullscreen-doubleclick"], returnFirstDependency); - define("fullscreenManager", [embyWebComponentsBowerPath + "/fullscreen/fullscreenmanager", 'events'], returnFirstDependency); - - define("layoutManager", [embyWebComponentsBowerPath + "/layoutmanager"], getLayoutManager); - define("playMenu", [embyWebComponentsBowerPath + "/playmenu"], returnFirstDependency); - define("refreshDialog", [embyWebComponentsBowerPath + "/refreshdialog/refreshdialog"], returnFirstDependency); - define("backdrop", [embyWebComponentsBowerPath + "/backdrop/backdrop"], returnFirstDependency); - define("fetchHelper", [embyWebComponentsBowerPath + "/fetchhelper"], returnFirstDependency); - - define("roundCardStyle", ["cardStyle", 'css!' + embyWebComponentsBowerPath + "/cardbuilder/roundcard"], returnFirstDependency); - define("cardStyle", ['css!' + embyWebComponentsBowerPath + "/cardbuilder/card"], returnFirstDependency); - define("cardBuilder", [embyWebComponentsBowerPath + "/cardbuilder/cardbuilder"], returnFirstDependency); - define("peoplecardbuilder", [embyWebComponentsBowerPath + "/cardbuilder/peoplecardbuilder"], returnFirstDependency); - define("chaptercardbuilder", [embyWebComponentsBowerPath + "/cardbuilder/chaptercardbuilder"], returnFirstDependency); - - define("mouseManager", [embyWebComponentsBowerPath + "/input/mouse"], returnFirstDependency); - - define("deleteHelper", [embyWebComponentsBowerPath + "/deletehelper"], returnFirstDependency); - define("tvguide", [embyWebComponentsBowerPath + "/guide/guide"], returnFirstDependency); - define("programStyles", ['css!' + embyWebComponentsBowerPath + "/guide/programs"], returnFirstDependency); - define("guide-settings-dialog", [embyWebComponentsBowerPath + "/guide/guide-settings"], returnFirstDependency); - define("syncDialog", [embyWebComponentsBowerPath + "/sync/sync"], returnFirstDependency); - define("syncToggle", [embyWebComponentsBowerPath + "/sync/synctoggle"], returnFirstDependency); - define("syncJobEditor", [embyWebComponentsBowerPath + "/sync/syncjobeditor"], returnFirstDependency); - define("syncJobList", [embyWebComponentsBowerPath + "/sync/syncjoblist"], returnFirstDependency); - define("voiceDialog", [embyWebComponentsBowerPath + "/voice/voicedialog"], returnFirstDependency); - define("voiceReceiver", [embyWebComponentsBowerPath + "/voice/voicereceiver"], returnFirstDependency); - define("voiceProcessor", [embyWebComponentsBowerPath + "/voice/voiceprocessor"], returnFirstDependency); - - define("viewManager", [embyWebComponentsBowerPath + "/viewmanager/viewmanager"], function (viewManager) { - window.ViewManager = viewManager; - viewManager.dispatchPageEvents(true); - return viewManager; - }); - - // hack for an android test before browserInfo is loaded - if (Dashboard.isRunningInCordova() && window.MainActivity) { - define("shell", ["cordova/shell"], returnFirstDependency); - } else { - define("shell", [embyWebComponentsBowerPath + "/shell"], returnFirstDependency); - } - - define("sharingmanager", [embyWebComponentsBowerPath + "/sharing/sharingmanager"], returnFirstDependency); - - if (Dashboard.isRunningInCordova()) { - paths.apphost = "cordova/apphost"; - } else { - paths.apphost = "components/apphost"; - } - - // hack for an android test before browserInfo is loaded - if (Dashboard.isRunningInCordova() && window.MainActivity) { - paths.appStorage = "cordova/appstorage"; - paths.filesystem = 'cordova/filesystem'; - } else { - paths.appStorage = getAppStorage(apiClientBowerPath); - paths.filesystem = embyWebComponentsBowerPath + '/filesystem'; - } - - var sha1Path = bowerPath + "/cryptojslib/components/sha1-min"; - var md5Path = bowerPath + "/cryptojslib/components/md5-min"; - var shim = {}; - - shim[sha1Path] = { - deps: [bowerPath + "/cryptojslib/components/core-min"] - }; - - shim[md5Path] = { - deps: [bowerPath + "/cryptojslib/components/core-min"] - }; - - requirejs.config({ - waitSeconds: 0, - map: { - '*': { - 'css': bowerPath + '/emby-webcomponents/require/requirecss', - 'html': bowerPath + '/emby-webcomponents/require/requirehtml', - 'text': bowerPath + '/emby-webcomponents/require/requiretext' - } - }, - urlArgs: urlArgs, - - paths: paths, - shim: shim - }); - - define("cryptojs-sha1", [sha1Path]); - define("cryptojs-md5", [md5Path]); - - define("jstree", [bowerPath + "/jstree/dist/jstree", "css!thirdparty/jstree/themes/default/style.min.css"]); - - define("dashboardcss", ['css!css/dashboard']); - - define("jqmtable", ["thirdparty/jquerymobile-1.4.5/jqm.table", 'css!thirdparty/jquerymobile-1.4.5/jqm.table.css']); - - define("jqmwidget", ["thirdparty/jquerymobile-1.4.5/jqm.widget"]); - - define("jqmslider", ["thirdparty/jquerymobile-1.4.5/jqm.slider", 'css!thirdparty/jquerymobile-1.4.5/jqm.slider.css']); - - define("jqmpopup", ["thirdparty/jquerymobile-1.4.5/jqm.popup", 'css!thirdparty/jquerymobile-1.4.5/jqm.popup.css']); - - define("jqmlistview", ['css!thirdparty/jquerymobile-1.4.5/jqm.listview.css']); - - define("jqmpanel", ["thirdparty/jquerymobile-1.4.5/jqm.panel", 'css!thirdparty/jquerymobile-1.4.5/jqm.panel.css']); - - define("slideshow", [embyWebComponentsBowerPath + "/slideshow/slideshow"], returnFirstDependency); - - define('fetch', [bowerPath + '/fetch/fetch']); - - define('raf', [embyWebComponentsBowerPath + '/polyfills/raf']); - define('functionbind', [embyWebComponentsBowerPath + '/polyfills/bind']); - define('arraypolyfills', [embyWebComponentsBowerPath + '/polyfills/array']); - define('objectassign', [embyWebComponentsBowerPath + '/polyfills/objectassign']); - - define("clearButtonStyle", ['css!' + embyWebComponentsBowerPath + '/clearbutton']); - define("userdataButtons", [embyWebComponentsBowerPath + "/userdatabuttons/userdatabuttons"], returnFirstDependency); - define("listView", [embyWebComponentsBowerPath + "/listview/listview"], returnFirstDependency); - define("listViewStyle", ['css!' + embyWebComponentsBowerPath + "/listview/listview"], returnFirstDependency); - define("formDialogStyle", ['css!' + embyWebComponentsBowerPath + "/formdialog"], returnFirstDependency); - define("indicators", [embyWebComponentsBowerPath + "/indicators/indicators"], returnFirstDependency); - - define("registrationServices", [embyWebComponentsBowerPath + "/registrationservices/registrationservices"], returnFirstDependency); - - if (Dashboard.isRunningInCordova()) { - define("iapManager", ["cordova/iap"], returnFirstDependency); - define("fileupload", ["cordova/fileupload"], returnFirstDependency); - } else { - define("iapManager", ["components/iap"], returnFirstDependency); - define("fileupload", [apiClientBowerPath + "/fileupload"], returnFirstDependency); - } - define("connectionmanager", [apiClientBowerPath + "/connectionmanager"]); - - define("cameraRoll", [apiClientBowerPath + "/cameraroll"], returnFirstDependency); - define("contentuploader", [apiClientBowerPath + "/sync/contentuploader"]); - define("serversync", [apiClientBowerPath + "/sync/serversync"]); - define("multiserversync", [apiClientBowerPath + "/sync/multiserversync"]); - define("offlineusersync", [apiClientBowerPath + "/sync/offlineusersync"]); - define("mediasync", [apiClientBowerPath + "/sync/mediasync"]); - - define("swiper", [bowerPath + "/Swiper/dist/js/swiper.min", "css!" + bowerPath + "/Swiper/dist/css/swiper.min"], returnFirstDependency); - - define("scroller", [embyWebComponentsBowerPath + "/scroller/smoothscroller"], returnFirstDependency); - define("toast", [embyWebComponentsBowerPath + "/toast/toast"], returnFirstDependency); - define("scrollHelper", [embyWebComponentsBowerPath + "/scrollhelper"], returnFirstDependency); - - define("appSettings", [embyWebComponentsBowerPath + "/appsettings"], updateAppSettings); - define("userSettings", [embyWebComponentsBowerPath + "/usersettings/usersettings"], returnFirstDependency); - define("userSettingsBuilder", [embyWebComponentsBowerPath + "/usersettings/usersettingsbuilder"], returnFirstDependency); - - define("material-icons", ['css!' + embyWebComponentsBowerPath + '/fonts/material-icons/style']); - define("robotoFont", ['css!' + embyWebComponentsBowerPath + '/fonts/roboto/style']); - define("scrollStyles", ['css!' + embyWebComponentsBowerPath + '/scrollstyles']); - - define("navdrawer", ['components/navdrawer/navdrawer'], returnFirstDependency); - define("viewcontainer", ['components/viewcontainer-lite', 'css!' + embyWebComponentsBowerPath + '/viewmanager/viewcontainer-lite'], returnFirstDependency); - define('queryString', [bowerPath + '/query-string/index'], function () { - return queryString; - }); - - define("jQuery", [bowerPath + '/jquery/dist/jquery.slim.min'], function () { - - if (window.ApiClient) { - jQuery.ajax = ApiClient.ajax; - } - return jQuery; - }); - - define("fnchecked", ['legacy/fnchecked']); - - define("dialogHelper", [embyWebComponentsBowerPath + "/dialoghelper/dialoghelper"], function (dialoghelper) { - - dialoghelper.setOnOpen(onDialogOpen); - return dialoghelper; - }); - - define("inputmanager", ['inputManager'], returnFirstDependency); - - // alias - define("historyManager", ['embyRouter'], returnFirstDependency); - - define("headroom-window", ['headroom'], createWindowHeadroom); - define("hammer-main", ['hammer'], createMainContentHammer); - define("appfooter-shared", ['appfooter'], createSharedAppFooter); - - // mock this for now. not used in this app - define("skinManager", [], function () { - - return { - loadUserSkin: function () { - - Emby.Page.show('/home.html'); - } - }; - }); - - define("connectionManager", [], function () { - return ConnectionManager; - }); - - define('apiClientResolver', [], function () { - return function () { - return window.ApiClient; - }; - }); - - define("embyRouter", [embyWebComponentsBowerPath + '/router'], function (embyRouter) { - - embyRouter.showLocalLogin = function (apiClient, serverId, manualLogin) { - Dashboard.navigate('login.html?serverid=' + serverId); - }; - - embyRouter.showVideoOsd = function () { - return Dashboard.navigate('videoosd.html'); - }; - - embyRouter.showSelectServer = function () { - Dashboard.navigate('selectserver.html'); - }; - - embyRouter.showWelcome = function () { - - if (Dashboard.isConnectMode()) { - Dashboard.navigate('connectlogin.html?mode=welcome'); - } else { - Dashboard.navigate('login.html'); - } - }; - - embyRouter.showSettings = function () { - Dashboard.navigate('mypreferencesmenu.html'); - }; - - embyRouter.showGuide = function () { - Dashboard.navigate('livetv.html?tab=1'); - }; - - embyRouter.goHome = function () { - Dashboard.navigate('home.html'); - }; - - embyRouter.showSearch = function () { - Dashboard.navigate('search.html'); - }; - - embyRouter.showLiveTV = function () { - Dashboard.navigate('livetv.html'); - }; - - embyRouter.showRecordedTV = function () { - Dashboard.navigate('livetv.html?tab=3'); - }; - - embyRouter.showFavorites = function () { - Dashboard.navigate('favorites.html'); - }; - - embyRouter.showSettings = function () { - Dashboard.navigate('mypreferencesmenu.html'); - }; - - embyRouter.setTitle = function () { - }; - - function showItem(item, serverId, options) { - if (typeof (item) === 'string') { - require(['connectionManager'], function (connectionManager) { - var apiClient = connectionManager.currentApiClient(); - apiClient.getItem(apiClient.getCurrentUserId(), item).then(function (item) { - embyRouter.showItem(item, options); - }); - }); - } else { - - if (arguments.length == 2) { - options = arguments[1]; - } - - var context = options ? options.context : null; - Emby.Page.show('/' + LibraryBrowser.getHref(item, context), { item: item }); - } - } - - embyRouter.showItem = showItem; - - return embyRouter; - }); - } - - function updateAppSettings(appSettings) { - - appSettings.enableExternalPlayers = function (val) { - - if (val != null) { - appSettings.set('externalplayers', val.toString()); - } - - return appSettings.get('externalplayers') === 'true'; - }; - - return appSettings; - } - - function onDialogOpen(dlg) { - if (!dlg.classList.contains('background-theme-a') && !dlg.classList.contains('actionSheet')) { - - dlg.classList.add('background-theme-b'); - dlg.classList.add('ui-body-b'); - } - } - - function initRequireWithBrowser(browser) { - - var bowerPath = getBowerPath(); - var apiClientBowerPath = bowerPath + "/emby-apiclient"; - var embyWebComponentsBowerPath = bowerPath + '/emby-webcomponents'; - - if (Dashboard.isRunningInCordova() && browser.safari) { - define("actionsheet", ["cordova/actionsheet"], returnFirstDependency); - } else { - define("actionsheet", ["webActionSheet"], returnFirstDependency); - } - - if (!('registerElement' in document)) { - if (browser.msie) { - define("registerElement", [bowerPath + '/webcomponentsjs/webcomponents-lite.min.js']); - } else { - define("registerElement", [bowerPath + '/document-register-element/build/document-register-element']); - } - } else { - define("registerElement", []); - } - - if ((window.chrome && window.chrome.sockets)) { - define("serverdiscovery", [apiClientBowerPath + "/serverdiscovery-chrome"], returnFirstDependency); - } else if (Dashboard.isRunningInCordova() && browser.android) { - define("serverdiscovery", ["cordova/serverdiscovery"], returnFirstDependency); - } else if (Dashboard.isRunningInCordova() && browser.safari) { - define("serverdiscovery", [apiClientBowerPath + "/serverdiscovery-chrome"], returnFirstDependency); - } else { - define("serverdiscovery", [apiClientBowerPath + "/serverdiscovery"], returnFirstDependency); - } - - if (Dashboard.isRunningInCordova() && browser.safari) { - define("imageFetcher", ['cordova/imagestore'], returnFirstDependency); - } else { - define("imageFetcher", [embyWebComponentsBowerPath + "/images/basicimagefetcher"], returnFirstDependency); - } - - var preferNativeAlerts = browser.tv; - // use native alerts if preferred and supported (not supported in opera tv) - if (preferNativeAlerts && window.alert) { - define("alert", [embyWebComponentsBowerPath + "/alert/nativealert"], returnFirstDependency); - } else { - define("alert", [embyWebComponentsBowerPath + "/alert/alert"], returnFirstDependency); - } - - define("dialog", [embyWebComponentsBowerPath + "/dialog/dialog"], returnFirstDependency); - - if (preferNativeAlerts && window.confirm) { - define("confirm", [embyWebComponentsBowerPath + "/confirm/nativeconfirm"], returnFirstDependency); - } else { - define("confirm", [embyWebComponentsBowerPath + "/confirm/confirm"], returnFirstDependency); - } - - var preferNativePrompt = preferNativeAlerts || browser.xboxOne; - if (preferNativePrompt && window.confirm) { - define("prompt", [embyWebComponentsBowerPath + "/prompt/nativeprompt"], returnFirstDependency); - } else { - define("prompt", [embyWebComponentsBowerPath + "/prompt/prompt"], returnFirstDependency); - } - - if (browser.tizen || browser.operaTv) { - // Need the older version due to artifacts - define("loading", [embyWebComponentsBowerPath + "/loading/loading-legacy"], returnFirstDependency); - } else { - define("loading", [embyWebComponentsBowerPath + "/loading/loading-lite"], returnFirstDependency); - } - - define("multi-download", [embyWebComponentsBowerPath + '/multidownload'], returnFirstDependency); - - if (Dashboard.isRunningInCordova() && browser.android) { - define("fileDownloader", ['cordova/filedownloader'], returnFirstDependency); - define("localassetmanager", ["cordova/localassetmanager"], returnFirstDependency); - } else { - define("fileDownloader", [embyWebComponentsBowerPath + '/filedownloader'], returnFirstDependency); - define("localassetmanager", [apiClientBowerPath + "/localassetmanager"], returnFirstDependency); - } - - define("screenLock", [embyWebComponentsBowerPath + "/resourcelocks/nullresourcelock"], returnFirstDependency); - - if (Dashboard.isRunningInCordova() && browser.android) { - define("resourceLockManager", [embyWebComponentsBowerPath + "/resourcelocks/resourcelockmanager"], returnFirstDependency); - define("wakeLock", ["cordova/wakelock"], returnFirstDependency); - define("networkLock", ["cordova/networklock"], returnFirstDependency); - } else { - define("resourceLockManager", [embyWebComponentsBowerPath + "/resourcelocks/resourcelockmanager"], returnFirstDependency); - define("wakeLock", [embyWebComponentsBowerPath + "/resourcelocks/nullresourcelock"], returnFirstDependency); - define("networkLock", [embyWebComponentsBowerPath + "/resourcelocks/nullresourcelock"], returnFirstDependency); - } - } - - function getDummyResourceLockManager() { - return { - request: function (resourceType) { - return Promise.reject(); - } - }; - } - - function init() { - - if (Dashboard.isRunningInCordova() && browserInfo.android) { - define("nativedirectorychooser", ["cordova/nativedirectorychooser"]); - } - - if (Dashboard.isRunningInCordova() && browserInfo.android) { - define("localsync", ["cordova/localsync"], returnFirstDependency); - } - else { - define("localsync", ["scripts/localsync"], returnFirstDependency); - } - - define("livetvcss", ['css!css/livetv.css']); - define("detailtablecss", ['css!css/detailtable.css']); - define("autoorganizetablecss", ['css!css/autoorganizetable.css']); - - define("buttonenabled", ["legacy/buttonenabled"]); - - initAfterDependencies(); - } - - function getRequirePromise(deps) { - - return new Promise(function (resolve, reject) { - - require(deps, resolve); - }); - } - - function initAfterDependencies() { - - var list = []; - - if (!window.fetch) { - list.push('fetch'); - } - - if (typeof Object.assign != 'function') { - list.push('objectassign'); - } - - if (!Array.prototype.filter) { - list.push('arraypolyfills'); - } - - if (!Function.prototype.bind) { - list.push('functionbind'); - } - - if (!window.requestAnimationFrame) { - list.push('raf'); - } - - require(list, function () { - - createConnectionManager().then(function () { - - console.log('initAfterDependencies promises resolved'); - - require(['globalize'], function (globalize) { - - window.Globalize = globalize; - - Promise.all([loadCoreDictionary(globalize), loadSharedComponentsDictionary(globalize)]).then(onGlobalizeInit); - }); - }); - }); - } - - function loadSharedComponentsDictionary(globalize) { - - var baseUrl = 'bower_components/emby-webcomponents/strings/'; - - var languages = ['ar', 'bg-bg', 'ca', 'cs', 'da', 'de', 'el', 'en-gb', 'en-us', 'es-ar', 'es-mx', 'es', 'fi', 'fr', 'gsw', 'he', 'hr', 'hu', 'id', 'it', 'kk', 'ko', 'ms', 'nb', 'nl', 'pl', 'pt-br', 'pt-pt', 'ro', 'ru', 'sk', 'sl-si', 'sv', 'tr', 'uk', 'vi', 'zh-cn', 'zh-hk', 'zh-tw']; - - var translations = languages.map(function (i) { - return { - lang: i, - path: baseUrl + i + '.json' - }; - }); - - globalize.loadStrings({ - name: 'sharedcomponents', - translations: translations - }); - } - - function loadCoreDictionary(globalize) { - - var baseUrl = 'strings/'; - - var languages = ['ar', 'bg-bg', 'ca', 'cs', 'da', 'de', 'el', 'en-gb', 'en-us', 'es-ar', 'es-mx', 'es', 'fi', 'fr', 'gsw', 'he', 'hr', 'hu', 'id', 'it', 'kk', 'ko', 'ms', 'nb', 'nl', 'pl', 'pt-br', 'pt-pt', 'ro', 'ru', 'sl-si', 'sv', 'tr', 'uk', 'vi', 'zh-cn', 'zh-hk', 'zh-tw']; - - var translations = languages.map(function (i) { - return { - lang: i, - path: baseUrl + i + '.json' - }; - }); - - globalize.defaultModule('core'); - - return globalize.loadStrings({ - name: 'core', - translations: translations - }); - } - - function onGlobalizeInit() { - - document.title = Globalize.translateDocument(document.title, 'core'); - - require(['apphost'], function (appHost) { - - loadPlugins([], appHost, browserInfo).then(onAppReady); - }); - } - - function defineRoute(newRoute, dictionary) { - - var baseRoute = Emby.Page.baseUrl(); - - var path = newRoute.path; - - path = path.replace(baseRoute, ''); - - console.log('Defining route: ' + path); - - newRoute.dictionary = newRoute.dictionary || dictionary || 'core'; - Emby.Page.addRoute(path, newRoute); - } - - function defineCoreRoutes() { - - console.log('Defining core routes'); - - defineRoute({ - path: '/addplugin.html', - dependencies: [], - autoFocus: false, - roles: 'admin', - controller: 'scripts/addpluginpage' - }); - - defineRoute({ - path: '/appservices.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/autoorganizelog.html', - dependencies: ['scripts/taskbutton', 'autoorganizetablecss'], - controller: 'dashboard/autoorganizelog', - roles: 'admin' - }); - - defineRoute({ - path: '/autoorganizesmart.html', - dependencies: ['emby-button'], - controller: 'dashboard/autoorganizesmart', - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/autoorganizetv.html', - dependencies: ['emby-checkbox', 'emby-input', 'emby-button', 'emby-select', 'emby-collapse'], - controller: 'dashboard/autoorganizetv', - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/channelitems.html', - dependencies: [], - autoFocus: false, - transition: 'fade' - }); - - defineRoute({ - path: '/channels.html', - dependencies: [], - autoFocus: false, - transition: 'fade', - controller: 'scripts/channels' - }); - - defineRoute({ - path: '/channelsettings.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/cinemamodeconfiguration.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/connectlogin.html', - dependencies: ['emby-button', 'emby-input'], - autoFocus: false, - anonymous: true, - startup: true, - controller: 'scripts/connectlogin' - }); - - defineRoute({ - path: '/dashboard.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dashboardgeneral.html', - controller: 'dashboard/dashboardgeneral', - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dashboardhosting.html', - dependencies: ['emby-input', 'emby-button'], - autoFocus: false, - roles: 'admin', - controller: 'dashboard/dashboardhosting' - }); - - defineRoute({ - path: '/device.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/devices.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/devicesupload.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dlnaprofile.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dlnaprofiles.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dlnaserversettings.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/dlnasettings.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/edititemmetadata.html', - dependencies: [], - controller: 'scripts/edititemmetadata', - autoFocus: false - }); - - defineRoute({ - path: '/encodingsettings.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/favorites.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/favorites' - }); - - defineRoute({ - path: '/forgotpassword.html', - dependencies: ['emby-input', 'emby-button'], - anonymous: true, - startup: true, - controller: 'scripts/forgotpassword' - }); - - defineRoute({ - path: '/forgotpasswordpin.html', - dependencies: ['emby-input', 'emby-button'], - autoFocus: false, - anonymous: true, - startup: true, - controller: 'scripts/forgotpasswordpin' - }); - - defineRoute({ - path: '/gamegenres.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/games.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/gamesrecommended.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/gamestudios.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/gamesystems.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/home.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/indexpage', - transition: 'fade', - type: 'home' - }); - - defineRoute({ - path: '/index.html', - dependencies: [], - autoFocus: false, - isDefaultRoute: true - }); - - defineRoute({ - path: '/itemdetails.html', - dependencies: ['emby-button', 'scripts/livetvcomponents', 'paper-icon-button-light', 'emby-itemscontainer'], - controller: 'scripts/itemdetailpage', - autoFocus: false, - transition: 'fade' - }); - - defineRoute({ - path: '/itemlist.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/itemlistpage', - transition: 'fade' - }); - - defineRoute({ - path: '/kids.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/library.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/librarydisplay.html', - dependencies: [], - autoFocus: false, - roles: 'admin', - controller: 'dashboard/librarydisplay' - }); - - defineRoute({ - path: '/librarysettings.html', - dependencies: ['emby-collapse', 'emby-input', 'emby-button', 'emby-select'], - autoFocus: false, - roles: 'admin', - controller: 'dashboard/librarysettings' - }); - - defineRoute({ - path: '/livetv.html', - dependencies: ['emby-button', 'livetvcss'], - controller: 'scripts/livetvsuggested', - autoFocus: false, - transition: 'fade' - }); - - defineRoute({ - path: '/livetvguideprovider.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/livetvitems.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/livetvitems' - }); - - defineRoute({ - path: '/livetvseriestimer.html', - dependencies: ['emby-checkbox', 'emby-input', 'emby-button', 'emby-collapse', 'scripts/livetvcomponents', 'scripts/livetvseriestimer', 'livetvcss'], - autoFocus: false, - controller: 'scripts/livetvseriestimer' - }); - - defineRoute({ - path: '/livetvsettings.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/livetvstatus.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/livetvtunerprovider-hdhomerun.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/livetvtunerprovider-m3u.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/livetvtunerprovider-satip.html', - dependencies: ['emby-input'], - autoFocus: false, - roles: 'admin', - controller: 'dashboard/livetvtunerprovider-satip' - }); - - defineRoute({ - path: '/log.html', - dependencies: ['emby-checkbox'], - roles: 'admin', - controller: 'dashboard/logpage' - }); - - defineRoute({ - path: '/login.html', - dependencies: ['emby-button', 'emby-input'], - autoFocus: false, - anonymous: true, - startup: true, - controller: 'scripts/loginpage' - }); - - defineRoute({ - path: '/metadataadvanced.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/metadataimages.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/metadatanfo.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/metadatasubtitles.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/movies.html', - dependencies: ['emby-button'], - autoFocus: false, - controller: 'scripts/moviesrecommended', - transition: 'fade' - }); - - defineRoute({ - path: '/music.html', - dependencies: [], - controller: 'scripts/musicrecommended', - autoFocus: false, - transition: 'fade' - }); - - defineRoute({ - path: '/mypreferencesdisplay.html', - dependencies: ['emby-checkbox', 'emby-button', 'emby-select'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mypreferencesdisplay' - }); - - defineRoute({ - path: '/mypreferenceshome.html', - dependencies: ['emby-checkbox', 'emby-button', 'emby-select'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mypreferenceshome' - }); - - defineRoute({ - path: '/mypreferenceslanguages.html', - dependencies: ['emby-button', 'emby-checkbox', 'emby-select'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mypreferenceslanguages' - }); - - defineRoute({ - path: '/mypreferencesmenu.html', - dependencies: ['emby-button'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mypreferencescommon' - }); - - defineRoute({ - path: '/myprofile.html', - dependencies: ['emby-button', 'emby-collapse', 'emby-checkbox', 'emby-input'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/myprofile' - }); - - defineRoute({ - path: '/mysync.html', - dependencies: [], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mysync' - }); - - defineRoute({ - path: '/camerauploadsettings.html', - dependencies: [], - autoFocus: false, - transition: 'fade', - controller: 'scripts/camerauploadsettings' - }); - - defineRoute({ - path: '/mysyncjob.html', - dependencies: [], - autoFocus: false, - transition: 'fade', - controller: 'scripts/syncjob' - }); - - defineRoute({ - path: '/mysyncsettings.html', - dependencies: ['emby-checkbox', 'emby-input', 'emby-button', 'paper-icon-button-light'], - autoFocus: false, - transition: 'fade', - controller: 'scripts/mysyncsettings' - }); - - defineRoute({ - path: '/notificationlist.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/notificationsetting.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/notificationsettings.html', - controller: 'scripts/notificationsettings', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/nowplaying.html', - dependencies: ['paper-icon-button-light', 'emby-slider', 'emby-button', 'emby-input', 'emby-itemscontainer'], - controller: 'scripts/nowplayingpage', - autoFocus: false, - transition: 'fade', - fullscreen: true, - supportsThemeMedia: true - }); - - defineRoute({ - path: '/photos.html', - dependencies: [], - autoFocus: false, - transition: 'fade' - }); - - defineRoute({ - path: '/playbackconfiguration.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/playlists.html', - dependencies: [], - autoFocus: false, - transition: 'fade', - controller: 'scripts/playlists' - }); - - defineRoute({ - path: '/plugincatalog.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/plugins.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/reports.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/scheduledtask.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/scheduledtasks.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/search.html', - dependencies: [], - controller: 'scripts/searchpage' - }); - - defineRoute({ - path: '/secondaryitems.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/secondaryitems' - }); - - defineRoute({ - path: '/selectserver.html', - dependencies: ['listViewStyle', 'emby-button'], - autoFocus: false, - anonymous: true, - startup: true, - controller: 'scripts/selectserver' - }); - - defineRoute({ - path: '/serversecurity.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/shared.html', - dependencies: [], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/streamingsettings.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/support.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/supporterkey.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/syncactivity.html', - dependencies: [], - autoFocus: false, - controller: 'scripts/syncactivity' - }); - - defineRoute({ - path: '/syncsettings.html', - dependencies: [], - autoFocus: false - }); - - defineRoute({ - path: '/tv.html', - dependencies: ['paper-icon-button-light', 'emby-button'], - autoFocus: false, - controller: 'scripts/tvrecommended', - transition: 'fade' - }); - - defineRoute({ - path: '/useredit.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/userlibraryaccess.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/usernew.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/userparentalcontrol.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/userpassword.html', - dependencies: ['emby-input', 'emby-button', 'emby-checkbox'], - autoFocus: false, - controller: 'scripts/userpasswordpage' - }); - - defineRoute({ - path: '/userprofiles.html', - dependencies: [], - autoFocus: false, - roles: 'admin' - }); - - defineRoute({ - path: '/wizardagreement.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizardcomponents.html', - dependencies: ['dashboardcss', 'emby-button', 'emby-input', 'emby-select'], - autoFocus: false, - anonymous: true, - controller: 'dashboard/wizardcomponents' - }); - - defineRoute({ - path: '/wizardfinish.html', - dependencies: ['emby-button', 'dashboardcss'], - autoFocus: false, - anonymous: true, - controller: 'dashboard/wizardfinishpage' - }); - - defineRoute({ - path: '/wizardlibrary.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizardlivetvguide.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizardlivetvtuner.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizardsettings.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizardstart.html', - dependencies: ['dashboardcss'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/wizarduser.html', - dependencies: ['dashboardcss', 'emby-input'], - autoFocus: false, - anonymous: true - }); - - defineRoute({ - path: '/videoosd.html', - dependencies: [], - transition: 'fade', - controller: 'scripts/videoosd', - autoFocus: false, - type: 'video-osd', - supportsThemeMedia: true, - fullscreen: true - }); - - defineRoute({ - path: '/configurationpage', - dependencies: ['jQuery'], - autoFocus: false, - enableCache: false, - enableContentQueryString: true, - roles: 'admin' - }); - - defineRoute({ - path: '/', - isDefaultRoute: true, - autoFocus: false, - dependencies: [] - }); - } - - function loadPlugins(externalPlugins, appHost, browser, shell) { - - console.log('Loading installed plugins'); - - // Load installed plugins - - var list = [ - //'plugins/defaultskin/plugin', - //'plugins/logoscreensaver/plugin', - //'plugins/backdropscreensaver/plugin', - //'plugins/defaultsoundeffects/plugin', - 'bower_components/emby-webcomponents/playback/playbackvalidation' - ]; - - if (Dashboard.isRunningInCordova() && browser.android) { - - // use the html audio player if flac is supported - if (document.createElement('audio').canPlayType('audio/flac').replace(/no/, '') && - document.createElement('audio').canPlayType('audio/ogg; codecs="opus"').replace(/no/, '')) { - - } else { - window.VlcAudio = true; - } - - // Needed for video - list.push('cordova/vlcplayer'); - - } else if (Dashboard.isRunningInCordova() && browser.safari) { - list.push('cordova/audioplayer'); - } - - list.push('bower_components/emby-webcomponents/htmlaudioplayer/plugin'); - - if (Dashboard.isRunningInCordova() && browser.safari) { - list.push('cordova/chromecast'); - } - - if (Dashboard.isRunningInCordova() && browser.android) { - // intent player - list.push('cordova/externalplayer'); - } - - list.push('bower_components/emby-webcomponents/htmlvideoplayer/plugin'); - - if (appHost.supports('remotecontrol')) { - list.push('bower_components/emby-webcomponents/sessionplayer'); - - if (browser.chrome) { - list.push('bower_components/emby-webcomponents/chromecastplayer'); - } - } - - list.push('bower_components/emby-webcomponents/youtubeplayer/plugin'); - - //if (globalScope.webapis && webapis.avplay) { - // list.push('plugins/tizenavplayer/plugin'); - //} else { - // list.push('plugins/htmlvideoplayer/plugin'); - //} - - //if (!browser.tv) { - // list.push('plugins/confirmstillplaying/plugin'); - //} - - //if (!browser.keyboard) { - // list.push('plugins/keyboard/plugin'); - //} - - for (var i = 0, length = externalPlugins.length; i < length; i++) { - list.push(externalPlugins[i]); - } - - //if (shell.canExec) { - // list.push('plugins/externalplayer/plugin'); - //} - - return new Promise(function (resolve, reject) { - - Promise.all(list.map(loadPlugin)).then(function () { - - require(['packageManager'], function (packageManager) { - packageManager.init().then(resolve, reject); - }); - - }, reject); - }); - } - - function loadPlugin(url) { - - return new Promise(function (resolve, reject) { - - require(['pluginManager'], function (pluginManager) { - pluginManager.loadPlugin(url).then(resolve, reject); - }); - }); - } - - function enableNativeGamepadKeyMapping() { - - // On Windows UWP, this will tell the platform to make the gamepad emit normal keyboard events - if (window.navigator && typeof window.navigator.gamepadInputEmulation === "string") { - // We want the gamepad to provide gamepad VK keyboard events rather than moving a - // mouse like cursor. Set to "keyboard", the gamepad will provide such keyboard events - // and provide input to the DOM navigator.getGamepads API. - window.navigator.gamepadInputEmulation = "keyboard"; - return true; - } - - return false; - } - - function isGamepadSupported() { - return 'ongamepadconnected' in window || navigator.getGamepads || navigator.webkitGetGamepads; - } - - function onAppReady() { - - console.log('Begin onAppReady'); - - var deps = []; - - deps.push('apphost'); - deps.push('embyRouter'); - - if (!(AppInfo.isNativeApp && browserInfo.android)) { - document.documentElement.classList.add('minimumSizeTabs'); - } - - // Do these now to prevent a flash of content - if (AppInfo.isNativeApp && browserInfo.android) { - deps.push('css!devices/android/android.css'); - } else if (AppInfo.isNativeApp && browserInfo.safari) { - deps.push('css!devices/ios/ios.css'); - } - - loadTheme(); - - if (Dashboard.isRunningInCordova()) { - deps.push('registrationServices'); - - if (browserInfo.android) { - deps.push('cordova/androidcredentials'); - } - } - - deps.push('libraryMenu'); - - console.log('onAppReady - loading dependencies'); - - require(deps, function (appHost, pageObjects) { - - console.log('Loaded dependencies in onAppReady'); - - window.Emby = {}; - window.Emby.Page = pageObjects; - defineCoreRoutes(); - Emby.Page.start({ - click: true, - hashbang: Dashboard.isRunningInCordova() - }); - - var postInitDependencies = []; - - if (!enableNativeGamepadKeyMapping() && isGamepadSupported()) { - postInitDependencies.push('bower_components/emby-webcomponents/input/gamepadtokey'); - } - - postInitDependencies.push('bower_components/emby-webcomponents/thememediaplayer'); - postInitDependencies.push('css!css/chromecast.css'); - postInitDependencies.push('scripts/autobackdrops'); - - if (Dashboard.isRunningInCordova()) { - - if (browserInfo.android) { - postInitDependencies.push('cordova/mediasession'); - postInitDependencies.push('cordova/chromecast'); - - } else if (browserInfo.safari) { - - postInitDependencies.push('cordova/volume'); - postInitDependencies.push('cordova/statusbar'); - postInitDependencies.push('cordova/orientation'); - postInitDependencies.push('cordova/remotecontrols'); - - //postInitDependencies.push('cordova/backgroundfetch'); - } - } - - postInitDependencies.push('scripts/nowplayingbar'); - - postInitDependencies.push('bower_components/emby-webcomponents/playback/remotecontrolautoplay'); - - // Prefer custom font over Segoe if on desktop windows - if (!browserInfo.mobile && navigator.userAgent.toLowerCase().indexOf('windows') != -1) { - //postInitDependencies.push('opensansFont'); - postInitDependencies.push('robotoFont'); - } - - postInitDependencies.push('bower_components/emby-webcomponents/input/api'); - postInitDependencies.push('mouseManager'); - - if (!browserInfo.tv) { - - registerServiceWorker(); - if (window.Notification) { - postInitDependencies.push('bower_components/emby-webcomponents/notifications/notifications'); - } - } - - postInitDependencies.push('playerSelectionMenu'); - - if (appHost.supports('fullscreenchange')) { - require(['fullscreen-doubleclick']); - } - - require(postInitDependencies); - initAutoSync(); - }); - } - - function registerServiceWorker() { - - if (navigator.serviceWorker) { - try { - navigator.serviceWorker.register('serviceworker.js').then(function () { - return navigator.serviceWorker.ready; - }).then(function (reg) { - - if (reg && reg.sync) { - // https://github.com/WICG/BackgroundSync/blob/master/explainer.md - return reg.sync.register('emby-sync').then(function () { - window.SyncRegistered = Dashboard.isConnectMode(); - }); - } - }); - - } catch (err) { - console.log('Error registering serviceWorker: ' + err); - } - } - } - - function initAutoSync() { - require(['serverNotifications', 'events'], function (serverNotifications, events) { - events.on(serverNotifications, 'SyncJobItemReady', function (e, apiClient, data) { - require(['localsync'], function (localSync) { - localSync.sync({}); - }); - }); - }); - } - - initRequire(); - - function onWebComponentsReady(browser) { - - var initialDependencies = []; - - if (!window.Promise || browser.web0s) { - initialDependencies.push('bower_components/emby-webcomponents/native-promise-only/lib/npo.src'); - } - - initRequireWithBrowser(browser); - - window.browserInfo = browser; - setAppInfo(); - setDocumentClasses(browser); - - require(initialDependencies, init); - } - - require(['browser'], onWebComponentsReady); -})(); - -function pageClassOn(eventName, className, fn) { - 'use strict'; - - document.addEventListener(eventName, function (e) { - - var target = e.target; - if (target.classList.contains(className)) { - fn.call(target, e); - } - }); -} - -function pageIdOn(eventName, id, fn) { - 'use strict'; - - document.addEventListener(eventName, function (e) { - - var target = e.target; - if (target.id == id) { - fn.call(target, e); - } - }); -} - -pageClassOn('viewinit', "page", function () { - 'use strict'; - - var page = this; - - var current = page.getAttribute('data-theme'); - - if (!current) { - - var newTheme; - - if (page.classList.contains('libraryPage')) { - newTheme = 'b'; - } else { - newTheme = 'a'; - } - - page.setAttribute("data-theme", newTheme); - current = newTheme; - } - - page.classList.add("ui-page"); - page.classList.add("ui-page-theme-" + current); - page.classList.add("ui-body-" + current); - - var contents = page.querySelectorAll("div[data-role='content']"); - - for (var i = 0, length = contents.length; i < length; i++) { - var content = contents[i]; - //var theme = content.getAttribute("theme") || undefined; - - //content.classList.add("ui-content"); - //if (self.options.contentTheme) { - // content.classList.add("ui-body-" + (self.options.contentTheme)); - //} - // Add ARIA role - content.setAttribute("role", "main"); - content.classList.add("ui-content"); - } -}); - -pageClassOn('viewshow', "page", function () { - 'use strict'; - - var page = this; - - var currentTheme = page.classList.contains('ui-page-theme-a') ? 'a' : 'b'; - var docElem = document.documentElement; - - if (currentTheme == 'a') { - docElem.classList.add('background-theme-a'); - docElem.classList.remove('background-theme-b'); - } else { - docElem.classList.add('background-theme-b'); - docElem.classList.remove('background-theme-a'); - } - - Dashboard.ensureHeader(page); -}); \ No newline at end of file +function getWindowLocationSearch(win){"use strict";var search=(win||window).location.search;if(!search){var index=window.location.href.indexOf("?");index!=-1&&(search=window.location.href.substring(index))}return search||""}function getParameterByName(name,url){"use strict";name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regexS="[\\?&]"+name+"=([^&#]*)",regex=new RegExp(regexS,"i"),results=regex.exec(url||getWindowLocationSearch());return null==results?"":decodeURIComponent(results[1].replace(/\+/g," "))}function pageClassOn(eventName,className,fn){"use strict";document.addEventListener(eventName,function(e){var target=e.target;target.classList.contains(className)&&fn.call(target,e)})}function pageIdOn(eventName,id,fn){"use strict";document.addEventListener(eventName,function(e){var target=e.target;target.id==id&&fn.call(target,e)})}var Dashboard={isConnectMode:function(){if(AppInfo.isNativeApp)return!0;var url=window.location.href.toLowerCase();return url.indexOf("mediabrowser.tv")!=-1||url.indexOf("emby.media")!=-1},isRunningInCordova:function(){return"cordova"==window.appMode},onRequestFail:function(e,data){if(401==data.status&&"ParentalControl"==data.errorCode){var currentView=ViewManager.currentView();currentView&&!currentView.classList.contains(".standalonePage")&&Dashboard.alert({message:Globalize.translate("MessageLoggedOutParentalControl"),callback:function(){Dashboard.logout(!1)}})}},getCurrentUser:function(){return window.ApiClient.getCurrentUser()},serverAddress:function(){if(Dashboard.isConnectMode()){var apiClient=window.ApiClient;return apiClient?apiClient.serverAddress():null}var urlLower=window.location.href.toLowerCase(),index=urlLower.lastIndexOf("/web");if(index!=-1)return urlLower.substring(0,index);var loc=window.location,address=loc.protocol+"//"+loc.hostname;return loc.port&&(address+=":"+loc.port),address},getCurrentUserId:function(){var apiClient=window.ApiClient;return apiClient?apiClient.getCurrentUserId():null},onServerChanged:function(userId,accessToken,apiClient){apiClient=apiClient||window.ApiClient,window.ApiClient=apiClient},logout:function(logoutWithServer){function onLogoutDone(){var loginPage;Dashboard.isConnectMode()?(loginPage="connectlogin.html",window.ApiClient=null):loginPage="login.html",Dashboard.navigate(loginPage)}logoutWithServer===!1?onLogoutDone():ConnectionManager.logout().then(onLogoutDone)},getConfigurationPageUrl:function(name){return"configurationpage?name="+encodeURIComponent(name)},navigate:function(url,preserveQueryString){if(!url)throw new Error("url cannot be null or empty");var queryString=getWindowLocationSearch();return preserveQueryString&&queryString&&(url+=queryString),Emby.Page.show(url)},showLoadingMsg:function(){Dashboard.loadingVisible=!0,require(["loading"],function(loading){Dashboard.loadingVisible?loading.show():loading.hide()})},hideLoadingMsg:function(){Dashboard.loadingVisible=!1,require(["loading"],function(loading){Dashboard.loadingVisible?loading.show():loading.hide()})},processPluginConfigurationUpdateResult:function(){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("MessageSettingsSaved"))})},processServerConfigurationUpdateResult:function(result){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("MessageSettingsSaved"))})},processErrorResponse:function(response){Dashboard.hideLoadingMsg();var status=""+response.status;response.statusText&&(status=response.statusText),Dashboard.alert({title:status,message:response.headers?response.headers.get("X-Application-Error-Code"):null})},alert:function(options){return"string"==typeof options?void require(["toast"],function(toast){toast({text:options})}):void require(["alert"],function(alert){alert({title:options.title||Globalize.translate("HeaderAlert"),text:options.message}).then(options.callback||function(){})})},restartServer:function(){var apiClient=window.ApiClient;apiClient&&(Dashboard.suppressAjaxErrors=!0,Dashboard.showLoadingMsg(),apiClient.restartServer().then(function(){setTimeout(function(){Dashboard.reloadPageWhenServerAvailable()},250)},function(){Dashboard.suppressAjaxErrors=!1}))},reloadPageWhenServerAvailable:function(retryCount){var apiClient=window.ApiClient;apiClient&&apiClient.getJSON(apiClient.getUrl("System/Info")).then(function(info){info.HasPendingRestart?Dashboard.retryReload(retryCount):window.location.reload(!0)},function(){Dashboard.retryReload(retryCount)})},retryReload:function(retryCount){setTimeout(function(){retryCount=retryCount||0,retryCount++,retryCount<10?Dashboard.reloadPageWhenServerAvailable(retryCount):Dashboard.suppressAjaxErrors=!1},500)},showUserFlyout:function(){Dashboard.navigate("mypreferencesmenu.html")},getPluginSecurityInfo:function(){var apiClient=window.ApiClient;if(!apiClient)return Promise.reject();var cachedInfo=Dashboard.pluginSecurityInfo;return cachedInfo?Promise.resolve(cachedInfo):apiClient.ajax({type:"GET",url:apiClient.getUrl("Plugins/SecurityInfo"),dataType:"json",error:function(){}}).then(function(result){return Dashboard.pluginSecurityInfo=result,result})},resetPluginSecurityInfo:function(){Dashboard.pluginSecurityInfo=null},ensureHeader:function(page){page.classList.contains("standalonePage")&&!page.classList.contains("noHeaderPage")&&Dashboard.renderHeader(page)},renderHeader:function(page){var header=page.querySelector(".header");if(!header){var headerHtml="";headerHtml+='",page.insertAdjacentHTML("afterbegin",headerHtml)}},getToolsLinkHtml:function(item){var menuHtml="",pageIds=item.pageIds?item.pageIds.join(","):"";return pageIds=pageIds?' data-pageids="'+pageIds+'"':"",menuHtml+='",menuHtml+='',menuHtml+=item.name,menuHtml+="",menuHtml+=""},getToolsMenuHtml:function(page){var i,length,item,items=Dashboard.getToolsMenuLinks(page),menuHtml="";for(menuHtml+='
',i=0,length=items.length;i
"),item.href?menuHtml+=Dashboard.getToolsLinkHtml(item):(menuHtml+='
',menuHtml+=item.name,menuHtml+="
");return menuHtml+="
"},getToolsMenuLinks:function(){return[{name:Globalize.translate("TabServer")},{name:Globalize.translate("TabDashboard"),href:"dashboard.html",pageIds:["dashboardPage"],icon:"dashboard"},{name:Globalize.translate("TabSettings"),href:"dashboardgeneral.html",pageIds:["dashboardGeneralPage"],icon:"settings"},{name:Globalize.translate("TabDevices"),href:"devices.html",pageIds:["devicesPage","devicePage"],icon:"tablet"},{name:Globalize.translate("TabUsers"),href:"userprofiles.html",pageIds:["userProfilesPage","newUserPage","editUserPage","userLibraryAccessPage","userParentalControlPage","userPasswordPage"],icon:"people"},{name:"Emby Premiere",href:"supporterkey.html",pageIds:["supporterKeyPage"],icon:"star"},{divider:!0,name:Globalize.translate("TabLibrary"),href:"library.html",pageIds:["mediaLibraryPage","librarySettingsPage","libraryDisplayPage","metadataImagesConfigurationPage","metadataNfoPage"],icon:"folder",color:"#38c"},{name:Globalize.translate("TabSubtitles"),href:"metadatasubtitles.html",pageIds:["metadataSubtitlesPage"],icon:"closed_caption"},{name:Globalize.translate("TabPlayback"),icon:"play_circle_filled",color:"#E5342E",href:"cinemamodeconfiguration.html",pageIds:["cinemaModeConfigurationPage","playbackConfigurationPage","streamingSettingsPage"]},{name:Globalize.translate("TabSync"),icon:"sync",href:"syncactivity.html",pageIds:["syncActivityPage","syncJobPage","devicesUploadPage","syncSettingsPage"],color:"#009688"},{name:Globalize.translate("TabTranscoding"),icon:"transform",href:"encodingsettings.html",pageIds:["encodingSettingsPage"]},{divider:!0,name:Globalize.translate("TabExtras")},{name:Globalize.translate("TabAutoOrganize"),color:"#01C0DD",href:"autoorganizelog.html",pageIds:["libraryFileOrganizerPage","libraryFileOrganizerSmartMatchPage","libraryFileOrganizerLogPage"],icon:"folder"},{name:Globalize.translate("DLNA"),href:"dlnasettings.html",pageIds:["dlnaSettingsPage","dlnaProfilesPage","dlnaProfilePage"],icon:"settings"},{name:Globalize.translate("TabLiveTV"),href:"livetvstatus.html",pageIds:["liveTvStatusPage","liveTvSettingsPage","liveTvTunerProviderHdHomerunPage","liveTvTunerProviderM3UPage","liveTvTunerProviderSatPage"],icon:"dvr"},{name:Globalize.translate("TabNotifications"),icon:"notifications",color:"brown",href:"notificationsettings.html",pageIds:["notificationSettingsPage","notificationSettingPage"]},{name:Globalize.translate("TabPlugins"),icon:"add_shopping_cart",color:"#9D22B1",href:"plugins.html",pageIds:["pluginsPage","pluginCatalogPage"]},{divider:!0,name:Globalize.translate("TabExpert")},{name:Globalize.translate("TabAdvanced"),icon:"settings",href:"dashboardhosting.html",color:"#F16834",pageIds:["dashboardHostingPage","serverSecurityPage"]},{name:Globalize.translate("TabLogs"),href:"log.html",pageIds:["logPage"],icon:"folder_open"},{name:Globalize.translate("TabScheduledTasks"),href:"scheduledtasks.html",pageIds:["scheduledTasksPage","scheduledTaskPage"],icon:"schedule"},{name:Globalize.translate("MetadataManager"),href:"edititemmetadata.html",pageIds:[],icon:"mode_edit"},{name:Globalize.translate("ButtonReports"),href:"reports.html",pageIds:[],icon:"insert_chart"}]},getSupportedRemoteCommands:function(){return["GoHome","GoToSettings","VolumeUp","VolumeDown","Mute","Unmute","ToggleMute","SetVolume","SetAudioStreamIndex","SetSubtitleStreamIndex","DisplayContent","GoToSearch","DisplayMessage","SetRepeatMode"]},capabilities:function(){var caps={PlayableMediaTypes:["Audio","Video"],SupportedCommands:Dashboard.getSupportedRemoteCommands(),SupportsPersistentIdentifier:Dashboard.isRunningInCordova(),SupportsMediaControl:!0,SupportedLiveMediaTypes:["Audio","Video"]};return Dashboard.isRunningInCordova()&&!browserInfo.safari&&(caps.SupportsSync=!0,caps.SupportsContentUploading=!0),caps},normalizeImageOptions:function(options){AppInfo.hasLowImageBandwidth&&(options.enableImageEnhancers=!1);var setQuality;if(options.maxWidth&&(setQuality=!0),options.width&&(setQuality=!0),options.maxHeight&&(setQuality=!0),options.height&&(setQuality=!0),setQuality){var quality=90,isBackdrop="backdrop"==(options.type||"").toLowerCase();isBackdrop&&(quality-=10),browserInfo.slow&&(quality-=40),AppInfo.hasLowImageBandwidth&&!isBackdrop&&(quality-=10),options.quality=quality}}},AppInfo={};!function(){"use strict";function setAppInfo(){var isCordova=Dashboard.isRunningInCordova();AppInfo.enableHomeTabs=!0,AppInfo.enableAutoSave=browserInfo.touch,AppInfo.enableAppStorePolicy=isCordova;var isIOS=browserInfo.ipad||browserInfo.iphone,isAndroid=browserInfo.android;isIOS&&(AppInfo.hasLowImageBandwidth=!0),isCordova?(AppInfo.isNativeApp=!0,AppInfo.enableHomeTabs=!1,isAndroid&&(AppInfo.supportsExternalPlayers=!0)):AppInfo.enableSupporterMembership=!0,AppInfo.supportsFileInput=!(AppInfo.isNativeApp&&isAndroid),isCordova&&isIOS?AppInfo.moreIcon="more-horiz":AppInfo.moreIcon="more-vert",AppInfo.supportsUserDisplayLanguageSetting=Dashboard.isConnectMode()}function initializeApiClient(apiClient){AppInfo.enableAppStorePolicy&&(apiClient.getAvailablePlugins=function(){return Promise.resolve([])},apiClient.getInstalledPlugins=function(){return Promise.resolve([])}),apiClient.normalizeImageOptions=Dashboard.normalizeImageOptions,Events.off(apiClient,"requestfail",Dashboard.onRequestFail),Events.on(apiClient,"requestfail",Dashboard.onRequestFail)}function onApiClientCreated(e,newApiClient){initializeApiClient(newApiClient),window.$&&($.ajax=newApiClient.ajax)}function defineConnectionManager(connectionManager){window.ConnectionManager=connectionManager,define("connectionManager",[],function(){return connectionManager})}function bindConnectionManagerEvents(connectionManager,events,userSettings){window.Events=events,events.on(ConnectionManager,"apiclientcreated",onApiClientCreated),connectionManager.currentApiClient=function(){if(!localApiClient){var server=connectionManager.getLastUsedServer();server&&(localApiClient=connectionManager.getApiClient(server.Id))}return localApiClient},connectionManager.onLocalUserSignedIn=function(user){return localApiClient=connectionManager.getApiClient(user.ServerId),window.ApiClient=localApiClient,userSettings.setUserInfo(user.Id,localApiClient)},events.on(connectionManager,"localusersignedout",function(){userSettings.setUserInfo(null,null)})}function createConnectionManager(){return new Promise(function(resolve,reject){require(["connectionManagerFactory","apphost","credentialprovider","events","userSettings"],function(connectionManagerExports,apphost,credentialProvider,events,userSettings){window.MediaBrowser=Object.assign(window.MediaBrowser||{},connectionManagerExports);var credentialProviderInstance=new credentialProvider,promises=[apphost.getSyncProfile(),apphost.appInfo()];Promise.all(promises).then(function(responses){var deviceProfile=responses[0],appInfo=responses[1],capabilities=Dashboard.capabilities();capabilities.DeviceProfile=deviceProfile;var connectionManager=new MediaBrowser.ConnectionManager(credentialProviderInstance,appInfo.appName,appInfo.appVersion,appInfo.deviceName,appInfo.deviceId,capabilities,window.devicePixelRatio);return defineConnectionManager(connectionManager),bindConnectionManagerEvents(connectionManager,events,userSettings),Dashboard.isConnectMode()?void resolve():(console.log("loading ApiClient singleton"),getRequirePromise(["apiclient"]).then(function(apiClientFactory){console.log("creating ApiClient singleton");var apiClient=new apiClientFactory(Dashboard.serverAddress(),appInfo.appName,appInfo.appVersion,appInfo.deviceName,appInfo.deviceId,window.devicePixelRatio);apiClient.enableAutomaticNetworking=!1,connectionManager.addApiClient(apiClient),require(["css!"+apiClient.getUrl("Branding/Css")]),window.ApiClient=apiClient,localApiClient=apiClient,console.log("loaded ApiClient singleton"),resolve()}))})})})}function setDocumentClasses(browser){var elem=document.documentElement;AppInfo.enableSupporterMembership||elem.classList.add("supporterMembershipDisabled")}function loadTheme(){var name=getParameterByName("theme");if(name)return void require(["themes/"+name+"/theme"]);if(!AppInfo.isNativeApp){var date=new Date,month=date.getMonth(),day=date.getDate();return 9==month&&day>=30?void require(["themes/halloween/theme"]):void 0}}function returnFirstDependency(obj){return obj}function getBowerPath(){return"bower_components"}function getLayoutManager(layoutManager){return layoutManager.init(),layoutManager}function getAppStorage(basePath){try{return localStorage.setItem("_test","0"),localStorage.removeItem("_test"),basePath+"/appstorage-localstorage"}catch(e){return basePath+"/appstorage-memory"}}function createWindowHeadroom(){var headroom=new Headroom([],{tolerance:{down:0,up:0},classes:{}});return headroom.init(),headroom}function createMainContentHammer(Hammer){var hammer=new Hammer(document.querySelector(".mainDrawerPanelContent"),null);return hammer}function createSharedAppFooter(appFooter){var footer=new appFooter({});return footer}function initRequire(){var urlArgs="v="+(window.dashboardVersion||(new Date).getDate()),bowerPath=getBowerPath(),apiClientBowerPath=bowerPath+"/emby-apiclient",embyWebComponentsBowerPath=bowerPath+"/emby-webcomponents",paths={velocity:bowerPath+"/velocity/velocity.min",vibrant:bowerPath+"/vibrant/dist/vibrant",ironCardList:"components/ironcardlist/ironcardlist",scrollThreshold:"components/scrollthreshold",playlisteditor:"components/playlisteditor/playlisteditor",medialibrarycreator:"components/medialibrarycreator/medialibrarycreator",medialibraryeditor:"components/medialibraryeditor/medialibraryeditor",howler:bowerPath+"/howlerjs/howler.min",sortable:bowerPath+"/Sortable/Sortable.min",isMobile:bowerPath+"/isMobile/isMobile.min",headroom:bowerPath+"/headroomjs/dist/headroom",masonry:bowerPath+"/masonry/dist/masonry.pkgd.min",humanedate:"components/humanedate",libraryBrowser:"scripts/librarybrowser",chromecasthelpers:"components/chromecasthelpers",events:apiClientBowerPath+"/events",credentialprovider:apiClientBowerPath+"/credentials",apiclient:apiClientBowerPath+"/apiclient",connectionManagerFactory:bowerPath+"/emby-apiclient/connectionmanager",visibleinviewport:embyWebComponentsBowerPath+"/visibleinviewport",browserdeviceprofile:embyWebComponentsBowerPath+"/browserdeviceprofile",browser:embyWebComponentsBowerPath+"/browser",inputManager:embyWebComponentsBowerPath+"/inputmanager",qualityoptions:embyWebComponentsBowerPath+"/qualityoptions",hammer:bowerPath+"/hammerjs/hammer.min",pageJs:embyWebComponentsBowerPath+"/pagejs/page",focusManager:embyWebComponentsBowerPath+"/focusmanager",datetime:embyWebComponentsBowerPath+"/datetime",globalize:embyWebComponentsBowerPath+"/globalize",itemHelper:embyWebComponentsBowerPath+"/itemhelper",itemShortcuts:embyWebComponentsBowerPath+"/shortcuts",serverNotifications:embyWebComponentsBowerPath+"/servernotifications",playbackManager:embyWebComponentsBowerPath+"/playback/playbackmanager",nowPlayingHelper:embyWebComponentsBowerPath+"/playback/nowplayinghelper",pluginManager:embyWebComponentsBowerPath+"/pluginmanager",packageManager:embyWebComponentsBowerPath+"/packagemanager",webAnimations:bowerPath+"/web-animations-js/web-animations-next-lite.min"};paths.hlsjs=bowerPath+"/hlsjs/dist/hls.min",define("webActionSheet",[embyWebComponentsBowerPath+"/actionsheet/actionsheet"],returnFirstDependency),Dashboard.isRunningInCordova()?paths.sharingMenu="cordova/sharingwidget":define("sharingMenu",[embyWebComponentsBowerPath+"/sharing/sharingmenu"],returnFirstDependency),paths.wakeonlan=apiClientBowerPath+"/wakeonlan",define("libjass",[bowerPath+"/libjass/libjass.min","css!"+bowerPath+"/libjass/libjass"],returnFirstDependency),window.IntersectionObserver?define("lazyLoader",[embyWebComponentsBowerPath+"/lazyloader/lazyloader-intersectionobserver"],returnFirstDependency):define("lazyLoader",[embyWebComponentsBowerPath+"/lazyloader/lazyloader-scroll"],returnFirstDependency),define("imageLoader",[embyWebComponentsBowerPath+"/images/imagehelper"],returnFirstDependency),define("appfooter",["components/appfooter/appfooter"],returnFirstDependency),define("dockedtabs",["components/dockedtabs/dockedtabs"],returnFirstDependency),define("directorybrowser",["components/directorybrowser/directorybrowser"],returnFirstDependency),define("metadataEditor",[embyWebComponentsBowerPath+"/metadataeditor/metadataeditor"],returnFirstDependency),define("personEditor",[embyWebComponentsBowerPath+"/metadataeditor/personeditor"],returnFirstDependency),define("playerSelectionMenu",[embyWebComponentsBowerPath+"/playback/playerselection"],returnFirstDependency),define("playerSettingsMenu",[embyWebComponentsBowerPath+"/playback/playersettingsmenu"],returnFirstDependency),define("libraryMenu",["scripts/librarymenu"],returnFirstDependency),define("emby-collapse",[embyWebComponentsBowerPath+"/emby-collapse/emby-collapse"],returnFirstDependency),define("emby-button",[embyWebComponentsBowerPath+"/emby-button/emby-button"],returnFirstDependency),define("emby-itemscontainer",[embyWebComponentsBowerPath+"/emby-itemscontainer/emby-itemscontainer"],returnFirstDependency),define("emby-tabs",[embyWebComponentsBowerPath+"/emby-tabs/emby-tabs"],returnFirstDependency),define("itemHoverMenu",[embyWebComponentsBowerPath+"/itemhovermenu/itemhovermenu"],returnFirstDependency),define("multiSelect",[embyWebComponentsBowerPath+"/multiselect/multiselect"],returnFirstDependency),define("alphaPicker",[embyWebComponentsBowerPath+"/alphapicker/alphapicker"],returnFirstDependency),define("paper-icon-button-light",[embyWebComponentsBowerPath+"/emby-button/paper-icon-button-light"]),define("connectHelper",[embyWebComponentsBowerPath+"/emby-connect/connecthelper"],returnFirstDependency),define("emby-input",[embyWebComponentsBowerPath+"/emby-input/emby-input"],returnFirstDependency),define("emby-select",[embyWebComponentsBowerPath+"/emby-select/emby-select"],returnFirstDependency),define("emby-slider",[embyWebComponentsBowerPath+"/emby-slider/emby-slider"],returnFirstDependency),define("emby-checkbox",[embyWebComponentsBowerPath+"/emby-checkbox/emby-checkbox"],returnFirstDependency),define("emby-toggle",[embyWebComponentsBowerPath+"/emby-toggle/emby-toggle"],returnFirstDependency),define("emby-radio",[embyWebComponentsBowerPath+"/emby-radio/emby-radio"],returnFirstDependency),define("emby-textarea",[embyWebComponentsBowerPath+"/emby-textarea/emby-textarea"],returnFirstDependency),define("collectionEditor",[embyWebComponentsBowerPath+"/collectioneditor/collectioneditor"],returnFirstDependency),define("playlistEditor",[embyWebComponentsBowerPath+"/playlisteditor/playlisteditor"],returnFirstDependency),define("recordingCreator",[embyWebComponentsBowerPath+"/recordingcreator/recordingcreator"],returnFirstDependency),define("recordingEditor",[embyWebComponentsBowerPath+"/recordingcreator/recordingeditor"],returnFirstDependency),define("seriesRecordingEditor",[embyWebComponentsBowerPath+"/recordingcreator/seriesrecordingeditor"],returnFirstDependency),define("recordingFields",[embyWebComponentsBowerPath+"/recordingcreator/recordingfields"],returnFirstDependency),define("recordingHelper",[embyWebComponentsBowerPath+"/recordingcreator/recordinghelper"],returnFirstDependency),define("subtitleEditor",[embyWebComponentsBowerPath+"/subtitleeditor/subtitleeditor"],returnFirstDependency),define("itemIdentifier",[embyWebComponentsBowerPath+"/itemidentifier/itemidentifier"],returnFirstDependency),define("mediaInfo",[embyWebComponentsBowerPath+"/mediainfo/mediainfo"],returnFirstDependency),define("itemContextMenu",[embyWebComponentsBowerPath+"/itemcontextmenu"],returnFirstDependency),define("imageEditor",[embyWebComponentsBowerPath+"/imageeditor/imageeditor"],returnFirstDependency),define("dom",[embyWebComponentsBowerPath+"/dom"],returnFirstDependency),define("fullscreen-doubleclick",[embyWebComponentsBowerPath+"/fullscreen/fullscreen-doubleclick"],returnFirstDependency),define("fullscreenManager",[embyWebComponentsBowerPath+"/fullscreen/fullscreenmanager","events"],returnFirstDependency),define("layoutManager",[embyWebComponentsBowerPath+"/layoutmanager"],getLayoutManager),define("playMenu",[embyWebComponentsBowerPath+"/playmenu"],returnFirstDependency),define("refreshDialog",[embyWebComponentsBowerPath+"/refreshdialog/refreshdialog"],returnFirstDependency),define("backdrop",[embyWebComponentsBowerPath+"/backdrop/backdrop"],returnFirstDependency),define("fetchHelper",[embyWebComponentsBowerPath+"/fetchhelper"],returnFirstDependency),define("roundCardStyle",["cardStyle","css!"+embyWebComponentsBowerPath+"/cardbuilder/roundcard"],returnFirstDependency),define("cardStyle",["css!"+embyWebComponentsBowerPath+"/cardbuilder/card"],returnFirstDependency),define("cardBuilder",[embyWebComponentsBowerPath+"/cardbuilder/cardbuilder"],returnFirstDependency),define("peoplecardbuilder",[embyWebComponentsBowerPath+"/cardbuilder/peoplecardbuilder"],returnFirstDependency),define("chaptercardbuilder",[embyWebComponentsBowerPath+"/cardbuilder/chaptercardbuilder"],returnFirstDependency),define("mouseManager",[embyWebComponentsBowerPath+"/input/mouse"],returnFirstDependency),define("deleteHelper",[embyWebComponentsBowerPath+"/deletehelper"],returnFirstDependency),define("tvguide",[embyWebComponentsBowerPath+"/guide/guide"],returnFirstDependency),define("programStyles",["css!"+embyWebComponentsBowerPath+"/guide/programs"],returnFirstDependency),define("guide-settings-dialog",[embyWebComponentsBowerPath+"/guide/guide-settings"],returnFirstDependency),define("syncDialog",[embyWebComponentsBowerPath+"/sync/sync"],returnFirstDependency),define("syncToggle",[embyWebComponentsBowerPath+"/sync/synctoggle"],returnFirstDependency),define("syncJobEditor",[embyWebComponentsBowerPath+"/sync/syncjobeditor"],returnFirstDependency),define("syncJobList",[embyWebComponentsBowerPath+"/sync/syncjoblist"],returnFirstDependency),define("voiceDialog",[embyWebComponentsBowerPath+"/voice/voicedialog"],returnFirstDependency),define("voiceReceiver",[embyWebComponentsBowerPath+"/voice/voicereceiver"],returnFirstDependency),define("voiceProcessor",[embyWebComponentsBowerPath+"/voice/voiceprocessor"],returnFirstDependency),define("viewManager",[embyWebComponentsBowerPath+"/viewmanager/viewmanager"],function(viewManager){return window.ViewManager=viewManager,viewManager.dispatchPageEvents(!0),viewManager}),Dashboard.isRunningInCordova()&&window.MainActivity?define("shell",["cordova/shell"],returnFirstDependency):define("shell",[embyWebComponentsBowerPath+"/shell"],returnFirstDependency),define("sharingmanager",[embyWebComponentsBowerPath+"/sharing/sharingmanager"],returnFirstDependency),Dashboard.isRunningInCordova()?paths.apphost="cordova/apphost":paths.apphost="components/apphost",Dashboard.isRunningInCordova()&&window.MainActivity?(paths.appStorage="cordova/appstorage",paths.filesystem="cordova/filesystem"):(paths.appStorage=getAppStorage(apiClientBowerPath),paths.filesystem=embyWebComponentsBowerPath+"/filesystem");var sha1Path=bowerPath+"/cryptojslib/components/sha1-min",md5Path=bowerPath+"/cryptojslib/components/md5-min",shim={};shim[sha1Path]={deps:[bowerPath+"/cryptojslib/components/core-min"]},shim[md5Path]={deps:[bowerPath+"/cryptojslib/components/core-min"]},requirejs.config({waitSeconds:0,map:{"*":{css:bowerPath+"/emby-webcomponents/require/requirecss",html:bowerPath+"/emby-webcomponents/require/requirehtml",text:bowerPath+"/emby-webcomponents/require/requiretext"}},urlArgs:urlArgs,paths:paths,shim:shim}),define("cryptojs-sha1",[sha1Path]),define("cryptojs-md5",[md5Path]),define("jstree",[bowerPath+"/jstree/dist/jstree","css!thirdparty/jstree/themes/default/style.min.css"]),define("dashboardcss",["css!css/dashboard"]),define("jqmtable",["thirdparty/jquerymobile-1.4.5/jqm.table","css!thirdparty/jquerymobile-1.4.5/jqm.table.css"]),define("jqmwidget",["thirdparty/jquerymobile-1.4.5/jqm.widget"]),define("jqmslider",["thirdparty/jquerymobile-1.4.5/jqm.slider","css!thirdparty/jquerymobile-1.4.5/jqm.slider.css"]),define("jqmpopup",["thirdparty/jquerymobile-1.4.5/jqm.popup","css!thirdparty/jquerymobile-1.4.5/jqm.popup.css"]),define("jqmlistview",["css!thirdparty/jquerymobile-1.4.5/jqm.listview.css"]),define("jqmpanel",["thirdparty/jquerymobile-1.4.5/jqm.panel","css!thirdparty/jquerymobile-1.4.5/jqm.panel.css"]),define("slideshow",[embyWebComponentsBowerPath+"/slideshow/slideshow"],returnFirstDependency),define("fetch",[bowerPath+"/fetch/fetch"]),define("raf",[embyWebComponentsBowerPath+"/polyfills/raf"]),define("functionbind",[embyWebComponentsBowerPath+"/polyfills/bind"]),define("arraypolyfills",[embyWebComponentsBowerPath+"/polyfills/array"]),define("objectassign",[embyWebComponentsBowerPath+"/polyfills/objectassign"]),define("clearButtonStyle",["css!"+embyWebComponentsBowerPath+"/clearbutton"]),define("userdataButtons",[embyWebComponentsBowerPath+"/userdatabuttons/userdatabuttons"],returnFirstDependency),define("listView",[embyWebComponentsBowerPath+"/listview/listview"],returnFirstDependency),define("listViewStyle",["css!"+embyWebComponentsBowerPath+"/listview/listview"],returnFirstDependency),define("formDialogStyle",["css!"+embyWebComponentsBowerPath+"/formdialog"],returnFirstDependency),define("indicators",[embyWebComponentsBowerPath+"/indicators/indicators"],returnFirstDependency),define("registrationServices",[embyWebComponentsBowerPath+"/registrationservices/registrationservices"],returnFirstDependency),Dashboard.isRunningInCordova()?(define("iapManager",["cordova/iap"],returnFirstDependency),define("fileupload",["cordova/fileupload"],returnFirstDependency)):(define("iapManager",["components/iap"],returnFirstDependency),define("fileupload",[apiClientBowerPath+"/fileupload"],returnFirstDependency)),define("connectionmanager",[apiClientBowerPath+"/connectionmanager"]),define("cameraRoll",[apiClientBowerPath+"/cameraroll"],returnFirstDependency),define("contentuploader",[apiClientBowerPath+"/sync/contentuploader"]),define("serversync",[apiClientBowerPath+"/sync/serversync"]),define("multiserversync",[apiClientBowerPath+"/sync/multiserversync"]),define("offlineusersync",[apiClientBowerPath+"/sync/offlineusersync"]),define("mediasync",[apiClientBowerPath+"/sync/mediasync"]),define("swiper",[bowerPath+"/Swiper/dist/js/swiper.min","css!"+bowerPath+"/Swiper/dist/css/swiper.min"],returnFirstDependency),define("scroller",[embyWebComponentsBowerPath+"/scroller/smoothscroller"],returnFirstDependency),define("toast",[embyWebComponentsBowerPath+"/toast/toast"],returnFirstDependency),define("scrollHelper",[embyWebComponentsBowerPath+"/scrollhelper"],returnFirstDependency),define("appSettings",[embyWebComponentsBowerPath+"/appsettings"],updateAppSettings),define("userSettings",[embyWebComponentsBowerPath+"/usersettings/usersettings"],returnFirstDependency),define("userSettingsBuilder",[embyWebComponentsBowerPath+"/usersettings/usersettingsbuilder"],returnFirstDependency),define("material-icons",["css!"+embyWebComponentsBowerPath+"/fonts/material-icons/style"]),define("robotoFont",["css!"+embyWebComponentsBowerPath+"/fonts/roboto/style"]),define("scrollStyles",["css!"+embyWebComponentsBowerPath+"/scrollstyles"]),define("navdrawer",["components/navdrawer/navdrawer"],returnFirstDependency),define("viewcontainer",["components/viewcontainer-lite","css!"+embyWebComponentsBowerPath+"/viewmanager/viewcontainer-lite"],returnFirstDependency),define("queryString",[bowerPath+"/query-string/index"],function(){return queryString}),define("jQuery",[bowerPath+"/jquery/dist/jquery.slim.min"],function(){return window.ApiClient&&(jQuery.ajax=ApiClient.ajax),jQuery}),define("fnchecked",["legacy/fnchecked"]),define("dialogHelper",[embyWebComponentsBowerPath+"/dialoghelper/dialoghelper"],function(dialoghelper){return dialoghelper.setOnOpen(onDialogOpen),dialoghelper}),define("inputmanager",["inputManager"],returnFirstDependency),define("historyManager",["embyRouter"],returnFirstDependency),define("headroom-window",["headroom"],createWindowHeadroom),define("hammer-main",["hammer"],createMainContentHammer),define("appfooter-shared",["appfooter"],createSharedAppFooter),define("skinManager",[],function(){return{loadUserSkin:function(){Emby.Page.show("/home.html")}}}),define("connectionManager",[],function(){return ConnectionManager}),define("apiClientResolver",[],function(){return function(){return window.ApiClient}}),define("embyRouter",[embyWebComponentsBowerPath+"/router"],function(embyRouter){function showItem(item,serverId,options){if("string"==typeof item)require(["connectionManager"],function(connectionManager){var apiClient=connectionManager.currentApiClient();apiClient.getItem(apiClient.getCurrentUserId(),item).then(function(item){embyRouter.showItem(item,options)})});else{2==arguments.length&&(options=arguments[1]);var context=options?options.context:null;Emby.Page.show("/"+LibraryBrowser.getHref(item,context),{item:item})}}return embyRouter.showLocalLogin=function(apiClient,serverId,manualLogin){Dashboard.navigate("login.html?serverid="+serverId)},embyRouter.showVideoOsd=function(){return Dashboard.navigate("videoosd.html")},embyRouter.showSelectServer=function(){Dashboard.navigate("selectserver.html")},embyRouter.showWelcome=function(){Dashboard.isConnectMode()?Dashboard.navigate("connectlogin.html?mode=welcome"):Dashboard.navigate("login.html")},embyRouter.showSettings=function(){Dashboard.navigate("mypreferencesmenu.html")},embyRouter.showGuide=function(){Dashboard.navigate("livetv.html?tab=1")},embyRouter.goHome=function(){Dashboard.navigate("home.html"); +},embyRouter.showSearch=function(){Dashboard.navigate("search.html")},embyRouter.showLiveTV=function(){Dashboard.navigate("livetv.html")},embyRouter.showRecordedTV=function(){Dashboard.navigate("livetv.html?tab=3")},embyRouter.showFavorites=function(){Dashboard.navigate("favorites.html")},embyRouter.showSettings=function(){Dashboard.navigate("mypreferencesmenu.html")},embyRouter.setTitle=function(){},embyRouter.showItem=showItem,embyRouter})}function updateAppSettings(appSettings){return appSettings.enableExternalPlayers=function(val){return null!=val&&appSettings.set("externalplayers",val.toString()),"true"===appSettings.get("externalplayers")},appSettings}function onDialogOpen(dlg){dlg.classList.contains("background-theme-a")||dlg.classList.contains("actionSheet")||(dlg.classList.add("background-theme-b"),dlg.classList.add("ui-body-b"))}function initRequireWithBrowser(browser){var bowerPath=getBowerPath(),apiClientBowerPath=bowerPath+"/emby-apiclient",embyWebComponentsBowerPath=bowerPath+"/emby-webcomponents";Dashboard.isRunningInCordova()&&browser.safari?define("actionsheet",["cordova/actionsheet"],returnFirstDependency):define("actionsheet",["webActionSheet"],returnFirstDependency),"registerElement"in document?define("registerElement",[]):browser.msie?define("registerElement",[bowerPath+"/webcomponentsjs/webcomponents-lite.min.js"]):define("registerElement",[bowerPath+"/document-register-element/build/document-register-element"]),window.chrome&&window.chrome.sockets?define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery-chrome"],returnFirstDependency):Dashboard.isRunningInCordova()&&browser.android?define("serverdiscovery",["cordova/serverdiscovery"],returnFirstDependency):Dashboard.isRunningInCordova()&&browser.safari?define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery-chrome"],returnFirstDependency):define("serverdiscovery",[apiClientBowerPath+"/serverdiscovery"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.safari?define("imageFetcher",["cordova/imagestore"],returnFirstDependency):define("imageFetcher",[embyWebComponentsBowerPath+"/images/basicimagefetcher"],returnFirstDependency);var preferNativeAlerts=browser.tv;preferNativeAlerts&&window.alert?define("alert",[embyWebComponentsBowerPath+"/alert/nativealert"],returnFirstDependency):define("alert",[embyWebComponentsBowerPath+"/alert/alert"],returnFirstDependency),define("dialog",[embyWebComponentsBowerPath+"/dialog/dialog"],returnFirstDependency),preferNativeAlerts&&window.confirm?define("confirm",[embyWebComponentsBowerPath+"/confirm/nativeconfirm"],returnFirstDependency):define("confirm",[embyWebComponentsBowerPath+"/confirm/confirm"],returnFirstDependency);var preferNativePrompt=preferNativeAlerts||browser.xboxOne;preferNativePrompt&&window.confirm?define("prompt",[embyWebComponentsBowerPath+"/prompt/nativeprompt"],returnFirstDependency):define("prompt",[embyWebComponentsBowerPath+"/prompt/prompt"],returnFirstDependency),browser.tizen||browser.operaTv?define("loading",[embyWebComponentsBowerPath+"/loading/loading-legacy"],returnFirstDependency):define("loading",[embyWebComponentsBowerPath+"/loading/loading-lite"],returnFirstDependency),define("multi-download",[embyWebComponentsBowerPath+"/multidownload"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.android?(define("fileDownloader",["cordova/filedownloader"],returnFirstDependency),define("localassetmanager",["cordova/localassetmanager"],returnFirstDependency)):(define("fileDownloader",[embyWebComponentsBowerPath+"/filedownloader"],returnFirstDependency),define("localassetmanager",[apiClientBowerPath+"/localassetmanager"],returnFirstDependency)),define("screenLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency),Dashboard.isRunningInCordova()&&browser.android?(define("resourceLockManager",[embyWebComponentsBowerPath+"/resourcelocks/resourcelockmanager"],returnFirstDependency),define("wakeLock",["cordova/wakelock"],returnFirstDependency),define("networkLock",["cordova/networklock"],returnFirstDependency)):(define("resourceLockManager",[embyWebComponentsBowerPath+"/resourcelocks/resourcelockmanager"],returnFirstDependency),define("wakeLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency),define("networkLock",[embyWebComponentsBowerPath+"/resourcelocks/nullresourcelock"],returnFirstDependency))}function init(){Dashboard.isRunningInCordova()&&browserInfo.android&&define("nativedirectorychooser",["cordova/nativedirectorychooser"]),Dashboard.isRunningInCordova()&&browserInfo.android?define("localsync",["cordova/localsync"],returnFirstDependency):define("localsync",["scripts/localsync"],returnFirstDependency),define("livetvcss",["css!css/livetv.css"]),define("detailtablecss",["css!css/detailtable.css"]),define("autoorganizetablecss",["css!css/autoorganizetable.css"]),define("buttonenabled",["legacy/buttonenabled"]),initAfterDependencies()}function getRequirePromise(deps){return new Promise(function(resolve,reject){require(deps,resolve)})}function initAfterDependencies(){var list=[];window.fetch||list.push("fetch"),"function"!=typeof Object.assign&&list.push("objectassign"),Array.prototype.filter||list.push("arraypolyfills"),Function.prototype.bind||list.push("functionbind"),window.requestAnimationFrame||list.push("raf"),require(list,function(){createConnectionManager().then(function(){console.log("initAfterDependencies promises resolved"),require(["globalize"],function(globalize){window.Globalize=globalize,Promise.all([loadCoreDictionary(globalize),loadSharedComponentsDictionary(globalize)]).then(onGlobalizeInit)})})})}function loadSharedComponentsDictionary(globalize){var baseUrl="bower_components/emby-webcomponents/strings/",languages=["ar","bg-bg","ca","cs","da","de","el","en-gb","en-us","es-ar","es-mx","es","fi","fr","gsw","he","hr","hu","id","it","kk","ko","ms","nb","nl","pl","pt-br","pt-pt","ro","ru","sk","sl-si","sv","tr","uk","vi","zh-cn","zh-hk","zh-tw"],translations=languages.map(function(i){return{lang:i,path:baseUrl+i+".json"}});globalize.loadStrings({name:"sharedcomponents",translations:translations})}function loadCoreDictionary(globalize){var baseUrl="strings/",languages=["ar","bg-bg","ca","cs","da","de","el","en-gb","en-us","es-ar","es-mx","es","fi","fr","gsw","he","hr","hu","id","it","kk","ko","ms","nb","nl","pl","pt-br","pt-pt","ro","ru","sl-si","sv","tr","uk","vi","zh-cn","zh-hk","zh-tw"],translations=languages.map(function(i){return{lang:i,path:baseUrl+i+".json"}});return globalize.defaultModule("core"),globalize.loadStrings({name:"core",translations:translations})}function onGlobalizeInit(){document.title=Globalize.translateDocument(document.title,"core"),require(["apphost"],function(appHost){loadPlugins([],appHost,browserInfo).then(onAppReady)})}function defineRoute(newRoute,dictionary){var baseRoute=Emby.Page.baseUrl(),path=newRoute.path;path=path.replace(baseRoute,""),console.log("Defining route: "+path),newRoute.dictionary=newRoute.dictionary||dictionary||"core",Emby.Page.addRoute(path,newRoute)}function defineCoreRoutes(){console.log("Defining core routes"),defineRoute({path:"/addplugin.html",dependencies:[],autoFocus:!1,roles:"admin",controller:"scripts/addpluginpage"}),defineRoute({path:"/appservices.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/autoorganizelog.html",dependencies:["scripts/taskbutton","autoorganizetablecss"],controller:"dashboard/autoorganizelog",roles:"admin"}),defineRoute({path:"/autoorganizesmart.html",dependencies:["emby-button"],controller:"dashboard/autoorganizesmart",autoFocus:!1,roles:"admin"}),defineRoute({path:"/autoorganizetv.html",dependencies:["emby-checkbox","emby-input","emby-button","emby-select","emby-collapse"],controller:"dashboard/autoorganizetv",autoFocus:!1,roles:"admin"}),defineRoute({path:"/channelitems.html",dependencies:[],autoFocus:!1,transition:"fade"}),defineRoute({path:"/channels.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/channels"}),defineRoute({path:"/channelsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/cinemamodeconfiguration.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/connectlogin.html",dependencies:["emby-button","emby-input"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/connectlogin"}),defineRoute({path:"/dashboard.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dashboardgeneral.html",controller:"dashboard/dashboardgeneral",autoFocus:!1,roles:"admin"}),defineRoute({path:"/dashboardhosting.html",dependencies:["emby-input","emby-button"],autoFocus:!1,roles:"admin",controller:"dashboard/dashboardhosting"}),defineRoute({path:"/device.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/devices.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/devicesupload.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaprofile.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaprofiles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnaserversettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/dlnasettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/edititemmetadata.html",dependencies:[],controller:"scripts/edititemmetadata",autoFocus:!1}),defineRoute({path:"/encodingsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/favorites.html",dependencies:[],autoFocus:!1,controller:"scripts/favorites"}),defineRoute({path:"/forgotpassword.html",dependencies:["emby-input","emby-button"],anonymous:!0,startup:!0,controller:"scripts/forgotpassword"}),defineRoute({path:"/forgotpasswordpin.html",dependencies:["emby-input","emby-button"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/forgotpasswordpin"}),defineRoute({path:"/gamegenres.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/games.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamesrecommended.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamestudios.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/gamesystems.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/home.html",dependencies:[],autoFocus:!1,controller:"scripts/indexpage",transition:"fade",type:"home"}),defineRoute({path:"/index.html",dependencies:[],autoFocus:!1,isDefaultRoute:!0}),defineRoute({path:"/itemdetails.html",dependencies:["emby-button","scripts/livetvcomponents","paper-icon-button-light","emby-itemscontainer"],controller:"scripts/itemdetailpage",autoFocus:!1,transition:"fade"}),defineRoute({path:"/itemlist.html",dependencies:[],autoFocus:!1,controller:"scripts/itemlistpage",transition:"fade"}),defineRoute({path:"/kids.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/library.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/librarydisplay.html",dependencies:[],autoFocus:!1,roles:"admin",controller:"dashboard/librarydisplay"}),defineRoute({path:"/librarysettings.html",dependencies:["emby-collapse","emby-input","emby-button","emby-select"],autoFocus:!1,roles:"admin",controller:"dashboard/librarysettings"}),defineRoute({path:"/livetv.html",dependencies:["emby-button","livetvcss"],controller:"scripts/livetvsuggested",autoFocus:!1,transition:"fade"}),defineRoute({path:"/livetvguideprovider.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvitems.html",dependencies:[],autoFocus:!1,controller:"scripts/livetvitems"}),defineRoute({path:"/livetvseriestimer.html",dependencies:["emby-checkbox","emby-input","emby-button","emby-collapse","scripts/livetvcomponents","scripts/livetvseriestimer","livetvcss"],autoFocus:!1,controller:"scripts/livetvseriestimer"}),defineRoute({path:"/livetvsettings.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/livetvstatus.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvtunerprovider-hdhomerun.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvtunerprovider-m3u.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/livetvtunerprovider-satip.html",dependencies:["emby-input"],autoFocus:!1,roles:"admin",controller:"dashboard/livetvtunerprovider-satip"}),defineRoute({path:"/log.html",dependencies:["emby-checkbox"],roles:"admin",controller:"dashboard/logpage"}),defineRoute({path:"/login.html",dependencies:["emby-button","emby-input"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/loginpage"}),defineRoute({path:"/metadataadvanced.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadataimages.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadatanfo.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/metadatasubtitles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/movies.html",dependencies:["emby-button"],autoFocus:!1,controller:"scripts/moviesrecommended",transition:"fade"}),defineRoute({path:"/music.html",dependencies:[],controller:"scripts/musicrecommended",autoFocus:!1,transition:"fade"}),defineRoute({path:"/mypreferencesdisplay.html",dependencies:["emby-checkbox","emby-button","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferencesdisplay"}),defineRoute({path:"/mypreferenceshome.html",dependencies:["emby-checkbox","emby-button","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferenceshome"}),defineRoute({path:"/mypreferenceslanguages.html",dependencies:["emby-button","emby-checkbox","emby-select"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferenceslanguages"}),defineRoute({path:"/mypreferencesmenu.html",dependencies:["emby-button"],autoFocus:!1,transition:"fade",controller:"scripts/mypreferencescommon"}),defineRoute({path:"/myprofile.html",dependencies:["emby-button","emby-collapse","emby-checkbox","emby-input"],autoFocus:!1,transition:"fade",controller:"scripts/myprofile"}),defineRoute({path:"/mysync.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/mysync"}),defineRoute({path:"/camerauploadsettings.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/camerauploadsettings"}),defineRoute({path:"/mysyncjob.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/syncjob"}),defineRoute({path:"/mysyncsettings.html",dependencies:["emby-checkbox","emby-input","emby-button","paper-icon-button-light"],autoFocus:!1,transition:"fade",controller:"scripts/mysyncsettings"}),defineRoute({path:"/notificationlist.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/notificationsetting.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/notificationsettings.html",controller:"scripts/notificationsettings",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/nowplaying.html",dependencies:["paper-icon-button-light","emby-slider","emby-button","emby-input","emby-itemscontainer"],controller:"scripts/nowplayingpage",autoFocus:!1,transition:"fade",fullscreen:!0,supportsThemeMedia:!0}),defineRoute({path:"/photos.html",dependencies:[],autoFocus:!1,transition:"fade"}),defineRoute({path:"/playbackconfiguration.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/playlists.html",dependencies:[],autoFocus:!1,transition:"fade",controller:"scripts/playlists"}),defineRoute({path:"/plugincatalog.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/plugins.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/reports.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/scheduledtask.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/scheduledtasks.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/search.html",dependencies:[],controller:"scripts/searchpage"}),defineRoute({path:"/secondaryitems.html",dependencies:[],autoFocus:!1,controller:"scripts/secondaryitems"}),defineRoute({path:"/selectserver.html",dependencies:["listViewStyle","emby-button"],autoFocus:!1,anonymous:!0,startup:!0,controller:"scripts/selectserver"}),defineRoute({path:"/serversecurity.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/shared.html",dependencies:[],autoFocus:!1,anonymous:!0}),defineRoute({path:"/streamingsettings.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/support.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/supporterkey.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/syncactivity.html",dependencies:[],autoFocus:!1,controller:"scripts/syncactivity"}),defineRoute({path:"/syncsettings.html",dependencies:[],autoFocus:!1}),defineRoute({path:"/tv.html",dependencies:["paper-icon-button-light","emby-button"],autoFocus:!1,controller:"scripts/tvrecommended",transition:"fade"}),defineRoute({path:"/useredit.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userlibraryaccess.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/usernew.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userparentalcontrol.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/userpassword.html",dependencies:["emby-input","emby-button","emby-checkbox"],autoFocus:!1,controller:"scripts/userpasswordpage"}),defineRoute({path:"/userprofiles.html",dependencies:[],autoFocus:!1,roles:"admin"}),defineRoute({path:"/wizardagreement.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardcomponents.html",dependencies:["dashboardcss","emby-button","emby-input","emby-select"],autoFocus:!1,anonymous:!0,controller:"dashboard/wizardcomponents"}),defineRoute({path:"/wizardfinish.html",dependencies:["emby-button","dashboardcss"],autoFocus:!1,anonymous:!0,controller:"dashboard/wizardfinishpage"}),defineRoute({path:"/wizardlibrary.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardlivetvguide.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardlivetvtuner.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardsettings.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizardstart.html",dependencies:["dashboardcss"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/wizarduser.html",dependencies:["dashboardcss","emby-input"],autoFocus:!1,anonymous:!0}),defineRoute({path:"/videoosd.html",dependencies:[],transition:"fade",controller:"scripts/videoosd",autoFocus:!1,type:"video-osd",supportsThemeMedia:!0,fullscreen:!0}),defineRoute({path:"/configurationpage",dependencies:["jQuery"],autoFocus:!1,enableCache:!1,enableContentQueryString:!0,roles:"admin"}),defineRoute({path:"/",isDefaultRoute:!0,autoFocus:!1,dependencies:[]})}function loadPlugins(externalPlugins,appHost,browser,shell){console.log("Loading installed plugins");var list=["bower_components/emby-webcomponents/playback/playbackvalidation"];Dashboard.isRunningInCordova()&&browser.android?(document.createElement("audio").canPlayType("audio/flac").replace(/no/,"")&&document.createElement("audio").canPlayType('audio/ogg; codecs="opus"').replace(/no/,"")||(window.VlcAudio=!0),list.push("cordova/vlcplayer")):Dashboard.isRunningInCordova()&&browser.safari&&list.push("cordova/audioplayer"),list.push("bower_components/emby-webcomponents/htmlaudioplayer/plugin"),Dashboard.isRunningInCordova()&&browser.safari&&list.push("cordova/chromecast"),Dashboard.isRunningInCordova()&&browser.android&&list.push("cordova/externalplayer"),list.push("bower_components/emby-webcomponents/htmlvideoplayer/plugin"),appHost.supports("remotecontrol")&&(list.push("bower_components/emby-webcomponents/sessionplayer"),browser.chrome&&list.push("bower_components/emby-webcomponents/chromecastplayer")),list.push("bower_components/emby-webcomponents/youtubeplayer/plugin");for(var i=0,length=externalPlugins.length;i', ''); - - page.querySelector('.lnkPremiere').addEventListener('click', onSupporterLinkClick); - - }).on('pageshow', "#supporterKeyPage", function () { - - var page = this; - loadUserInfo(page); - load(page); - }); - -}); \ No newline at end of file +define(["fetchHelper","jQuery","registrationServices"],function(fetchHelper,$,registrationServices){"use strict";function load(page){Dashboard.showLoadingMsg(),ApiClient.getPluginSecurityInfo().then(function(info){$("#txtSupporterKey",page).val(info.SupporterKey),info.SupporterKey&&!info.IsMBSupporter?(page.querySelector("#txtSupporterKey").classList.add("invalidEntry"),$(".notSupporter",page).show()):(page.querySelector("#txtSupporterKey").classList.remove("invalidEntry"),$(".notSupporter",page).hide()),Dashboard.hideLoadingMsg()})}function loadUserInfo(page){Dashboard.getPluginSecurityInfo().then(function(info){info.IsMBSupporter?$(".supporterContainer",page).addClass("hide"):$(".supporterContainer",page).removeClass("hide")})}function retrieveSupporterKey(){Dashboard.showLoadingMsg();var form=this,email=$("#txtEmail",form).val(),url="https://mb3admin.com/admin/service/supporter/retrievekey?email="+email;return console.log(url),fetchHelper.ajax({url:url,type:"POST",dataType:"json"}).then(function(result){Dashboard.hideLoadingMsg(),result.Success?require(["toast"],function(toast){toast(Globalize.translate("MessageKeyEmailedTo").replace("{0}",email))}):require(["toast"],function(toast){toast(result.ErrorMessage)}),console.log(result)}),!1}function onSupporterLinkClick(e){registrationServices.showPremiereInfo(),e.preventDefault(),e.stopPropagation()}var SupporterKeyPage={updateSupporterKey:function(){Dashboard.showLoadingMsg();var form=this,key=$("#txtSupporterKey",form).val(),info={SupporterKey:key};return ApiClient.updatePluginSecurityInfo(info).then(function(){Dashboard.resetPluginSecurityInfo(),Dashboard.hideLoadingMsg(),key?Dashboard.alert({message:Globalize.translate("MessageKeyUpdated"),title:Globalize.translate("HeaderConfirmation")}):Dashboard.alert({message:Globalize.translate("MessageKeyRemoved"),title:Globalize.translate("HeaderConfirmation")});var page=$(form).parents(".page")[0];load(page)}),!1},linkSupporterKeys:function(){Dashboard.showLoadingMsg();var form=this,email=$("#txtNewEmail",form).val(),newkey=$("#txtNewKey",form).val(),oldkey=$("#txtOldKey",form).val(),url="https://mb3admin.com/admin/service/supporter/linkKeys";return console.log(url),fetchHelper.ajax({url:url,type:"POST",dataType:"json",query:{email:email,newkey:newkey,oldkey:oldkey}}).then(function(result){Dashboard.hideLoadingMsg(),result.Success?require(["toast"],function(toast){toast(Globalize.translate("MessageKeysLinked"))}):require(["toast"],function(toast){toast(result.ErrorMessage)}),console.log(result)}),!1}};$(document).on("pageinit","#supporterKeyPage",function(){var page=this;$("#supporterKeyForm",this).on("submit",SupporterKeyPage.updateSupporterKey),$("#lostKeyForm",this).on("submit",retrieveSupporterKey),$("#linkKeysForm",this).on("submit",SupporterKeyPage.linkSupporterKeys),page.querySelector(".benefits").innerHTML=Globalize.translate("HeaderSupporterBenefit",'',""),page.querySelector(".lnkPremiere").addEventListener("click",onSupporterLinkClick)}).on("pageshow","#supporterKeyPage",function(){var page=this;loadUserInfo(page),load(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/syncactivity.js b/dashboard-ui/scripts/syncactivity.js index 607a3bf83e..9d73c21be7 100644 --- a/dashboard-ui/scripts/syncactivity.js +++ b/dashboard-ui/scripts/syncactivity.js @@ -1,61 +1 @@ -define(['loading', 'apphost', 'globalize', 'syncJobList', 'events', 'scripts/taskbutton', 'localsync', 'emby-button', 'paper-icon-button-light'], function (loading, appHost, globalize, syncJobList, events, taskButton) { - 'use strict'; - - function getTabs() { - return [ - { - href: 'syncactivity.html', - name: Globalize.translate('TabSyncJobs') - }, - { - href: 'devicesupload.html', - name: Globalize.translate('TabCameraUpload') - }, - { - href: 'appservices.html?context=sync', - name: Globalize.translate('TabServices') - }, - { - href: 'syncsettings.html', - name: Globalize.translate('TabSettings') - }]; - } - - return function (view, params) { - - var mySyncJobList = new syncJobList({ - isLocalSync: params.mode === 'offline', - serverId: ApiClient.serverId(), - userId: params.mode === 'offline' ? null : ApiClient.getCurrentUserId(), - element: view.querySelector('.syncActivity'), - mode: params.mode - }); - - view.addEventListener('viewshow', function () { - - LibraryMenu.setTabs('syncadmin', 0, getTabs); - - taskButton({ - mode: 'on', - progressElem: view.querySelector('.syncProgress'), - taskKey: 'SyncPrepare', - button: view.querySelector('.btnSync') - }); - }); - - view.addEventListener('viewbeforehide', function () { - - taskButton({ - mode: 'off', - taskKey: 'SyncPrepare', - button: view.querySelector('.btnSync') - }); - }); - - view.addEventListener('viewdestroy', function () { - - mySyncJobList.destroy(); - }); - }; - -}); \ No newline at end of file +define(["loading","apphost","globalize","syncJobList","events","scripts/taskbutton","localsync","emby-button","paper-icon-button-light"],function(loading,appHost,globalize,syncJobList,events,taskButton){"use strict";function getTabs(){return[{href:"syncactivity.html",name:Globalize.translate("TabSyncJobs")},{href:"devicesupload.html",name:Globalize.translate("TabCameraUpload")},{href:"appservices.html?context=sync",name:Globalize.translate("TabServices")},{href:"syncsettings.html",name:Globalize.translate("TabSettings")}]}return function(view,params){var mySyncJobList=new syncJobList({isLocalSync:"offline"===params.mode,serverId:ApiClient.serverId(),userId:"offline"===params.mode?null:ApiClient.getCurrentUserId(),element:view.querySelector(".syncActivity"),mode:params.mode});view.addEventListener("viewshow",function(){LibraryMenu.setTabs("syncadmin",0,getTabs),taskButton({mode:"on",progressElem:view.querySelector(".syncProgress"),taskKey:"SyncPrepare",button:view.querySelector(".btnSync")})}),view.addEventListener("viewbeforehide",function(){taskButton({mode:"off",taskKey:"SyncPrepare",button:view.querySelector(".btnSync")})}),view.addEventListener("viewdestroy",function(){mySyncJobList.destroy()})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/syncsettings.js b/dashboard-ui/scripts/syncsettings.js index f7c99178a1..8054af66f0 100644 --- a/dashboard-ui/scripts/syncsettings.js +++ b/dashboard-ui/scripts/syncsettings.js @@ -1,92 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function loadPage(page, config) { - - $('#txtSyncTempPath', page).val(config.TemporaryPath || ''); - $('#txtUploadSpeedLimit', page).val((config.UploadSpeedLimitBytes / 1000000) || ''); - $('#txtCpuCoreLimit', page).val(config.TranscodingCpuCoreLimit); - $('#chkEnableFullSpeedConversion', page).checked(config.EnableFullSpeedTranscoding); - - Dashboard.hideLoadingMsg(); - } - - function onSubmit() { - Dashboard.showLoadingMsg(); - - var form = this; - - ApiClient.getNamedConfiguration("sync").then(function (config) { - - config.TemporaryPath = $('#txtSyncTempPath', form).val(); - config.UploadSpeedLimitBytes = parseInt(parseFloat(($('#txtUploadSpeedLimit', form).val() || '0')) * 1000000); - config.TranscodingCpuCoreLimit = parseInt($('#txtCpuCoreLimit', form).val()); - config.EnableFullSpeedTranscoding = $('#chkEnableFullSpeedConversion', form).checked(); - - ApiClient.updateNamedConfiguration("sync", config).then(Dashboard.processServerConfigurationUpdateResult); - }); - - // Disable default form submission - return false; - } - - function getTabs() { - return [ - { - href: 'syncactivity.html', - name: Globalize.translate('TabSyncJobs') - }, - { - href: 'devicesupload.html', - name: Globalize.translate('TabCameraUpload') - }, - { - href: 'appservices.html?context=sync', - name: Globalize.translate('TabServices') - }, - { - href: 'syncsettings.html', - name: Globalize.translate('TabSettings') - }]; - } - - $(document).on('pageinit', "#syncSettingsPage", function () { - - var page = this; - - $('#btnSelectSyncTempPath', page).on("click.selectDirectory", function () { - - require(['directorybrowser'], function (directoryBrowser) { - - var picker = new directoryBrowser(); - - picker.show({ - - callback: function (path) { - if (path) { - $('#txtSyncTempPath', page).val(path); - } - picker.close(); - } - }); - }); - }); - - $('.syncSettingsForm').off('submit', onSubmit).on('submit', onSubmit); - - - }).on('pageshow', "#syncSettingsPage", function () { - - Dashboard.showLoadingMsg(); - - LibraryMenu.setTabs('syncadmin', 3, getTabs); - var page = this; - - ApiClient.getNamedConfiguration("sync").then(function (config) { - - loadPage(page, config); - - }); - }); - -}); +define(["jQuery","fnchecked"],function($){"use strict";function loadPage(page,config){$("#txtSyncTempPath",page).val(config.TemporaryPath||""),$("#txtUploadSpeedLimit",page).val(config.UploadSpeedLimitBytes/1e6||""),$("#txtCpuCoreLimit",page).val(config.TranscodingCpuCoreLimit),$("#chkEnableFullSpeedConversion",page).checked(config.EnableFullSpeedTranscoding),Dashboard.hideLoadingMsg()}function onSubmit(){Dashboard.showLoadingMsg();var form=this;return ApiClient.getNamedConfiguration("sync").then(function(config){config.TemporaryPath=$("#txtSyncTempPath",form).val(),config.UploadSpeedLimitBytes=parseInt(1e6*parseFloat($("#txtUploadSpeedLimit",form).val()||"0")),config.TranscodingCpuCoreLimit=parseInt($("#txtCpuCoreLimit",form).val()),config.EnableFullSpeedTranscoding=$("#chkEnableFullSpeedConversion",form).checked(),ApiClient.updateNamedConfiguration("sync",config).then(Dashboard.processServerConfigurationUpdateResult)}),!1}function getTabs(){return[{href:"syncactivity.html",name:Globalize.translate("TabSyncJobs")},{href:"devicesupload.html",name:Globalize.translate("TabCameraUpload")},{href:"appservices.html?context=sync",name:Globalize.translate("TabServices")},{href:"syncsettings.html",name:Globalize.translate("TabSettings")}]}$(document).on("pageinit","#syncSettingsPage",function(){var page=this;$("#btnSelectSyncTempPath",page).on("click.selectDirectory",function(){require(["directorybrowser"],function(directoryBrowser){var picker=new directoryBrowser;picker.show({callback:function(path){path&&$("#txtSyncTempPath",page).val(path),picker.close()}})})}),$(".syncSettingsForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#syncSettingsPage",function(){Dashboard.showLoadingMsg(),LibraryMenu.setTabs("syncadmin",3,getTabs);var page=this;ApiClient.getNamedConfiguration("sync").then(function(config){loadPage(page,config)})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/taskbutton.js b/dashboard-ui/scripts/taskbutton.js index b3a8f9560a..a325a0c343 100644 --- a/dashboard-ui/scripts/taskbutton.js +++ b/dashboard-ui/scripts/taskbutton.js @@ -1,149 +1 @@ -define(['userSettings', 'emby-button'], function (userSettings) { - 'use strict'; - - return function (options) { - - var button = options.button; - - function pollTasks() { - - ApiClient.getScheduledTasks({ - - IsEnabled: true - - }).then(updateTasks); - } - - function updateTasks(tasks) { - - var task = tasks.filter(function (t) { - - return t.Key == options.taskKey; - - })[0]; - - if (options.panel) { - if (task) { - options.panel.classList.remove('hide'); - } else { - options.panel.classList.add('hide'); - } - } - - if (!task) { - return; - } - - if (task.State == 'Idle') { - button.removeAttribute('disabled'); - } else { - button.setAttribute('disabled', 'disabled'); - } - - button.setAttribute('data-taskid', task.Id); - - var progress = (task.CurrentProgressPercentage || 0).toFixed(1); - - if (options.progressElem) { - options.progressElem.value = progress; - - if (task.State == 'Running') { - options.progressElem.classList.remove('hide'); - } else { - options.progressElem.classList.add('hide'); - } - } - - if (options.lastResultElem) { - var lastResult = task.LastExecutionResult ? task.LastExecutionResult.Status : ''; - - if (lastResult == "Failed") { - options.lastResultElem.html('(' + Globalize.translate('LabelFailed') + ')'); - } - else if (lastResult == "Cancelled") { - options.lastResultElem.html('(' + Globalize.translate('LabelCancelled') + ')'); - } - else if (lastResult == "Aborted") { - options.lastResultElem.html('' + Globalize.translate('LabelAbortedByServerShutdown') + ''); - } else { - options.lastResultElem.html(lastResult); - } - } - } - - function onScheduledTaskMessageConfirmed(id) { - ApiClient.startScheduledTask(id).then(pollTasks); - } - - function onButtonClick() { - - var button = this; - var taskId = button.getAttribute('data-taskid'); - onScheduledTaskMessageConfirmed(taskId); - } - - function onSocketOpen() { - startInterval(); - } - - function onSocketMessage(e, msg) { - if (msg.MessageType == "ScheduledTasksInfo") { - - var tasks = msg.Data; - - updateTasks(tasks); - } - } - - var pollInterval; - - function onPollIntervalFired() { - - if (!ApiClient.isWebSocketOpen()) { - pollTasks(); - } - } - - function startInterval() { - if (ApiClient.isWebSocketOpen()) { - ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart", "1000,1000"); - } - if (pollInterval) { - clearInterval(pollInterval); - } - pollInterval = setInterval(onPollIntervalFired, 5000); - } - - function stopInterval() { - if (ApiClient.isWebSocketOpen()) { - ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"); - } - if (pollInterval) { - clearInterval(pollInterval); - } - } - - if (options.panel) { - options.panel.classList.add('hide'); - } - - if (options.mode == 'off') { - - button.removeEventListener('click', onButtonClick); - Events.off(ApiClient, 'websocketmessage', onSocketMessage); - Events.off(ApiClient, 'websocketopen', onSocketOpen); - stopInterval(); - - } else { - - button.addEventListener('click', onButtonClick); - - pollTasks(); - - startInterval(); - - Events.on(ApiClient, 'websocketmessage', onSocketMessage); - Events.on(ApiClient, 'websocketopen', onSocketOpen); - } - }; -}); \ No newline at end of file +define(["userSettings","emby-button"],function(userSettings){"use strict";return function(options){function pollTasks(){ApiClient.getScheduledTasks({IsEnabled:!0}).then(updateTasks)}function updateTasks(tasks){var task=tasks.filter(function(t){return t.Key==options.taskKey})[0];if(options.panel&&(task?options.panel.classList.remove("hide"):options.panel.classList.add("hide")),task){"Idle"==task.State?button.removeAttribute("disabled"):button.setAttribute("disabled","disabled"),button.setAttribute("data-taskid",task.Id);var progress=(task.CurrentProgressPercentage||0).toFixed(1);if(options.progressElem&&(options.progressElem.value=progress,"Running"==task.State?options.progressElem.classList.remove("hide"):options.progressElem.classList.add("hide")),options.lastResultElem){var lastResult=task.LastExecutionResult?task.LastExecutionResult.Status:"";"Failed"==lastResult?options.lastResultElem.html('('+Globalize.translate("LabelFailed")+")"):"Cancelled"==lastResult?options.lastResultElem.html('('+Globalize.translate("LabelCancelled")+")"):"Aborted"==lastResult?options.lastResultElem.html(''+Globalize.translate("LabelAbortedByServerShutdown")+""):options.lastResultElem.html(lastResult)}}}function onScheduledTaskMessageConfirmed(id){ApiClient.startScheduledTask(id).then(pollTasks)}function onButtonClick(){var button=this,taskId=button.getAttribute("data-taskid");onScheduledTaskMessageConfirmed(taskId)}function onSocketOpen(){startInterval()}function onSocketMessage(e,msg){if("ScheduledTasksInfo"==msg.MessageType){var tasks=msg.Data;updateTasks(tasks)}}function onPollIntervalFired(){ApiClient.isWebSocketOpen()||pollTasks()}function startInterval(){ApiClient.isWebSocketOpen()&&ApiClient.sendWebSocketMessage("ScheduledTasksInfoStart","1000,1000"),pollInterval&&clearInterval(pollInterval),pollInterval=setInterval(onPollIntervalFired,5e3)}function stopInterval(){ApiClient.isWebSocketOpen()&&ApiClient.sendWebSocketMessage("ScheduledTasksInfoStop"),pollInterval&&clearInterval(pollInterval)}var pollInterval,button=options.button;options.panel&&options.panel.classList.add("hide"),"off"==options.mode?(button.removeEventListener("click",onButtonClick),Events.off(ApiClient,"websocketmessage",onSocketMessage),Events.off(ApiClient,"websocketopen",onSocketOpen),stopInterval()):(button.addEventListener("click",onButtonClick),pollTasks(),startInterval(),Events.on(ApiClient,"websocketmessage",onSocketMessage),Events.on(ApiClient,"websocketopen",onSocketOpen))}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/tvgenres.js b/dashboard-ui/scripts/tvgenres.js index a2e5013b86..e3f65772e3 100644 --- a/dashboard-ui/scripts/tvgenres.js +++ b/dashboard-ui/scripts/tvgenres.js @@ -1,247 +1 @@ -define(['libraryBrowser', 'cardBuilder', 'lazyLoader', 'apphost', 'globalize', 'dom'], function (libraryBrowser, cardBuilder, lazyLoader, appHost, globalize, dom) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - - var data = {}; - function getPageData() { - var key = getSavedQueryKey(); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Series", - Recursive: true, - EnableTotalRecordCount: false - }, - view: libraryBrowser.getSavedView(key) || (appHost.preferVisualCards ? 'PosterCard' : 'Poster') - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery() { - - return getPageData().query; - } - - function getSavedQueryKey() { - - return libraryBrowser.getSavedQueryKey('seriesgenres'); - } - - function getPromise() { - - Dashboard.showLoadingMsg(); - var query = getQuery(); - - return ApiClient.getGenres(Dashboard.getCurrentUserId(), query); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function getThumbShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function getPortraitShape() { - return enableScrollX() ? 'overflowPortrait' : 'portrait'; - } - - function getMoreItemsHref(itemId, type) { - - return 'secondaryitems.html?type=' + type + '&genreId=' + itemId + '&parentId=' + params.topParentId; - } - - dom.addEventListener(tabContent, 'click', function (e) { - - var btnMoreFromGenre = dom.parentWithClass(e.target, 'btnMoreFromGenre'); - if (btnMoreFromGenre) { - var id = btnMoreFromGenre.getAttribute('data-id'); - Dashboard.navigate(getMoreItemsHref(id, 'Series')); - } - - }, { - passive: true - }); - - function fillItemsContainer(elem) { - - var id = elem.getAttribute('data-id'); - - var viewStyle = self.getCurrentViewStyle(); - - var limit = viewStyle == 'Thumb' || viewStyle == 'ThumbCard' ? - 5 : - 8; - - if (enableScrollX()) { - limit = 10; - } - - var enableImageTypes = viewStyle == 'Thumb' || viewStyle == 'ThumbCard' ? - "Primary,Backdrop,Thumb" : - "Primary"; - - var query = { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Series", - Recursive: true, - Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: enableImageTypes, - Limit: limit, - GenreIds: id, - EnableTotalRecordCount: false, - ParentId: params.topParentId - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - if (viewStyle == "Thumb") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getThumbShape(), - preferThumb: true, - showTitle: true, - scalable: true, - centerText: true, - overlayMoreButton: true, - allowBottomPadding: false - }); - } - else if (viewStyle == "ThumbCard") { - - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getThumbShape(), - preferThumb: true, - showTitle: true, - scalable: true, - centerText: false, - cardLayout: true, - vibrant: supportsImageAnalysis, - showSeriesYear: true - }); - } - else if (viewStyle == "PosterCard") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getPortraitShape(), - showTitle: true, - scalable: true, - centerText: false, - cardLayout: true, - vibrant: supportsImageAnalysis, - showSeriesYear: true - }); - } - else if (viewStyle == "Poster") { - cardBuilder.buildCards(result.Items, { - itemsContainer: elem, - shape: getPortraitShape(), - showTitle: true, - scalable: true, - centerText: true, - overlayMoreButton: true, - allowBottomPadding: false - }); - } - - if (result.Items.length >= query.Limit) { - tabContent.querySelector('.btnMoreFromGenre' + id).classList.remove('hide'); - } - }); - } - - function reloadItems(context, promise) { - - var query = getQuery(); - - promise.then(function (result) { - - var elem = context.querySelector('#items'); - var html = ''; - - var items = result.Items; - - for (var i = 0, length = items.length; i < length; i++) { - - var item = items[i]; - - html += '
'; - - html += '
'; - html += '

'; - html += item.Name; - html += '

'; - html += ''; - html += '
'; - - if (enableScrollX()) { - html += '
'; - } else { - html += '
'; - } - html += '
'; - - html += '
'; - } - - elem.innerHTML = html; - - lazyLoader.lazyChildren(elem, fillItemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.getViewStyles = function () { - return 'Poster,PosterCard,Thumb,ThumbCard'.split(','); - }; - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - self.setCurrentViewStyle = function (viewStyle) { - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - fullyReload(); - }; - - self.enableViewSelection = true; - var promise; - - self.preRender = function () { - promise = getPromise(); - }; - - self.renderTab = function () { - - reloadItems(tabContent, promise); - }; - - function fullyReload() { - self.preRender(); - self.renderTab(); - } - }; -}); \ No newline at end of file +define(["libraryBrowser","cardBuilder","lazyLoader","apphost","globalize","dom"],function(libraryBrowser,cardBuilder,lazyLoader,appHost,globalize,dom){"use strict";return function(view,params,tabContent){function getPageData(){var key=getSavedQueryKey(),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Series",Recursive:!0,EnableTotalRecordCount:!1},view:libraryBrowser.getSavedView(key)||(appHost.preferVisualCards?"PosterCard":"Poster")},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(){return getPageData().query}function getSavedQueryKey(){return libraryBrowser.getSavedQueryKey("seriesgenres")}function getPromise(){Dashboard.showLoadingMsg();var query=getQuery();return ApiClient.getGenres(Dashboard.getCurrentUserId(),query)}function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function getPortraitShape(){return enableScrollX()?"overflowPortrait":"portrait"}function getMoreItemsHref(itemId,type){return"secondaryitems.html?type="+type+"&genreId="+itemId+"&parentId="+params.topParentId}function fillItemsContainer(elem){var id=elem.getAttribute("data-id"),viewStyle=self.getCurrentViewStyle(),limit="Thumb"==viewStyle||"ThumbCard"==viewStyle?5:8;enableScrollX()&&(limit=10);var enableImageTypes="Thumb"==viewStyle||"ThumbCard"==viewStyle?"Primary,Backdrop,Thumb":"Primary",query={SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Series",Recursive:!0,Fields:"PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:enableImageTypes,Limit:limit,GenreIds:id,EnableTotalRecordCount:!1,ParentId:params.topParentId};ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){var supportsImageAnalysis=appHost.supports("imageanalysis");"Thumb"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getThumbShape(),preferThumb:!0,showTitle:!0,scalable:!0,centerText:!0,overlayMoreButton:!0,allowBottomPadding:!1}):"ThumbCard"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getThumbShape(),preferThumb:!0,showTitle:!0,scalable:!0,centerText:!1,cardLayout:!0,vibrant:supportsImageAnalysis,showSeriesYear:!0}):"PosterCard"==viewStyle?cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getPortraitShape(),showTitle:!0,scalable:!0,centerText:!1,cardLayout:!0,vibrant:supportsImageAnalysis,showSeriesYear:!0}):"Poster"==viewStyle&&cardBuilder.buildCards(result.Items,{itemsContainer:elem,shape:getPortraitShape(),showTitle:!0,scalable:!0,centerText:!0,overlayMoreButton:!0,allowBottomPadding:!1}),result.Items.length>=query.Limit&&tabContent.querySelector(".btnMoreFromGenre"+id).classList.remove("hide")})}function reloadItems(context,promise){var query=getQuery();promise.then(function(result){for(var elem=context.querySelector("#items"),html="",items=result.Items,i=0,length=items.length;i',html+='
',html+='

',html+=item.Name,html+="

",html+='",html+="
",html+=enableScrollX()?'
':'
',html+="
",html+="
"}elem.innerHTML=html,lazyLoader.lazyChildren(elem,fillItemsContainer),libraryBrowser.saveQueryValues(getSavedQueryKey(),query),Dashboard.hideLoadingMsg()})}function fullyReload(){self.preRender(),self.renderTab()}var self=this,data={};dom.addEventListener(tabContent,"click",function(e){var btnMoreFromGenre=dom.parentWithClass(e.target,"btnMoreFromGenre");if(btnMoreFromGenre){var id=btnMoreFromGenre.getAttribute("data-id");Dashboard.navigate(getMoreItemsHref(id,"Series"))}},{passive:!0}),self.getViewStyles=function(){return"Poster,PosterCard,Thumb,ThumbCard".split(",")},self.getCurrentViewStyle=function(){return getPageData(tabContent).view},self.setCurrentViewStyle=function(viewStyle){getPageData(tabContent).view=viewStyle,libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent),viewStyle),fullyReload()},self.enableViewSelection=!0;var promise;self.preRender=function(){promise=getPromise()},self.renderTab=function(){reloadItems(tabContent,promise)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/tvlatest.js b/dashboard-ui/scripts/tvlatest.js index 3b92833fec..09442f3f76 100644 --- a/dashboard-ui/scripts/tvlatest.js +++ b/dashboard-ui/scripts/tvlatest.js @@ -1,81 +1 @@ -define(['components/categorysyncbuttons', 'components/groupedcards', 'cardBuilder', 'apphost', 'imageLoader'], function (categorysyncbuttons, groupedcards, cardBuilder, appHost, imageLoader) { - 'use strict'; - - function getView() { - - return 'Thumb'; - } - - function getLatestPromise(context, params) { - - Dashboard.showLoadingMsg(); - - var userId = Dashboard.getCurrentUserId(); - - var parentId = params.topParentId; - - var options = { - - IncludeItemTypes: "Episode", - Limit: 30, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb" - }; - - return ApiClient.getJSON(ApiClient.getUrl('Users/' + userId + '/Items/Latest', options)); - } - - function loadLatest(context, params, promise) { - - promise.then(function (items) { - - var html = ''; - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = supportsImageAnalysis; - - html += cardBuilder.getCardsHtml({ - items: items, - shape: "backdrop", - preferThumb: true, - showTitle: true, - showSeriesYear: true, - showParentTitle: true, - overlayText: false, - cardLayout: cardLayout, - showUnplayedIndicator: false, - showChildCountIndicator: true, - centerText: !cardLayout, - lazy: true, - overlayPlayButton: true, - vibrant: supportsImageAnalysis, - lines: 2 - }); - - var elem = context.querySelector('#latestEpisodes'); - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - - Dashboard.hideLoadingMsg(); - }); - } - return function (view, params, tabContent) { - - var self = this; - - categorysyncbuttons.init(tabContent); var latestPromise; - - self.preRender = function () { - latestPromise = getLatestPromise(view, params); - }; - - self.renderTab = function () { - - loadLatest(tabContent, params, latestPromise); - }; - - tabContent.querySelector('#latestEpisodes').addEventListener('click', groupedcards.onItemsContainerClick); - }; -}); \ No newline at end of file +define(["components/categorysyncbuttons","components/groupedcards","cardBuilder","apphost","imageLoader"],function(categorysyncbuttons,groupedcards,cardBuilder,appHost,imageLoader){"use strict";function getLatestPromise(context,params){Dashboard.showLoadingMsg();var userId=Dashboard.getCurrentUserId(),parentId=params.topParentId,options={IncludeItemTypes:"Episode",Limit:30,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb"};return ApiClient.getJSON(ApiClient.getUrl("Users/"+userId+"/Items/Latest",options))}function loadLatest(context,params,promise){promise.then(function(items){var html="",supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis;html+=cardBuilder.getCardsHtml({items:items,shape:"backdrop",preferThumb:!0,showTitle:!0,showSeriesYear:!0,showParentTitle:!0,overlayText:!1,cardLayout:cardLayout,showUnplayedIndicator:!1,showChildCountIndicator:!0,centerText:!cardLayout,lazy:!0,overlayPlayButton:!0,vibrant:supportsImageAnalysis,lines:2});var elem=context.querySelector("#latestEpisodes");elem.innerHTML=html,imageLoader.lazyChildren(elem),Dashboard.hideLoadingMsg()})}return function(view,params,tabContent){var self=this;categorysyncbuttons.init(tabContent);var latestPromise;self.preRender=function(){latestPromise=getLatestPromise(view,params)},self.renderTab=function(){loadLatest(tabContent,params,latestPromise)},tabContent.querySelector("#latestEpisodes").addEventListener("click",groupedcards.onItemsContainerClick)}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/tvrecommended.js b/dashboard-ui/scripts/tvrecommended.js index a97d0ad1a6..0e2b12dc95 100644 --- a/dashboard-ui/scripts/tvrecommended.js +++ b/dashboard-ui/scripts/tvrecommended.js @@ -1,304 +1 @@ -define(['libraryBrowser', 'dom', 'components/categorysyncbuttons', 'cardBuilder', 'apphost', 'playbackManager', 'scrollStyles', 'emby-itemscontainer', 'emby-tabs', 'emby-button'], function (libraryBrowser, dom, categorysyncbuttons, cardBuilder, appHost, playbackManager) { - 'use strict'; - - return function (view, params) { - - var self = this; - - function reload() { - - Dashboard.showLoadingMsg(); - - loadResume(); - loadNextUp(); - } - - function loadNextUp() { - - var query = { - - Limit: 24, - Fields: "PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo", - UserId: Dashboard.getCurrentUserId(), - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb" - }; - - query.ParentId = LibraryMenu.getTopParentId(); - - ApiClient.getNextUpEpisodes(query).then(function (result) { - - if (result.Items.length) { - view.querySelector('.noNextUpItems').classList.add('hide'); - } else { - view.querySelector('.noNextUpItems').classList.remove('hide'); - } - - var container = view.querySelector('#nextUpItems'); - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - cardBuilder.buildCards(result.Items, { - itemsContainer: container, - preferThumb: true, - shape: "backdrop", - scalable: true, - showTitle: true, - showParentTitle: true, - overlayText: false, - centerText: !supportsImageAnalysis, - overlayPlayButton: true, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - }); - - Dashboard.hideLoadingMsg(); - }); - } - - function enableScrollX() { - return browserInfo.mobile; - } - - function getThumbShape() { - return enableScrollX() ? 'overflowBackdrop' : 'backdrop'; - } - - function loadResume() { - - var parentId = LibraryMenu.getTopParentId(); - - var screenWidth = dom.getWindowSize().innerWidth; - var limit = screenWidth >= 1600 ? 5 : 6; - - var options = { - - SortBy: "DatePlayed", - SortOrder: "Descending", - IncludeItemTypes: "Episode", - Filters: "IsResumable", - Limit: limit, - Recursive: true, - Fields: "PrimaryImageAspectRatio,SeriesInfo,UserData,BasicSyncInfo", - ExcludeLocationTypes: "Virtual", - ParentId: parentId, - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Thumb", - EnableTotalRecordCount: false - }; - - ApiClient.getItems(Dashboard.getCurrentUserId(), options).then(function (result) { - - if (result.Items.length) { - view.querySelector('#resumableSection').classList.remove('hide'); - } else { - view.querySelector('#resumableSection').classList.add('hide'); - } - - var allowBottomPadding = !enableScrollX(); - - var container = view.querySelector('#resumableItems'); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - var cardLayout = supportsImageAnalysis; - - cardBuilder.buildCards(result.Items, { - itemsContainer: container, - preferThumb: true, - shape: getThumbShape(), - scalable: true, - showTitle: true, - showParentTitle: true, - overlayText: false, - centerText: !cardLayout, - overlayPlayButton: true, - allowBottomPadding: allowBottomPadding, - cardLayout: cardLayout, - vibrant: supportsImageAnalysis - }); - }); - } - - self.initTab = function () { - - var tabContent = self.tabContent; - - var resumableItemsContainer = tabContent.querySelector('#resumableItems'); - - if (enableScrollX()) { - resumableItemsContainer.classList.add('hiddenScrollX'); - resumableItemsContainer.classList.remove('vertical-wrap'); - } else { - resumableItemsContainer.classList.remove('hiddenScrollX'); - resumableItemsContainer.classList.add('vertical-wrap'); - } - - categorysyncbuttons.init(tabContent); - }; - - self.renderTab = function () { - reload(); - }; - - var tabControllers = []; - var renderedTabs = []; - - function getTabController(page, index, callback) { - - var depends = []; - - switch (index) { - - case 0: - break; - case 1: - depends.push('scripts/tvlatest'); - break; - case 2: - depends.push('scripts/tvupcoming'); - break; - case 3: - depends.push('scripts/tvshows'); - break; - case 4: - depends.push('scripts/tvgenres'); - break; - case 5: - depends.push('scripts/tvstudios'); - break; - case 6: - depends.push('scripts/episodes'); - break; - default: - break; - } - - require(depends, function (controllerFactory) { - var tabContent; - if (index == 0) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - self.tabContent = tabContent; - } - var controller = tabControllers[index]; - if (!controller) { - tabContent = view.querySelector('.pageTabContent[data-index=\'' + index + '\']'); - controller = index ? new controllerFactory(view, params, tabContent) : self; - tabControllers[index] = controller; - - if (controller.initTab) { - controller.initTab(); - } - } - - callback(controller); - }); - } - - function preLoadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - if (controller.preRender) { - controller.preRender(); - } - } - }); - } - - function loadTab(page, index) { - - getTabController(page, index, function (controller) { - if (renderedTabs.indexOf(index) == -1) { - renderedTabs.push(index); - controller.renderTab(); - } - }); - } - - var viewTabs = view.querySelector('.libraryViewNav'); - - function onPlaybackStop(e, state) { - - if (state.NowPlayingItem && state.NowPlayingItem.MediaType == 'Video') { - - renderedTabs = []; - viewTabs.triggerTabChange(); - } - } - - if (enableScrollX()) { - view.querySelector('#resumableItems').classList.add('hiddenScrollX'); - } else { - view.querySelector('#resumableItems').classList.remove('hiddenScrollX'); - } - libraryBrowser.configurePaperLibraryTabs(view, viewTabs, view.querySelectorAll('.pageTabContent'), [0, 1, 2, 4, 5, 6]); - - viewTabs.addEventListener('beforetabchange', function (e) { - preLoadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - viewTabs.addEventListener('tabchange', function (e) { - loadTab(view, parseInt(e.detail.selectedTabIndex)); - }); - - function onWebSocketMessage(e, data) { - - var msg = data; - - if (msg.MessageType === "UserDataChanged") { - - if (msg.Data.UserId == Dashboard.getCurrentUserId()) { - - renderedTabs = []; - } - } - - } - - view.addEventListener('viewbeforeshow', function (e) { - - if (!view.getAttribute('data-title')) { - - var parentId = params.topParentId; - - if (parentId) { - - ApiClient.getItem(Dashboard.getCurrentUserId(), parentId).then(function (item) { - - view.setAttribute('data-title', item.Name); - LibraryMenu.setTitle(item.Name); - }); - - - } else { - view.setAttribute('data-title', Globalize.translate('TabShows')); - LibraryMenu.setTitle(Globalize.translate('TabShows')); - } - } - - Events.on(playbackManager, 'playbackstop', onPlaybackStop); - Events.on(ApiClient, "websocketmessage", onWebSocketMessage); - }); - - view.addEventListener('viewbeforehide', function (e) { - - Events.off(playbackManager, 'playbackstop', onPlaybackStop); - Events.off(ApiClient, "websocketmessage", onWebSocketMessage); - }); - - require(["headroom-window"], function (headroom) { - headroom.add(viewTabs); - self.headroom = headroom; - }); - - view.addEventListener('viewdestroy', function (e) { - - if (self.headroom) { - self.headroom.remove(viewTabs); - } - tabControllers.forEach(function (t) { - if (t.destroy) { - t.destroy(); - } - }); - }); - }; -}); \ No newline at end of file +define(["libraryBrowser","dom","components/categorysyncbuttons","cardBuilder","apphost","playbackManager","scrollStyles","emby-itemscontainer","emby-tabs","emby-button"],function(libraryBrowser,dom,categorysyncbuttons,cardBuilder,appHost,playbackManager){"use strict";return function(view,params){function reload(){Dashboard.showLoadingMsg(),loadResume(),loadNextUp()}function loadNextUp(){var query={Limit:24,Fields:"PrimaryImageAspectRatio,SeriesInfo,DateCreated,BasicSyncInfo",UserId:Dashboard.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb"};query.ParentId=LibraryMenu.getTopParentId(),ApiClient.getNextUpEpisodes(query).then(function(result){result.Items.length?view.querySelector(".noNextUpItems").classList.add("hide"):view.querySelector(".noNextUpItems").classList.remove("hide");var container=view.querySelector("#nextUpItems"),supportsImageAnalysis=appHost.supports("imageanalysis");cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:"backdrop",scalable:!0,showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!supportsImageAnalysis,overlayPlayButton:!0,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),Dashboard.hideLoadingMsg()})}function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function loadResume(){var parentId=LibraryMenu.getTopParentId(),screenWidth=dom.getWindowSize().innerWidth,limit=screenWidth>=1600?5:6,options={SortBy:"DatePlayed",SortOrder:"Descending",IncludeItemTypes:"Episode",Filters:"IsResumable",Limit:limit,Recursive:!0,Fields:"PrimaryImageAspectRatio,SeriesInfo,UserData,BasicSyncInfo",ExcludeLocationTypes:"Virtual",ParentId:parentId,ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Thumb",EnableTotalRecordCount:!1};ApiClient.getItems(Dashboard.getCurrentUserId(),options).then(function(result){result.Items.length?view.querySelector("#resumableSection").classList.remove("hide"):view.querySelector("#resumableSection").classList.add("hide");var allowBottomPadding=!enableScrollX(),container=view.querySelector("#resumableItems"),supportsImageAnalysis=appHost.supports("imageanalysis"),cardLayout=supportsImageAnalysis;cardBuilder.buildCards(result.Items,{itemsContainer:container,preferThumb:!0,shape:getThumbShape(),scalable:!0,showTitle:!0,showParentTitle:!0,overlayText:!1,centerText:!cardLayout,overlayPlayButton:!0,allowBottomPadding:allowBottomPadding,cardLayout:cardLayout,vibrant:supportsImageAnalysis})})}function getTabController(page,index,callback){var depends=[];switch(index){case 0:break;case 1:depends.push("scripts/tvlatest");break;case 2:depends.push("scripts/tvupcoming");break;case 3:depends.push("scripts/tvshows");break;case 4:depends.push("scripts/tvgenres");break;case 5:depends.push("scripts/tvstudios");break;case 6:depends.push("scripts/episodes")}require(depends,function(controllerFactory){var tabContent;0==index&&(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),self.tabContent=tabContent);var controller=tabControllers[index];controller||(tabContent=view.querySelector(".pageTabContent[data-index='"+index+"']"),controller=index?new controllerFactory(view,params,tabContent):self,tabControllers[index]=controller,controller.initTab&&controller.initTab()),callback(controller)})}function preLoadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&controller.preRender&&controller.preRender()})}function loadTab(page,index){getTabController(page,index,function(controller){renderedTabs.indexOf(index)==-1&&(renderedTabs.push(index),controller.renderTab())})}function onPlaybackStop(e,state){state.NowPlayingItem&&"Video"==state.NowPlayingItem.MediaType&&(renderedTabs=[],viewTabs.triggerTabChange())}function onWebSocketMessage(e,data){var msg=data;"UserDataChanged"===msg.MessageType&&msg.Data.UserId==Dashboard.getCurrentUserId()&&(renderedTabs=[])}var self=this;self.initTab=function(){var tabContent=self.tabContent,resumableItemsContainer=tabContent.querySelector("#resumableItems");enableScrollX()?(resumableItemsContainer.classList.add("hiddenScrollX"),resumableItemsContainer.classList.remove("vertical-wrap")):(resumableItemsContainer.classList.remove("hiddenScrollX"),resumableItemsContainer.classList.add("vertical-wrap")),categorysyncbuttons.init(tabContent)},self.renderTab=function(){reload()};var tabControllers=[],renderedTabs=[],viewTabs=view.querySelector(".libraryViewNav");enableScrollX()?view.querySelector("#resumableItems").classList.add("hiddenScrollX"):view.querySelector("#resumableItems").classList.remove("hiddenScrollX"),libraryBrowser.configurePaperLibraryTabs(view,viewTabs,view.querySelectorAll(".pageTabContent"),[0,1,2,4,5,6]),viewTabs.addEventListener("beforetabchange",function(e){preLoadTab(view,parseInt(e.detail.selectedTabIndex))}),viewTabs.addEventListener("tabchange",function(e){loadTab(view,parseInt(e.detail.selectedTabIndex))}),view.addEventListener("viewbeforeshow",function(e){if(!view.getAttribute("data-title")){var parentId=params.topParentId;parentId?ApiClient.getItem(Dashboard.getCurrentUserId(),parentId).then(function(item){view.setAttribute("data-title",item.Name),LibraryMenu.setTitle(item.Name)}):(view.setAttribute("data-title",Globalize.translate("TabShows")),LibraryMenu.setTitle(Globalize.translate("TabShows")))}Events.on(playbackManager,"playbackstop",onPlaybackStop),Events.on(ApiClient,"websocketmessage",onWebSocketMessage)}),view.addEventListener("viewbeforehide",function(e){Events.off(playbackManager,"playbackstop",onPlaybackStop),Events.off(ApiClient,"websocketmessage",onWebSocketMessage)}),require(["headroom-window"],function(headroom){headroom.add(viewTabs),self.headroom=headroom}),view.addEventListener("viewdestroy",function(e){self.headroom&&self.headroom.remove(viewTabs),tabControllers.forEach(function(t){t.destroy&&t.destroy()})})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/tvshows.js b/dashboard-ui/scripts/tvshows.js index 80a16dd9b7..c16fc6eb3b 100644 --- a/dashboard-ui/scripts/tvshows.js +++ b/dashboard-ui/scripts/tvshows.js @@ -1,304 +1 @@ -define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'cardBuilder', 'apphost', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView, cardBuilder, appHost) { - 'use strict'; - - return function (view, params, tabContent) { - - var self = this; - var pageSize = libraryBrowser.getDefaultPageSize(); - - var data = {}; - - function getPageData(context) { - var key = getSavedQueryKey(context); - var pageData = data[key]; - - if (!pageData) { - pageData = data[key] = { - query: { - SortBy: "SortName", - SortOrder: "Ascending", - IncludeItemTypes: "Series", - Recursive: true, - Fields: "PrimaryImageAspectRatio,BasicSyncInfo", - ImageTypeLimit: 1, - EnableImageTypes: "Primary,Backdrop,Banner,Thumb", - StartIndex: 0, - Limit: pageSize - }, - view: libraryBrowser.getSavedView(key) || 'Poster' - }; - - pageData.query.ParentId = params.topParentId; - libraryBrowser.loadSavedQueryValues(key, pageData.query); - } - return pageData; - } - - function getQuery(context) { - - return getPageData(context).query; - } - - function getSavedQueryKey(context) { - - if (!context.savedQueryKey) { - context.savedQueryKey = libraryBrowser.getSavedQueryKey('series'); - } - return context.savedQueryKey; - } - - function onViewStyleChange() { - - var viewStyle = self.getCurrentViewStyle(); - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - - if (viewStyle == "List") { - - itemsContainer.classList.add('vertical-list'); - itemsContainer.classList.remove('vertical-wrap'); - } - else { - - itemsContainer.classList.remove('vertical-list'); - itemsContainer.classList.add('vertical-wrap'); - } - itemsContainer.innerHTML = ''; - } - - function reloadItems(page) { - - Dashboard.showLoadingMsg(); - - var query = getQuery(page); - - ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) { - - // Scroll back up so they can see the results from the beginning - window.scrollTo(0, 0); - - updateFilterControls(page); - - var pagingHtml = LibraryBrowser.getQueryPagingHtml({ - startIndex: query.StartIndex, - limit: query.Limit, - totalRecordCount: result.TotalRecordCount, - showLimit: false, - updatePageSizeSetting: false, - addLayoutButton: false, - sortButton: false, - filterButton: false - }); - - var html; - var viewStyle = self.getCurrentViewStyle(); - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - if (viewStyle == "Thumb") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'tvshows', - lazy: true, - overlayMoreButton: true - }); - } - else if (viewStyle == "ThumbCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "backdrop", - preferThumb: true, - context: 'tvshows', - lazy: true, - cardLayout: true, - showTitle: true, - showSeriesYear: true, - vibrant: supportsImageAnalysis - }); - } - else if (viewStyle == "Banner") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "banner", - preferBanner: true, - context: 'tvshows', - lazy: true - }); - } - else if (viewStyle == "List") { - - html = listView.getListViewHtml({ - items: result.Items, - context: 'tvshows', - sortBy: query.SortBy - }); - } - else if (viewStyle == "PosterCard") { - - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "portrait", - context: 'tvshows', - showTitle: true, - showSeriesYear: true, - lazy: true, - cardLayout: true, - vibrant: supportsImageAnalysis - }); - } - else { - - // Poster - html = cardBuilder.getCardsHtml({ - items: result.Items, - shape: "portrait", - context: 'tvshows', - centerText: true, - lazy: true, - overlayMoreButton: true - }); - } - - var i, length; - var elems = tabContent.querySelectorAll('.paging'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].innerHTML = pagingHtml; - } - - function onNextPageClick() { - query.StartIndex += query.Limit; - reloadItems(tabContent); - } - - function onPreviousPageClick() { - query.StartIndex -= query.Limit; - reloadItems(tabContent); - } - - elems = tabContent.querySelectorAll('.btnNextPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onNextPageClick); - } - - elems = tabContent.querySelectorAll('.btnPreviousPage'); - for (i = 0, length = elems.length; i < length; i++) { - elems[i].addEventListener('click', onPreviousPageClick); - } - - var itemsContainer = tabContent.querySelector('.itemsContainer'); - itemsContainer.innerHTML = html; - imageLoader.lazyChildren(itemsContainer); - - libraryBrowser.saveQueryValues(getSavedQueryKey(page), query); - - Dashboard.hideLoadingMsg(); - }); - } - - self.showFilterMenu = function () { - - require(['components/filterdialog/filterdialog'], function (filterDialogFactory) { - - var filterDialog = new filterDialogFactory({ - query: getQuery(tabContent), - mode: 'series' - }); - - Events.on(filterDialog, 'filterchange', function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }); - - filterDialog.show(); - }); - } - - function updateFilterControls(tabContent) { - - } - - function initPage(tabContent) { - - tabContent.querySelector('.btnFilter').addEventListener('click', function () { - self.showFilterMenu(); - }); - - tabContent.querySelector('.btnSort').addEventListener('click', function (e) { - libraryBrowser.showSortMenu({ - items: [{ - name: Globalize.translate('OptionNameSort'), - id: 'SortName' - }, - { - name: Globalize.translate('OptionImdbRating'), - id: 'CommunityRating,SortName' - }, - { - name: Globalize.translate('OptionDateAdded'), - id: 'DateCreated,SortName' - }, - { - name: Globalize.translate('OptionDatePlayed'), - id: 'DatePlayed,SortName' - }, - { - name: Globalize.translate('OptionMetascore'), - id: 'Metascore,SortName' - }, - { - name: Globalize.translate('OptionParentalRating'), - id: 'OfficialRating,SortName' - }, - { - name: Globalize.translate('OptionReleaseDate'), - id: 'PremiereDate,SortName' - }], - callback: function () { - getQuery(tabContent).StartIndex = 0; - reloadItems(tabContent); - }, - query: getQuery(tabContent), - button: e.target - }); - }); - - var btnSelectView = tabContent.querySelector('.btnSelectView'); - btnSelectView.addEventListener('click', function (e) { - - libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), 'Banner,List,Poster,PosterCard,Thumb,ThumbCard'.split(',')); - }); - - btnSelectView.addEventListener('layoutchange', function (e) { - - var viewStyle = e.detail.viewStyle; - - getPageData(tabContent).view = viewStyle; - libraryBrowser.saveViewSetting(getSavedQueryKey(tabContent), viewStyle); - getQuery(tabContent).StartIndex = 0; - onViewStyleChange(); - reloadItems(tabContent); - }); - } - - self.getCurrentViewStyle = function () { - return getPageData(tabContent).view; - }; - - initPage(tabContent); - onViewStyleChange(); - - self.renderTab = function () { - - reloadItems(tabContent); - updateFilterControls(tabContent); - }; - - self.destroy = function () { - }; - }; -}); \ No newline at end of file +define(["events","libraryBrowser","imageLoader","listView","cardBuilder","apphost","emby-itemscontainer"],function(events,libraryBrowser,imageLoader,listView,cardBuilder,appHost){"use strict";return function(view,params,tabContent){function getPageData(context){var key=getSavedQueryKey(context),pageData=data[key];return pageData||(pageData=data[key]={query:{SortBy:"SortName",SortOrder:"Ascending",IncludeItemTypes:"Series",Recursive:!0,Fields:"PrimaryImageAspectRatio,BasicSyncInfo",ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",StartIndex:0,Limit:pageSize},view:libraryBrowser.getSavedView(key)||"Poster"},pageData.query.ParentId=params.topParentId,libraryBrowser.loadSavedQueryValues(key,pageData.query)),pageData}function getQuery(context){return getPageData(context).query}function getSavedQueryKey(context){return context.savedQueryKey||(context.savedQueryKey=libraryBrowser.getSavedQueryKey("series")),context.savedQueryKey}function onViewStyleChange(){var viewStyle=self.getCurrentViewStyle(),itemsContainer=tabContent.querySelector(".itemsContainer");"List"==viewStyle?(itemsContainer.classList.add("vertical-list"),itemsContainer.classList.remove("vertical-wrap")):(itemsContainer.classList.remove("vertical-list"),itemsContainer.classList.add("vertical-wrap")),itemsContainer.innerHTML=""}function reloadItems(page){Dashboard.showLoadingMsg();var query=getQuery(page);ApiClient.getItems(Dashboard.getCurrentUserId(),query).then(function(result){function onNextPageClick(){query.StartIndex+=query.Limit,reloadItems(tabContent)}function onPreviousPageClick(){query.StartIndex-=query.Limit,reloadItems(tabContent)}window.scrollTo(0,0),updateFilterControls(page);var html,pagingHtml=LibraryBrowser.getQueryPagingHtml({startIndex:query.StartIndex,limit:query.Limit,totalRecordCount:result.TotalRecordCount,showLimit:!1,updatePageSizeSetting:!1,addLayoutButton:!1,sortButton:!1,filterButton:!1}),viewStyle=self.getCurrentViewStyle(),supportsImageAnalysis=appHost.supports("imageanalysis");html="Thumb"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"tvshows",lazy:!0,overlayMoreButton:!0}):"ThumbCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"backdrop",preferThumb:!0,context:"tvshows",lazy:!0,cardLayout:!0,showTitle:!0,showSeriesYear:!0,vibrant:supportsImageAnalysis}):"Banner"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"banner",preferBanner:!0,context:"tvshows",lazy:!0}):"List"==viewStyle?listView.getListViewHtml({items:result.Items,context:"tvshows",sortBy:query.SortBy}):"PosterCard"==viewStyle?cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"tvshows",showTitle:!0,showSeriesYear:!0,lazy:!0,cardLayout:!0,vibrant:supportsImageAnalysis}):cardBuilder.getCardsHtml({items:result.Items,shape:"portrait",context:"tvshows",centerText:!0,lazy:!0,overlayMoreButton:!0});var i,length,elems=tabContent.querySelectorAll(".paging");for(i=0,length=elems.length;i'; - - var allowBottomPadding = true; - - if (enableScrollX()) { - allowBottomPadding = false; - html += '
'; - } else { - html += '
'; - } - - var supportsImageAnalysis = appHost.supports('imageanalysis'); - - html += cardBuilder.getCardsHtml({ - items: group.items, - showLocationTypeIndicator: false, - shape: getThumbShape(), - showTitle: true, - preferThumb: true, - lazy: true, - showDetailsMenu: true, - centerText: !supportsImageAnalysis, - showParentTitle: true, - overlayText: false, - allowBottomPadding: allowBottomPadding, - cardLayout: supportsImageAnalysis, - vibrant: supportsImageAnalysis - - }); - html += '
'; - - html += '
'; - } - - elem.innerHTML = html; - imageLoader.lazyChildren(elem); - } - return function (view, params, tabContent) { - - var self = this; - var upcomingPromise; - - self.preRender = function () { - upcomingPromise = getUpcomingPromise(view, params); - }; - - self.renderTab = function () { - - loadUpcoming(tabContent, params, upcomingPromise); - }; - }; -}); \ No newline at end of file +define(["datetime","libraryBrowser","cardBuilder","apphost","imageLoader","scrollStyles","emby-itemscontainer"],function(datetime,libraryBrowser,cardBuilder,appHost,imageLoader){"use strict";function getUpcomingPromise(context,params){Dashboard.showLoadingMsg();var query={Limit:40,Fields:"AirTime,UserData",UserId:Dashboard.getCurrentUserId(),ImageTypeLimit:1,EnableImageTypes:"Primary,Backdrop,Banner,Thumb",EnableTotalRecordCount:!1};return query.ParentId=params.topParentId,ApiClient.getJSON(ApiClient.getUrl("Shows/Upcoming",query))}function loadUpcoming(context,params,promise){promise.then(function(result){var items=result.Items;items.length?context.querySelector(".noItemsMessage").style.display="none":context.querySelector(".noItemsMessage").style.display="block";var elem=context.querySelector("#upcomingItems");renderUpcoming(elem,items),Dashboard.hideLoadingMsg()})}function enableScrollX(){return browserInfo.mobile}function getThumbShape(){return enableScrollX()?"overflowBackdrop":"backdrop"}function renderUpcoming(elem,items){var i,length,groups=[],currentGroupName="",currentGroup=[];for(i=0,length=items.length;i',html+='

'+group.name+"

";var allowBottomPadding=!0;enableScrollX()?(allowBottomPadding=!1,html+='
'):html+='
';var supportsImageAnalysis=appHost.supports("imageanalysis");html+=cardBuilder.getCardsHtml({items:group.items,showLocationTypeIndicator:!1,shape:getThumbShape(),showTitle:!0,preferThumb:!0,lazy:!0,showDetailsMenu:!0,centerText:!supportsImageAnalysis,showParentTitle:!0,overlayText:!1,allowBottomPadding:allowBottomPadding,cardLayout:supportsImageAnalysis,vibrant:supportsImageAnalysis}),html+="
",html+="
"}elem.innerHTML=html,imageLoader.lazyChildren(elem)}return function(view,params,tabContent){var upcomingPromise,self=this;self.preRender=function(){upcomingPromise=getUpcomingPromise(view,params)},self.renderTab=function(){loadUpcoming(tabContent,params,upcomingPromise)}}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/useredit.js b/dashboard-ui/scripts/useredit.js index 08162da1f1..e53d4dfd1c 100644 --- a/dashboard-ui/scripts/useredit.js +++ b/dashboard-ui/scripts/useredit.js @@ -1,159 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - var currentUser; - - function loadUser(page, user) { - - currentUser = user; - - if (user.Policy.IsDisabled) { - $('.disabledUserBanner', page).show(); - } else { - $('.disabledUserBanner', page).hide(); - } - - if (user.ConnectLinkType == 'Guest') { - $('#fldConnectInfo', page).hide(); - $('#txtUserName', page).prop("disabled", "disabled"); - } else { - $('#txtUserName', page).prop("disabled", "").removeAttr('disabled'); - $('#fldConnectInfo', page).show(); - } - - $('.lnkEditUserPreferences', page).attr('href', 'mypreferencesmenu.html?userId=' + user.Id); - - LibraryMenu.setTitle(user.Name); - - $('#txtUserName', page).val(user.Name); - $('#txtConnectUserName', page).val(currentUser.ConnectUserName); - - $('#chkIsAdmin', page).checked(user.Policy.IsAdministrator); - - $('#chkDisabled', page).checked(user.Policy.IsDisabled); - $('#chkIsHidden', page).checked(user.Policy.IsHidden); - $('#chkRemoteControlSharedDevices', page).checked(user.Policy.EnableSharedDeviceControl); - $('#chkEnableRemoteControlOtherUsers', page).checked(user.Policy.EnableRemoteControlOfOtherUsers); - - $('#chkEnableDownloading', page).checked(user.Policy.EnableContentDownloading); - - $('#chkManageLiveTv', page).checked(user.Policy.EnableLiveTvManagement); - $('#chkEnableLiveTvAccess', page).checked(user.Policy.EnableLiveTvAccess); - $('#chkEnableContentDeletion', page).checked(user.Policy.EnableContentDeletion); - - $('#chkDisableUserPreferences', page).checked((!user.Policy.EnableUserPreferenceAccess)); - - $('#chkEnableMediaPlayback', page).checked(user.Policy.EnableMediaPlayback); - $('#chkEnableAudioPlaybackTranscoding', page).checked(user.Policy.EnableAudioPlaybackTranscoding); - $('#chkEnableVideoPlaybackTranscoding', page).checked(user.Policy.EnableVideoPlaybackTranscoding); - $('#chkEnableVideoPlaybackRemuxing', page).checked(user.Policy.EnablePlaybackRemuxing); - - $('#chkEnableSync', page).checked(user.Policy.EnableSync); - $('#chkEnableSyncTranscoding', page).checked(user.Policy.EnableSyncTranscoding); - $('#chkEnableSharing', page).checked(user.Policy.EnablePublicSharing); - - Dashboard.hideLoadingMsg(); - } - - function onSaveComplete(page, user) { - - Dashboard.hideLoadingMsg(); - - var currentConnectUsername = currentUser.ConnectUserName || ''; - var enteredConnectUsername = $('#txtConnectUserName', page).val(); - - if (currentConnectUsername == enteredConnectUsername) { - require(['toast'], function (toast) { - toast(Globalize.translate('SettingsSaved')); - }); - } else { - - require(['connectHelper'], function (connectHelper) { - connectHelper.updateUserLink(ApiClient, user, $('#txtConnectUserName', page).val()).then(function () { - - loadData(page); - }); - }); - } - } - - function saveUser(user, page) { - - user.Name = $('#txtUserName', page).val(); - - user.Policy.IsAdministrator = $('#chkIsAdmin', page).checked(); - - user.Policy.IsHidden = $('#chkIsHidden', page).checked(); - user.Policy.IsDisabled = $('#chkDisabled', page).checked(); - user.Policy.EnableRemoteControlOfOtherUsers = $('#chkEnableRemoteControlOtherUsers', page).checked(); - user.Policy.EnableLiveTvManagement = $('#chkManageLiveTv', page).checked(); - user.Policy.EnableLiveTvAccess = $('#chkEnableLiveTvAccess', page).checked(); - user.Policy.EnableContentDeletion = $('#chkEnableContentDeletion', page).checked(); - user.Policy.EnableUserPreferenceAccess = !$('#chkDisableUserPreferences', page).checked(); - user.Policy.EnableSharedDeviceControl = $('#chkRemoteControlSharedDevices', page).checked(); - - user.Policy.EnableMediaPlayback = $('#chkEnableMediaPlayback', page).checked(); - user.Policy.EnableAudioPlaybackTranscoding = $('#chkEnableAudioPlaybackTranscoding', page).checked(); - user.Policy.EnableVideoPlaybackTranscoding = $('#chkEnableVideoPlaybackTranscoding', page).checked(); - user.Policy.EnablePlaybackRemuxing = $('#chkEnableVideoPlaybackRemuxing', page).checked(); - - user.Policy.EnableContentDownloading = $('#chkEnableDownloading', page).checked(); - - user.Policy.EnableSync = $('#chkEnableSync', page).checked(); - user.Policy.EnableSyncTranscoding = $('#chkEnableSyncTranscoding', page).checked(); - user.Policy.EnablePublicSharing = $('#chkEnableSharing', page).checked(); - - ApiClient.updateUser(user).then(function () { - - ApiClient.updateUserPolicy(user.Id, user.Policy).then(function () { - - onSaveComplete(page, user); - }); - }); - } - - function onSubmit() { - var page = $(this).parents('.page'); - - Dashboard.showLoadingMsg(); - - getUser().then(function (result) { - saveUser(result, page); - }); - - // Disable default form submission - return false; - } - - function getUser() { - - var userId = getParameterByName("userId"); - - return ApiClient.getUser(userId); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - getUser().then(function (user) { - - loadUser(page, user); - }); - } - - $(document).on('pageinit', "#editUserPage", function () { - - $('.editUserProfileForm').off('submit', onSubmit).on('submit', onSubmit); - - this.querySelector('.sharingHelp').innerHTML = Globalize.translate('OptionAllowLinkSharingHelp', 30); - - }).on('pagebeforeshow', "#editUserPage", function () { - - var page = this; - - loadData(page); - - }); - -}); \ No newline at end of file +define(["jQuery","fnchecked"],function($){"use strict";function loadUser(page,user){currentUser=user,user.Policy.IsDisabled?$(".disabledUserBanner",page).show():$(".disabledUserBanner",page).hide(),"Guest"==user.ConnectLinkType?($("#fldConnectInfo",page).hide(),$("#txtUserName",page).prop("disabled","disabled")):($("#txtUserName",page).prop("disabled","").removeAttr("disabled"),$("#fldConnectInfo",page).show()),$(".lnkEditUserPreferences",page).attr("href","mypreferencesmenu.html?userId="+user.Id),LibraryMenu.setTitle(user.Name),$("#txtUserName",page).val(user.Name),$("#txtConnectUserName",page).val(currentUser.ConnectUserName),$("#chkIsAdmin",page).checked(user.Policy.IsAdministrator),$("#chkDisabled",page).checked(user.Policy.IsDisabled),$("#chkIsHidden",page).checked(user.Policy.IsHidden),$("#chkRemoteControlSharedDevices",page).checked(user.Policy.EnableSharedDeviceControl),$("#chkEnableRemoteControlOtherUsers",page).checked(user.Policy.EnableRemoteControlOfOtherUsers),$("#chkEnableDownloading",page).checked(user.Policy.EnableContentDownloading),$("#chkManageLiveTv",page).checked(user.Policy.EnableLiveTvManagement),$("#chkEnableLiveTvAccess",page).checked(user.Policy.EnableLiveTvAccess),$("#chkEnableContentDeletion",page).checked(user.Policy.EnableContentDeletion),$("#chkDisableUserPreferences",page).checked(!user.Policy.EnableUserPreferenceAccess),$("#chkEnableMediaPlayback",page).checked(user.Policy.EnableMediaPlayback),$("#chkEnableAudioPlaybackTranscoding",page).checked(user.Policy.EnableAudioPlaybackTranscoding),$("#chkEnableVideoPlaybackTranscoding",page).checked(user.Policy.EnableVideoPlaybackTranscoding),$("#chkEnableVideoPlaybackRemuxing",page).checked(user.Policy.EnablePlaybackRemuxing),$("#chkEnableSync",page).checked(user.Policy.EnableSync),$("#chkEnableSyncTranscoding",page).checked(user.Policy.EnableSyncTranscoding),$("#chkEnableSharing",page).checked(user.Policy.EnablePublicSharing),Dashboard.hideLoadingMsg()}function onSaveComplete(page,user){Dashboard.hideLoadingMsg();var currentConnectUsername=currentUser.ConnectUserName||"",enteredConnectUsername=$("#txtConnectUserName",page).val();currentConnectUsername==enteredConnectUsername?require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))}):require(["connectHelper"],function(connectHelper){connectHelper.updateUserLink(ApiClient,user,$("#txtConnectUserName",page).val()).then(function(){loadData(page)})})}function saveUser(user,page){user.Name=$("#txtUserName",page).val(),user.Policy.IsAdministrator=$("#chkIsAdmin",page).checked(),user.Policy.IsHidden=$("#chkIsHidden",page).checked(),user.Policy.IsDisabled=$("#chkDisabled",page).checked(),user.Policy.EnableRemoteControlOfOtherUsers=$("#chkEnableRemoteControlOtherUsers",page).checked(),user.Policy.EnableLiveTvManagement=$("#chkManageLiveTv",page).checked(),user.Policy.EnableLiveTvAccess=$("#chkEnableLiveTvAccess",page).checked(),user.Policy.EnableContentDeletion=$("#chkEnableContentDeletion",page).checked(),user.Policy.EnableUserPreferenceAccess=!$("#chkDisableUserPreferences",page).checked(),user.Policy.EnableSharedDeviceControl=$("#chkRemoteControlSharedDevices",page).checked(),user.Policy.EnableMediaPlayback=$("#chkEnableMediaPlayback",page).checked(),user.Policy.EnableAudioPlaybackTranscoding=$("#chkEnableAudioPlaybackTranscoding",page).checked(),user.Policy.EnableVideoPlaybackTranscoding=$("#chkEnableVideoPlaybackTranscoding",page).checked(),user.Policy.EnablePlaybackRemuxing=$("#chkEnableVideoPlaybackRemuxing",page).checked(),user.Policy.EnableContentDownloading=$("#chkEnableDownloading",page).checked(),user.Policy.EnableSync=$("#chkEnableSync",page).checked(),user.Policy.EnableSyncTranscoding=$("#chkEnableSyncTranscoding",page).checked(),user.Policy.EnablePublicSharing=$("#chkEnableSharing",page).checked(),ApiClient.updateUser(user).then(function(){ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){onSaveComplete(page,user)})})}function onSubmit(){var page=$(this).parents(".page");return Dashboard.showLoadingMsg(),getUser().then(function(result){saveUser(result,page)}),!1}function getUser(){var userId=getParameterByName("userId");return ApiClient.getUser(userId)}function loadData(page){Dashboard.showLoadingMsg(),getUser().then(function(user){loadUser(page,user)})}var currentUser;$(document).on("pageinit","#editUserPage",function(){$(".editUserProfileForm").off("submit",onSubmit).on("submit",onSubmit),this.querySelector(".sharingHelp").innerHTML=Globalize.translate("OptionAllowLinkSharingHelp",30)}).on("pagebeforeshow","#editUserPage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userlibraryaccess.js b/dashboard-ui/scripts/userlibraryaccess.js index 6bf4bc8789..9415eacb93 100644 --- a/dashboard-ui/scripts/userlibraryaccess.js +++ b/dashboard-ui/scripts/userlibraryaccess.js @@ -1,239 +1 @@ -define(['jQuery', 'fnchecked'], function ($) { - 'use strict'; - - function loadMediaFolders(page, user, mediaFolders) { - - var html = ''; - - html += '

' + Globalize.translate('HeaderLibraries') + '

'; - - html += '
'; - - for (var i = 0, length = mediaFolders.length; i < length; i++) { - - var folder = mediaFolders[i]; - - var isChecked = user.Policy.EnableAllFolders || user.Policy.EnabledFolders.indexOf(folder.Id) != -1; - var checkedAttribute = isChecked ? ' checked="checked"' : ''; - - html += ''; - } - - html += '
'; - - $('.folderAccess', page).html(html).trigger('create'); - - $('#chkEnableAllFolders', page).checked(user.Policy.EnableAllFolders).trigger('change'); - } - - function loadChannels(page, user, channels) { - - var html = ''; - - html += '

' + Globalize.translate('HeaderChannels') + '

'; - - html += '
'; - - for (var i = 0, length = channels.length; i < length; i++) { - - var folder = channels[i]; - - var isChecked = user.Policy.EnableAllChannels || user.Policy.EnabledChannels.indexOf(folder.Id) != -1; - var checkedAttribute = isChecked ? ' checked="checked"' : ''; - - html += ''; - } - - html += '
'; - - $('.channelAccess', page).show().html(html).trigger('create'); - - if (channels.length) { - $('.channelAccessContainer', page).show(); - } else { - $('.channelAccessContainer', page).hide(); - } - - $('#chkEnableAllChannels', page).checked(user.Policy.EnableAllChannels).trigger('change'); - } - - function loadDevices(page, user, devices) { - - var html = ''; - - html += '

' + Globalize.translate('HeaderDevices') + '

'; - - html += '
'; - - for (var i = 0, length = devices.length; i < length; i++) { - - var device = devices[i]; - - var checkedAttribute = user.Policy.EnableAllDevices || user.Policy.EnabledDevices.indexOf(device.Id) != -1 ? ' checked="checked"' : ''; - - html += ''; - } - - html += '
'; - - $('.deviceAccess', page).show().html(html).trigger('create'); - - $('#chkEnableAllDevices', page).checked(user.Policy.EnableAllDevices).trigger('change'); - - if (user.Policy.IsAdministrator) { - page.querySelector('.deviceAccessContainer').classList.add('hide'); - } else { - page.querySelector('.deviceAccessContainer').classList.remove('hide'); - } - } - - function loadUser(page, user, loggedInUser, mediaFolders, channels, devices) { - - $(page).trigger('userloaded', [user]); - - LibraryMenu.setTitle(user.Name); - - loadChannels(page, user, channels); - loadMediaFolders(page, user, mediaFolders); - loadDevices(page, user, devices); - - Dashboard.hideLoadingMsg(); - } - - function onSaveComplete(page) { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('SettingsSaved')); - }); - } - - function saveUser(user, page) { - - user.Policy.EnableAllFolders = $('#chkEnableAllFolders', page).checked(); - user.Policy.EnabledFolders = user.Policy.EnableAllFolders ? - [] : - $('.chkFolder', page).get().filter(function (c) { - return c.checked; - }).map(function (c) { - return c.getAttribute('data-id'); - }); - - user.Policy.EnableAllChannels = $('#chkEnableAllChannels', page).checked(); - user.Policy.EnabledChannels = user.Policy.EnableAllChannels ? - [] : - $('.chkChannel', page).get().filter(function (c) { - return c.checked; - }).map(function (c) { - return c.getAttribute('data-id'); - }); - - user.Policy.EnableAllDevices = $('#chkEnableAllDevices', page).checked(); - user.Policy.EnabledDevices = user.Policy.EnableAllDevices ? - [] : - $('.chkDevice', page).get().filter(function (c) { - return c.checked; - }).map(function (c) { - return c.getAttribute('data-id'); - }); - - // Legacy - user.Policy.BlockedChannels = null; - user.Policy.BlockedMediaFolders = null; - - ApiClient.updateUserPolicy(user.Id, user.Policy).then(function () { - onSaveComplete(page); - }); - } - - function onSubmit() { - var page = $(this).parents('.page'); - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - ApiClient.getUser(userId).then(function (result) { - saveUser(result, page); - }); - - // Disable default form submission - return false; - } - - $(document).on('pageinit', "#userLibraryAccessPage", function () { - - var page = this; - - $('#chkEnableAllDevices', page).on('change', function () { - - if (this.checked) { - $('.deviceAccessListContainer', page).hide(); - } else { - $('.deviceAccessListContainer', page).show(); - } - - }); - - $('#chkEnableAllChannels', page).on('change', function () { - - if (this.checked) { - $('.channelAccessListContainer', page).hide(); - } else { - $('.channelAccessListContainer', page).show(); - } - - }); - - $('#chkEnableAllFolders', page).on('change', function () { - - if (this.checked) { - $('.folderAccessListContainer', page).hide(); - } else { - $('.folderAccessListContainer', page).show(); - } - - }); - - $('.userLibraryAccessForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#userLibraryAccessPage", function () { - - var page = this; - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - var promise1; - - if (!userId) { - - var deferred = $.Deferred(); - - deferred.resolveWith(null, [{ - Configuration: {} - }]); - - promise1 = deferred.promise(); - } else { - - promise1 = ApiClient.getUser(userId); - } - - var promise2 = Dashboard.getCurrentUser(); - var promise4 = ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders", { IsHidden: false })); - var promise5 = ApiClient.getJSON(ApiClient.getUrl("Channels")); - var promise6 = ApiClient.getJSON(ApiClient.getUrl('Devices', { - SupportsPersistentIdentifier: true - })); - - Promise.all([promise1, promise2, promise4, promise5, promise6]).then(function (responses) { - - loadUser(page, responses[0], responses[1], responses[2].Items, responses[3].Items, responses[4].Items); - - }); - }); - -}); \ No newline at end of file +define(["jQuery","fnchecked"],function($){"use strict";function loadMediaFolders(page,user,mediaFolders){var html="";html+='

'+Globalize.translate("HeaderLibraries")+"

",html+='
';for(var i=0,length=mediaFolders.length;i"+folder.Name+""}html+="
",$(".folderAccess",page).html(html).trigger("create"),$("#chkEnableAllFolders",page).checked(user.Policy.EnableAllFolders).trigger("change")}function loadChannels(page,user,channels){var html="";html+='

'+Globalize.translate("HeaderChannels")+"

",html+='
';for(var i=0,length=channels.length;i"+folder.Name+""}html+="
",$(".channelAccess",page).show().html(html).trigger("create"),channels.length?$(".channelAccessContainer",page).show():$(".channelAccessContainer",page).hide(),$("#chkEnableAllChannels",page).checked(user.Policy.EnableAllChannels).trigger("change")}function loadDevices(page,user,devices){var html="";html+='

'+Globalize.translate("HeaderDevices")+"

",html+='
';for(var i=0,length=devices.length;i"+device.Name+" - "+device.AppName+""}html+="
",$(".deviceAccess",page).show().html(html).trigger("create"),$("#chkEnableAllDevices",page).checked(user.Policy.EnableAllDevices).trigger("change"),user.Policy.IsAdministrator?page.querySelector(".deviceAccessContainer").classList.add("hide"):page.querySelector(".deviceAccessContainer").classList.remove("hide")}function loadUser(page,user,loggedInUser,mediaFolders,channels,devices){$(page).trigger("userloaded",[user]),LibraryMenu.setTitle(user.Name),loadChannels(page,user,channels),loadMediaFolders(page,user,mediaFolders),loadDevices(page,user,devices),Dashboard.hideLoadingMsg()}function onSaveComplete(page){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))})}function saveUser(user,page){user.Policy.EnableAllFolders=$("#chkEnableAllFolders",page).checked(),user.Policy.EnabledFolders=user.Policy.EnableAllFolders?[]:$(".chkFolder",page).get().filter(function(c){return c.checked}).map(function(c){return c.getAttribute("data-id")}),user.Policy.EnableAllChannels=$("#chkEnableAllChannels",page).checked(),user.Policy.EnabledChannels=user.Policy.EnableAllChannels?[]:$(".chkChannel",page).get().filter(function(c){return c.checked}).map(function(c){return c.getAttribute("data-id")}),user.Policy.EnableAllDevices=$("#chkEnableAllDevices",page).checked(),user.Policy.EnabledDevices=user.Policy.EnableAllDevices?[]:$(".chkDevice",page).get().filter(function(c){return c.checked}).map(function(c){return c.getAttribute("data-id")}),user.Policy.BlockedChannels=null,user.Policy.BlockedMediaFolders=null,ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){onSaveComplete(page)})}function onSubmit(){var page=$(this).parents(".page");Dashboard.showLoadingMsg();var userId=getParameterByName("userId");return ApiClient.getUser(userId).then(function(result){saveUser(result,page)}),!1}$(document).on("pageinit","#userLibraryAccessPage",function(){var page=this;$("#chkEnableAllDevices",page).on("change",function(){this.checked?$(".deviceAccessListContainer",page).hide():$(".deviceAccessListContainer",page).show()}),$("#chkEnableAllChannels",page).on("change",function(){this.checked?$(".channelAccessListContainer",page).hide():$(".channelAccessListContainer",page).show()}),$("#chkEnableAllFolders",page).on("change",function(){this.checked?$(".folderAccessListContainer",page).hide():$(".folderAccessListContainer",page).show()}),$(".userLibraryAccessForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#userLibraryAccessPage",function(){var page=this;Dashboard.showLoadingMsg();var promise1,userId=getParameterByName("userId");if(userId)promise1=ApiClient.getUser(userId);else{var deferred=$.Deferred();deferred.resolveWith(null,[{Configuration:{}}]),promise1=deferred.promise()}var promise2=Dashboard.getCurrentUser(),promise4=ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders",{IsHidden:!1})),promise5=ApiClient.getJSON(ApiClient.getUrl("Channels")),promise6=ApiClient.getJSON(ApiClient.getUrl("Devices",{SupportsPersistentIdentifier:!0}));Promise.all([promise1,promise2,promise4,promise5,promise6]).then(function(responses){loadUser(page,responses[0],responses[1],responses[2].Items,responses[3].Items,responses[4].Items)})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/usernew.js b/dashboard-ui/scripts/usernew.js index d164ae911c..80c072ad6c 100644 --- a/dashboard-ui/scripts/usernew.js +++ b/dashboard-ui/scripts/usernew.js @@ -1,173 +1 @@ -define(['jQuery', 'fnchecked', 'emby-checkbox'], function ($) { - 'use strict'; - - function loadMediaFolders(page, mediaFolders) { - - var html = ''; - - html += '

' + Globalize.translate('HeaderLibraries') + '

'; - - html += '
'; - - for (var i = 0, length = mediaFolders.length; i < length; i++) { - - var folder = mediaFolders[i]; - - var checkedAttribute = ' checked="checked"'; - - html += ''; - } - - html += '
'; - - $('.folderAccess', page).html(html).trigger('create'); - - $('#chkEnableAllFolders', page).checked(true).trigger('change'); - } - - function loadChannels(page, channels) { - - var html = ''; - - html += '

' + Globalize.translate('HeaderChannels') + '

'; - - html += '
'; - - for (var i = 0, length = channels.length; i < length; i++) { - - var folder = channels[i]; - - var checkedAttribute = ' checked="checked"'; - - html += ''; - } - - html += '
'; - - $('.channelAccess', page).show().html(html).trigger('create'); - - if (channels.length) { - $('.channelAccessContainer', page).show(); - } else { - $('.channelAccessContainer', page).hide(); - } - - $('#chkEnableAllChannels', page).checked(true).trigger('change'); - } - - function loadUser(page) { - - $('#txtUserName', page).val(''); - - Dashboard.showLoadingMsg(); - - var promise4 = ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders", { IsHidden: false })); - - var promise5 = ApiClient.getJSON(ApiClient.getUrl("Channels")); - - Promise.all([promise4, promise5]).then(function (responses) { - - loadMediaFolders(page, responses[0].Items); - loadChannels(page, responses[1].Items); - - Dashboard.hideLoadingMsg(); - }); - } - - function saveUser(page) { - - var name = $('#txtUserName', page).val(); - - ApiClient.createUser(name).then(function (user) { - - user.Policy.EnableAllFolders = $('#chkEnableAllFolders', page).checked(); - user.Policy.EnabledFolders = user.Policy.EnableAllFolders ? - [] : - $('.chkFolder', page).get().filter(function (i) { - return i.checked; - }).map(function (i) { - return i.getAttribute('data-id'); - }); - - user.Policy.EnableAllChannels = $('#chkEnableAllChannels', page).checked(); - user.Policy.EnabledChannels = user.Policy.EnableAllChannels ? - [] : - $('.chkChannel', page).get().filter(function (i) { - return i.checked; - }).map(function (i) { - return i.getAttribute('data-id'); - }); - - ApiClient.updateUserPolicy(user.Id, user.Policy).then(function () { - Dashboard.navigate("useredit.html?userId=" + user.Id); - }); - - }, function (response) { - - if (response.status == 400) { - - Dashboard.alert({ - message: page.querySelector('.labelNewUserNameHelp').innerHTML - }); - - } else { - require(['toast'], function (toast) { - toast(Globalize.translate('DefaultErrorMessage')); - }); - } - - Dashboard.hideLoadingMsg(); - }); - } - - function onSubmit() { - var page = $(this).parents('.page')[0]; - - Dashboard.showLoadingMsg(); - - saveUser(page); - - // Disable default form submission - return false; - } - - function loadData(page) { - - loadUser(page); - } - - $(document).on('pageinit', "#newUserPage", function () { - - var page = this; - - $('#chkEnableAllChannels', page).on('change', function () { - - if (this.checked) { - $('.channelAccessListContainer', page).hide(); - } else { - $('.channelAccessListContainer', page).show(); - } - - }); - - $('#chkEnableAllFolders', page).on('change', function () { - - if (this.checked) { - $('.folderAccessListContainer', page).hide(); - } else { - $('.folderAccessListContainer', page).show(); - } - - }); - - $('.newUserProfileForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#newUserPage", function () { - - var page = this; - - loadData(page); - - }); - -}); \ No newline at end of file +define(["jQuery","fnchecked","emby-checkbox"],function($){"use strict";function loadMediaFolders(page,mediaFolders){var html="";html+='

'+Globalize.translate("HeaderLibraries")+"

",html+='
';for(var i=0,length=mediaFolders.length;i"+folder.Name+""}html+="
",$(".folderAccess",page).html(html).trigger("create"),$("#chkEnableAllFolders",page).checked(!0).trigger("change")}function loadChannels(page,channels){var html="";html+='

'+Globalize.translate("HeaderChannels")+"

",html+='
';for(var i=0,length=channels.length;i"+folder.Name+""}html+="
",$(".channelAccess",page).show().html(html).trigger("create"),channels.length?$(".channelAccessContainer",page).show():$(".channelAccessContainer",page).hide(),$("#chkEnableAllChannels",page).checked(!0).trigger("change")}function loadUser(page){$("#txtUserName",page).val(""),Dashboard.showLoadingMsg();var promise4=ApiClient.getJSON(ApiClient.getUrl("Library/MediaFolders",{IsHidden:!1})),promise5=ApiClient.getJSON(ApiClient.getUrl("Channels"));Promise.all([promise4,promise5]).then(function(responses){loadMediaFolders(page,responses[0].Items),loadChannels(page,responses[1].Items),Dashboard.hideLoadingMsg()})}function saveUser(page){var name=$("#txtUserName",page).val();ApiClient.createUser(name).then(function(user){user.Policy.EnableAllFolders=$("#chkEnableAllFolders",page).checked(),user.Policy.EnabledFolders=user.Policy.EnableAllFolders?[]:$(".chkFolder",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-id")}),user.Policy.EnableAllChannels=$("#chkEnableAllChannels",page).checked(),user.Policy.EnabledChannels=user.Policy.EnableAllChannels?[]:$(".chkChannel",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-id")}),ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){Dashboard.navigate("useredit.html?userId="+user.Id)})},function(response){400==response.status?Dashboard.alert({message:page.querySelector(".labelNewUserNameHelp").innerHTML}):require(["toast"],function(toast){toast(Globalize.translate("DefaultErrorMessage"))}),Dashboard.hideLoadingMsg()})}function onSubmit(){var page=$(this).parents(".page")[0];return Dashboard.showLoadingMsg(),saveUser(page),!1}function loadData(page){loadUser(page)}$(document).on("pageinit","#newUserPage",function(){var page=this;$("#chkEnableAllChannels",page).on("change",function(){this.checked?$(".channelAccessListContainer",page).hide():$(".channelAccessListContainer",page).show()}),$("#chkEnableAllFolders",page).on("change",function(){this.checked?$(".folderAccessListContainer",page).hide():$(".folderAccessListContainer",page).show()}),$(".newUserProfileForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#newUserPage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userparentalcontrol.js b/dashboard-ui/scripts/userparentalcontrol.js index 60f4514873..3099a0cff7 100644 --- a/dashboard-ui/scripts/userparentalcontrol.js +++ b/dashboard-ui/scripts/userparentalcontrol.js @@ -1,355 +1 @@ -define(['jQuery', 'datetime', 'listViewStyle', 'paper-icon-button-light'], function ($, datetime) { - 'use strict'; - - function populateRatings(allParentalRatings, page) { - - var html = ""; - - html += ""; - - var ratings = []; - var i, length, rating; - - for (i = 0, length = allParentalRatings.length; i < length; i++) { - - rating = allParentalRatings[i]; - - if (ratings.length) { - - var lastRating = ratings[ratings.length - 1]; - - if (lastRating.Value === rating.Value) { - - lastRating.Name += "/" + rating.Name; - continue; - } - - } - - ratings.push({ Name: rating.Name, Value: rating.Value }); - } - - for (i = 0, length = ratings.length; i < length; i++) { - - rating = ratings[i]; - - html += ""; - } - - $('#selectMaxParentalRating', page).html(html); - } - - function loadUnratedItems(page, user) { - - var items = [ - { name: Globalize.translate('OptionBlockBooks'), value: 'Book' }, - { name: Globalize.translate('OptionBlockGames'), value: 'Game' }, - { name: Globalize.translate('OptionBlockChannelContent'), value: 'ChannelContent' }, - { name: Globalize.translate('OptionBlockLiveTvChannels'), value: 'LiveTvChannel' }, - { name: Globalize.translate('OptionBlockMovies'), value: 'Movie' }, - { name: Globalize.translate('OptionBlockMusic'), value: 'Music' }, - { name: Globalize.translate('OptionBlockTrailers'), value: 'Trailer' }, - { name: Globalize.translate('OptionBlockTvShows'), value: 'Series' }, - { name: Globalize.translate('OptionBlockOthers'), value: 'Other' } - ]; - - var html = ''; - - html += '

' + Globalize.translate('HeaderBlockItemsWithNoRating') + '

'; - - html += '
'; - - for (var i = 0, length = items.length; i < length; i++) { - - var item = items[i]; - - var checkedAttribute = user.Policy.BlockUnratedItems.indexOf(item.value) != -1 ? ' checked="checked"' : ''; - - html += ''; - } - - html += '
'; - - $('.blockUnratedItems', page).html(html).trigger('create'); - } - - function loadUser(page, user, allParentalRatings) { - - LibraryMenu.setTitle(user.Name); - - loadUnratedItems(page, user); - loadBlockedTags(page, user.Policy.BlockedTags); - - populateRatings(allParentalRatings, page); - - var ratingValue = ""; - - if (user.Policy.MaxParentalRating) { - - for (var i = 0, length = allParentalRatings.length; i < length; i++) { - - var rating = allParentalRatings[i]; - - if (user.Policy.MaxParentalRating >= rating.Value) { - ratingValue = rating.Value; - } - } - } - - $('#selectMaxParentalRating', page).val(ratingValue); - - if (user.Policy.IsAdministrator) { - $('.accessScheduleSection', page).hide(); - } else { - $('.accessScheduleSection', page).show(); - } - - renderAccessSchedule(page, user.Policy.AccessSchedules || []); - - Dashboard.hideLoadingMsg(); - } - - function loadBlockedTags(page, tags) { - - var html = tags.map(function (h) { - - var li = '
'; - - li += '
'; - li += '

'; - li += h; - li += '

'; - li += '
'; - - li += ''; - - li += '
'; - - return li; - - }).join(''); - - if (html) { - html = '
' + html + '
'; - } - - var elem = $('.blockedTags', page).html(html).trigger('create'); - - $('.btnDeleteTag', elem).on('click', function () { - - var tag = this.getAttribute('data-tag'); - - var newTags = tags.filter(function (t) { - return t != tag; - }); - - loadBlockedTags(page, newTags); - }); - } - - function deleteAccessSchedule(page, schedules, index) { - - schedules.splice(index, 1); - - renderAccessSchedule(page, schedules); - } - - function renderAccessSchedule(page, schedules) { - - var html = ''; - var index = 0; - - html += schedules.map(function (a) { - - var itemHtml = ''; - - itemHtml += '
'; - - itemHtml += '
'; - itemHtml += '

'; - itemHtml += Globalize.translate('Option' + a.DayOfWeek); - itemHtml += '

'; - itemHtml += '
' + getDisplayTime(a.StartHour) + ' - ' + getDisplayTime(a.EndHour) + '
'; - itemHtml += '
'; - - itemHtml += ''; - - itemHtml += '
'; - - index++; - - return itemHtml; - - }).join(''); - - var accessScheduleList = page.querySelector('.accessScheduleList'); - accessScheduleList.innerHTML = html; - - $('.btnDelete', accessScheduleList).on('click', function () { - - deleteAccessSchedule(page, schedules, parseInt(this.getAttribute('data-index'))); - }); - } - - function onSaveComplete(page) { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('SettingsSaved')); - }); - } - - function saveUser(user, page) { - - user.Policy.MaxParentalRating = $('#selectMaxParentalRating', page).val() || null; - - user.Policy.BlockUnratedItems = $('.chkUnratedItem', page).get().filter(function (i) { - - return i.checked; - - }).map(function (i) { - - return i.getAttribute('data-itemtype'); - - }); - - user.Policy.AccessSchedules = getSchedulesFromPage(page); - - user.Policy.BlockedTags = getBlockedTagsFromPage(page); - - ApiClient.updateUserPolicy(user.Id, user.Policy).then(function () { - onSaveComplete(page); - }); - } - - window.UserParentalControlPage = { - - onSubmit: function () { - - var page = $(this).parents('.page'); - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - ApiClient.getUser(userId).then(function (result) { - saveUser(result, page); - }); - - // Disable default form submission - return false; - } - }; - - function getDisplayTime(hours) { - - var minutes = 0; - - var pct = hours % 1; - - if (pct) { - minutes = parseInt(pct * 60); - } - - return datetime.getDisplayTime(new Date(2000, 1, 1, hours, minutes, 0, 0)); - } - - function showSchedulePopup(page, schedule, index) { - - schedule = schedule || {}; - - require(['components/accessschedule/accessschedule'], function (accessschedule) { - accessschedule.show({ - schedule: schedule - }).then(function (updatedSchedule) { - - var schedules = getSchedulesFromPage(page); - - if (index == -1) { - index = schedules.length; - } - - schedules[index] = updatedSchedule; - - renderAccessSchedule(page, schedules); - }); - }); - } - - function getSchedulesFromPage(page) { - - return $('.liSchedule', page).map(function () { - - return { - DayOfWeek: this.getAttribute('data-day'), - StartHour: this.getAttribute('data-start'), - EndHour: this.getAttribute('data-end') - }; - - }).get(); - } - - function getBlockedTagsFromPage(page) { - - return $('.blockedTag', page).map(function () { - - return this.getAttribute('data-tag'); - - }).get(); - } - - function showBlockedTagPopup(page) { - - require(['prompt'], function (prompt) { - - prompt({ - label: Globalize.translate('LabelTag') - - }).then(function (value) { - var tags = getBlockedTagsFromPage(page); - - if (tags.indexOf(value) == -1) { - tags.push(value); - loadBlockedTags(page, tags); - } - }); - - }); - } - - $(document).on('pageinit', "#userParentalControlPage", function () { - - var page = this; - - - $('.btnAddSchedule', page).on('click', function () { - - showSchedulePopup(page, {}, -1); - }); - - $('.btnAddBlockedTag', page).on('click', function () { - - showBlockedTagPopup(page); - }); - - $('.userParentalControlForm').off('submit', UserParentalControlPage.onSubmit).on('submit', UserParentalControlPage.onSubmit); - - }).on('pageshow', "#userParentalControlPage", function () { - - var page = this; - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - var promise1 = ApiClient.getUser(userId); - var promise2 = ApiClient.getParentalRatings(); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadUser(page, responses[0], responses[1]); - - }); - }); - -}); \ No newline at end of file +define(["jQuery","datetime","listViewStyle","paper-icon-button-light"],function($,datetime){"use strict";function populateRatings(allParentalRatings,page){var html="";html+="";var i,length,rating,ratings=[];for(i=0,length=allParentalRatings.length;i"+rating.Name+"";$("#selectMaxParentalRating",page).html(html)}function loadUnratedItems(page,user){var items=[{name:Globalize.translate("OptionBlockBooks"),value:"Book"},{name:Globalize.translate("OptionBlockGames"),value:"Game"},{name:Globalize.translate("OptionBlockChannelContent"),value:"ChannelContent"},{name:Globalize.translate("OptionBlockLiveTvChannels"),value:"LiveTvChannel"},{name:Globalize.translate("OptionBlockMovies"),value:"Movie"},{name:Globalize.translate("OptionBlockMusic"),value:"Music"},{name:Globalize.translate("OptionBlockTrailers"),value:"Trailer"},{name:Globalize.translate("OptionBlockTvShows"),value:"Series"},{name:Globalize.translate("OptionBlockOthers"),value:"Other"}],html="";html+='

'+Globalize.translate("HeaderBlockItemsWithNoRating")+"

",html+='
';for(var i=0,length=items.length;i"+item.name+""}html+="
",$(".blockUnratedItems",page).html(html).trigger("create")}function loadUser(page,user,allParentalRatings){LibraryMenu.setTitle(user.Name),loadUnratedItems(page,user),loadBlockedTags(page,user.Policy.BlockedTags),populateRatings(allParentalRatings,page);var ratingValue="";if(user.Policy.MaxParentalRating)for(var i=0,length=allParentalRatings.length;i=rating.Value&&(ratingValue=rating.Value)}$("#selectMaxParentalRating",page).val(ratingValue),user.Policy.IsAdministrator?$(".accessScheduleSection",page).hide():$(".accessScheduleSection",page).show(),renderAccessSchedule(page,user.Policy.AccessSchedules||[]),Dashboard.hideLoadingMsg()}function loadBlockedTags(page,tags){var html=tags.map(function(h){var li='
';return li+='
',li+='

',li+=h,li+="

",li+="
",li+='',li+="
"}).join("");html&&(html='
'+html+"
");var elem=$(".blockedTags",page).html(html).trigger("create");$(".btnDeleteTag",elem).on("click",function(){var tag=this.getAttribute("data-tag"),newTags=tags.filter(function(t){return t!=tag});loadBlockedTags(page,newTags)})}function deleteAccessSchedule(page,schedules,index){schedules.splice(index,1),renderAccessSchedule(page,schedules)}function renderAccessSchedule(page,schedules){var html="",index=0;html+=schedules.map(function(a){var itemHtml="";return itemHtml+='
',itemHtml+='
',itemHtml+='

',itemHtml+=Globalize.translate("Option"+a.DayOfWeek),itemHtml+="

",itemHtml+='
'+getDisplayTime(a.StartHour)+" - "+getDisplayTime(a.EndHour)+"
",itemHtml+="
",itemHtml+='',itemHtml+="
",index++,itemHtml}).join("");var accessScheduleList=page.querySelector(".accessScheduleList");accessScheduleList.innerHTML=html,$(".btnDelete",accessScheduleList).on("click",function(){deleteAccessSchedule(page,schedules,parseInt(this.getAttribute("data-index")))})}function onSaveComplete(page){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("SettingsSaved"))})}function saveUser(user,page){user.Policy.MaxParentalRating=$("#selectMaxParentalRating",page).val()||null,user.Policy.BlockUnratedItems=$(".chkUnratedItem",page).get().filter(function(i){return i.checked}).map(function(i){return i.getAttribute("data-itemtype")}),user.Policy.AccessSchedules=getSchedulesFromPage(page),user.Policy.BlockedTags=getBlockedTagsFromPage(page),ApiClient.updateUserPolicy(user.Id,user.Policy).then(function(){onSaveComplete(page)})}function getDisplayTime(hours){var minutes=0,pct=hours%1;return pct&&(minutes=parseInt(60*pct)),datetime.getDisplayTime(new Date(2e3,1,1,hours,minutes,0,0))}function showSchedulePopup(page,schedule,index){schedule=schedule||{},require(["components/accessschedule/accessschedule"],function(accessschedule){accessschedule.show({schedule:schedule}).then(function(updatedSchedule){var schedules=getSchedulesFromPage(page);index==-1&&(index=schedules.length),schedules[index]=updatedSchedule,renderAccessSchedule(page,schedules)})})}function getSchedulesFromPage(page){return $(".liSchedule",page).map(function(){return{DayOfWeek:this.getAttribute("data-day"),StartHour:this.getAttribute("data-start"),EndHour:this.getAttribute("data-end")}}).get()}function getBlockedTagsFromPage(page){return $(".blockedTag",page).map(function(){return this.getAttribute("data-tag")}).get()}function showBlockedTagPopup(page){require(["prompt"],function(prompt){prompt({label:Globalize.translate("LabelTag")}).then(function(value){var tags=getBlockedTagsFromPage(page);tags.indexOf(value)==-1&&(tags.push(value),loadBlockedTags(page,tags))})})}window.UserParentalControlPage={onSubmit:function(){var page=$(this).parents(".page");Dashboard.showLoadingMsg();var userId=getParameterByName("userId");return ApiClient.getUser(userId).then(function(result){saveUser(result,page)}),!1}},$(document).on("pageinit","#userParentalControlPage",function(){var page=this;$(".btnAddSchedule",page).on("click",function(){showSchedulePopup(page,{},-1)}),$(".btnAddBlockedTag",page).on("click",function(){showBlockedTagPopup(page)}),$(".userParentalControlForm").off("submit",UserParentalControlPage.onSubmit).on("submit",UserParentalControlPage.onSubmit)}).on("pageshow","#userParentalControlPage",function(){var page=this;Dashboard.showLoadingMsg();var userId=getParameterByName("userId"),promise1=ApiClient.getUser(userId),promise2=ApiClient.getParentalRatings();Promise.all([promise1,promise2]).then(function(responses){loadUser(page,responses[0],responses[1])})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userpassword.js b/dashboard-ui/scripts/userpassword.js index e366129be3..70c2b590a8 100644 --- a/dashboard-ui/scripts/userpassword.js +++ b/dashboard-ui/scripts/userpassword.js @@ -1,45 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function loadUser(page, user) { - - LibraryMenu.setTitle(user.Name); - - if (user.ConnectLinkType == 'Guest') { - - $('.connectMessage', page).show(); - } - else { - $('.connectMessage', page).hide(); - } - - Dashboard.hideLoadingMsg(); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - var userId = getParameterByName("userId"); - - ApiClient.getUser(userId).then(function (user) { - - loadUser(page, user); - - }); - } - - $(document).on('pageinit', "#userPasswordPage", function () { - - $('.adminUpdatePasswordForm').off('submit', UpdatePasswordPage.onSubmit).on('submit', UpdatePasswordPage.onSubmit); - $('.adminLocalAccessForm').off('submit', UpdatePasswordPage.onLocalAccessSubmit).on('submit', UpdatePasswordPage.onLocalAccessSubmit); - - }).on('pagebeforeshow', "#userPasswordPage", function () { - - var page = this; - - loadData(page); - - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function loadUser(page,user){LibraryMenu.setTitle(user.Name),"Guest"==user.ConnectLinkType?$(".connectMessage",page).show():$(".connectMessage",page).hide(),Dashboard.hideLoadingMsg()}function loadData(page){Dashboard.showLoadingMsg();var userId=getParameterByName("userId");ApiClient.getUser(userId).then(function(user){loadUser(page,user)})}$(document).on("pageinit","#userPasswordPage",function(){$(".adminUpdatePasswordForm").off("submit",UpdatePasswordPage.onSubmit).on("submit",UpdatePasswordPage.onSubmit),$(".adminLocalAccessForm").off("submit",UpdatePasswordPage.onLocalAccessSubmit).on("submit",UpdatePasswordPage.onLocalAccessSubmit)}).on("pagebeforeshow","#userPasswordPage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userpasswordpage.js b/dashboard-ui/scripts/userpasswordpage.js index 0087cf0a32..8f75aaeefb 100644 --- a/dashboard-ui/scripts/userpasswordpage.js +++ b/dashboard-ui/scripts/userpasswordpage.js @@ -1,227 +1 @@ -define([], function () { - 'use strict'; - - function loadUser(page, params) { - - var userid = params.userId; - - ApiClient.getUser(userid).then(function (user) { - - Dashboard.getCurrentUser().then(function (loggedInUser) { - - LibraryMenu.setTitle(user.Name); - - var showPasswordSection = true; - var showLocalAccessSection = false; - if (user.ConnectLinkType == 'Guest') { - page.querySelector('.localAccessSection').classList.add('hide'); - showPasswordSection = false; - } - else if (user.HasConfiguredPassword) { - page.querySelector('#btnResetPassword').classList.remove('hide'); - page.querySelector('#fldCurrentPassword').classList.remove('hide'); - showLocalAccessSection = true; - } else { - page.querySelector('#btnResetPassword').classList.add('hide'); - page.querySelector('#fldCurrentPassword').classList.add('hide'); - } - - if (showPasswordSection && (loggedInUser.Policy.IsAdministrator || user.Policy.EnableUserPreferenceAccess)) { - page.querySelector('.passwordSection').classList.remove('hide'); - } else { - page.querySelector('.passwordSection').classList.add('hide'); - } - - if (showLocalAccessSection && (loggedInUser.Policy.IsAdministrator || user.Policy.EnableUserPreferenceAccess)) { - page.querySelector('.localAccessSection').classList.remove('hide'); - } else { - page.querySelector('.localAccessSection').classList.add('hide'); - } - - var txtEasyPassword = page.querySelector('#txtEasyPassword'); - txtEasyPassword.value = ''; - - if (user.HasConfiguredEasyPassword) { - txtEasyPassword.placeholder = '******'; - page.querySelector('#btnResetEasyPassword').classList.remove('hide'); - } else { - txtEasyPassword.removeAttribute('placeholder'); - txtEasyPassword.placeholder = ''; - page.querySelector('#btnResetEasyPassword').classList.add('hide'); - } - - page.querySelector('.chkEnableLocalEasyPassword').checked = user.Configuration.EnableLocalPassword; - }); - }); - - page.querySelector('#txtCurrentPassword').value = ''; - page.querySelector('#txtNewPassword').value = ''; - page.querySelector('#txtNewPasswordConfirm').value = ''; - } - - return function (view, params) { - - function saveEasyPassword() { - - var userId = params.userId; - - var easyPassword = view.querySelector('#txtEasyPassword').value; - - if (easyPassword) { - - ApiClient.updateEasyPassword(userId, easyPassword).then(function () { - - onEasyPasswordSaved(userId); - - }); - - } else { - onEasyPasswordSaved(userId); - } - } - - function onEasyPasswordSaved(userId) { - - ApiClient.getUser(userId).then(function (user) { - - user.Configuration.EnableLocalPassword = view.querySelector('.chkEnableLocalEasyPassword').checked; - - ApiClient.updateUserConfiguration(user.Id, user.Configuration).then(function () { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('MessageSettingsSaved')); - }); - loadUser(view, params); - }); - }); - } - - function savePassword() { - - var userId = params.userId; - - var currentPassword = view.querySelector('#txtCurrentPassword').value; - var newPassword = view.querySelector('#txtNewPassword').value; - - ApiClient.updateUserPassword(userId, currentPassword, newPassword).then(function () { - - Dashboard.hideLoadingMsg(); - - require(['toast'], function (toast) { - toast(Globalize.translate('PasswordSaved')); - }); - loadUser(view, params); - - }, function () { - - Dashboard.hideLoadingMsg(); - - Dashboard.alert({ - title: Globalize.translate('HeaderLoginFailure'), - message: Globalize.translate('MessageInvalidUser') - }); - - }); - - } - - function onSubmit(e) { - - var form = this; - - if (form.querySelector('#txtNewPassword').value != form.querySelector('#txtNewPasswordConfirm').value) { - - require(['toast'], function (toast) { - toast(Globalize.translate('PasswordMatchError')); - }); - } else { - - Dashboard.showLoadingMsg(); - savePassword(); - } - - // Disable default form submission - e.preventDefault(); - return false; - } - - function onLocalAccessSubmit(e) { - - Dashboard.showLoadingMsg(); - - saveEasyPassword(); - - // Disable default form submission - e.preventDefault(); - return false; - } - - function resetPassword() { - - var msg = Globalize.translate('PasswordResetConfirmation'); - - require(['confirm'], function (confirm) { - - confirm(msg, Globalize.translate('PasswordResetHeader')).then(function () { - - var userId = params.userId; - - Dashboard.showLoadingMsg(); - - ApiClient.resetUserPassword(userId).then(function () { - - Dashboard.hideLoadingMsg(); - - Dashboard.alert({ - message: Globalize.translate('PasswordResetComplete'), - title: Globalize.translate('PasswordResetHeader') - }); - - loadUser(view, params); - - }); - }); - }); - } - - function resetEasyPassword() { - - var msg = Globalize.translate('PinCodeResetConfirmation'); - - require(['confirm'], function (confirm) { - - confirm(msg, Globalize.translate('HeaderPinCodeReset')).then(function () { - - var userId = params.userId; - - Dashboard.showLoadingMsg(); - - ApiClient.resetEasyPassword(userId).then(function () { - - Dashboard.hideLoadingMsg(); - - Dashboard.alert({ - message: Globalize.translate('PinCodeResetComplete'), - title: Globalize.translate('HeaderPinCodeReset') - }); - - loadUser(view, params); - - }); - }); - }); - } - - view.querySelector('.updatePasswordForm').addEventListener('submit', onSubmit); - view.querySelector('.localAccessForm').addEventListener('submit', onLocalAccessSubmit); - - view.querySelector('#btnResetEasyPassword').addEventListener('click', resetEasyPassword); - view.querySelector('#btnResetPassword').addEventListener('click', resetPassword); - - view.addEventListener('viewshow', function () { - loadUser(view, params); - }); - }; -}); \ No newline at end of file +define([],function(){"use strict";function loadUser(page,params){var userid=params.userId;ApiClient.getUser(userid).then(function(user){Dashboard.getCurrentUser().then(function(loggedInUser){LibraryMenu.setTitle(user.Name);var showPasswordSection=!0,showLocalAccessSection=!1;"Guest"==user.ConnectLinkType?(page.querySelector(".localAccessSection").classList.add("hide"),showPasswordSection=!1):user.HasConfiguredPassword?(page.querySelector("#btnResetPassword").classList.remove("hide"),page.querySelector("#fldCurrentPassword").classList.remove("hide"),showLocalAccessSection=!0):(page.querySelector("#btnResetPassword").classList.add("hide"),page.querySelector("#fldCurrentPassword").classList.add("hide")),showPasswordSection&&(loggedInUser.Policy.IsAdministrator||user.Policy.EnableUserPreferenceAccess)?page.querySelector(".passwordSection").classList.remove("hide"):page.querySelector(".passwordSection").classList.add("hide"),showLocalAccessSection&&(loggedInUser.Policy.IsAdministrator||user.Policy.EnableUserPreferenceAccess)?page.querySelector(".localAccessSection").classList.remove("hide"):page.querySelector(".localAccessSection").classList.add("hide");var txtEasyPassword=page.querySelector("#txtEasyPassword");txtEasyPassword.value="",user.HasConfiguredEasyPassword?(txtEasyPassword.placeholder="******",page.querySelector("#btnResetEasyPassword").classList.remove("hide")):(txtEasyPassword.removeAttribute("placeholder"),txtEasyPassword.placeholder="",page.querySelector("#btnResetEasyPassword").classList.add("hide")),page.querySelector(".chkEnableLocalEasyPassword").checked=user.Configuration.EnableLocalPassword})}),page.querySelector("#txtCurrentPassword").value="",page.querySelector("#txtNewPassword").value="",page.querySelector("#txtNewPasswordConfirm").value=""}return function(view,params){function saveEasyPassword(){var userId=params.userId,easyPassword=view.querySelector("#txtEasyPassword").value;easyPassword?ApiClient.updateEasyPassword(userId,easyPassword).then(function(){onEasyPasswordSaved(userId)}):onEasyPasswordSaved(userId)}function onEasyPasswordSaved(userId){ApiClient.getUser(userId).then(function(user){user.Configuration.EnableLocalPassword=view.querySelector(".chkEnableLocalEasyPassword").checked,ApiClient.updateUserConfiguration(user.Id,user.Configuration).then(function(){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("MessageSettingsSaved"))}),loadUser(view,params)})})}function savePassword(){var userId=params.userId,currentPassword=view.querySelector("#txtCurrentPassword").value,newPassword=view.querySelector("#txtNewPassword").value;ApiClient.updateUserPassword(userId,currentPassword,newPassword).then(function(){Dashboard.hideLoadingMsg(),require(["toast"],function(toast){toast(Globalize.translate("PasswordSaved"))}),loadUser(view,params)},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({title:Globalize.translate("HeaderLoginFailure"),message:Globalize.translate("MessageInvalidUser")})})}function onSubmit(e){var form=this;return form.querySelector("#txtNewPassword").value!=form.querySelector("#txtNewPasswordConfirm").value?require(["toast"],function(toast){toast(Globalize.translate("PasswordMatchError"))}):(Dashboard.showLoadingMsg(),savePassword()),e.preventDefault(),!1}function onLocalAccessSubmit(e){return Dashboard.showLoadingMsg(),saveEasyPassword(),e.preventDefault(),!1}function resetPassword(){var msg=Globalize.translate("PasswordResetConfirmation");require(["confirm"],function(confirm){confirm(msg,Globalize.translate("PasswordResetHeader")).then(function(){var userId=params.userId;Dashboard.showLoadingMsg(),ApiClient.resetUserPassword(userId).then(function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("PasswordResetComplete"),title:Globalize.translate("PasswordResetHeader")}),loadUser(view,params)})})})}function resetEasyPassword(){var msg=Globalize.translate("PinCodeResetConfirmation");require(["confirm"],function(confirm){confirm(msg,Globalize.translate("HeaderPinCodeReset")).then(function(){var userId=params.userId;Dashboard.showLoadingMsg(),ApiClient.resetEasyPassword(userId).then(function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("PinCodeResetComplete"),title:Globalize.translate("HeaderPinCodeReset")}),loadUser(view,params)})})})}view.querySelector(".updatePasswordForm").addEventListener("submit",onSubmit),view.querySelector(".localAccessForm").addEventListener("submit",onLocalAccessSubmit),view.querySelector("#btnResetEasyPassword").addEventListener("click",resetEasyPassword),view.querySelector("#btnResetPassword").addEventListener("click",resetPassword),view.addEventListener("viewshow",function(){loadUser(view,params)})}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/userprofilespage.js b/dashboard-ui/scripts/userprofilespage.js index 83e1aa1111..19c2a9db48 100644 --- a/dashboard-ui/scripts/userprofilespage.js +++ b/dashboard-ui/scripts/userprofilespage.js @@ -1,409 +1 @@ -define(['jQuery', 'humanedate', 'paper-icon-button-light', 'cardStyle'], function ($) { - 'use strict'; - - function deleteUser(page, id) { - - var msg = Globalize.translate('DeleteUserConfirmation'); - - require(['confirm'], function (confirm) { - - confirm({ - - title: Globalize.translate('DeleteUser'), - text: msg, - confirmText: Globalize.translate('ButtonDelete'), - primary: 'cancel' - - }).then(function () { - - Dashboard.showLoadingMsg(); - - ApiClient.deleteUser(id).then(function () { - - loadData(page); - }); - }); - - }); - } - - function showUserMenu(elem) { - - var card = $(elem).parents('.card')[0]; - var page = $(card).parents('.page')[0]; - var userId = card.getAttribute('data-userid'); - - var menuItems = []; - - menuItems.push({ - name: Globalize.translate('ButtonOpen'), - id: 'open', - ironIcon: 'mode-edit' - }); - - menuItems.push({ - name: Globalize.translate('ButtonLibraryAccess'), - id: 'access', - ironIcon: 'lock' - }); - - menuItems.push({ - name: Globalize.translate('ButtonParentalControl'), - id: 'parentalcontrol', - ironIcon: 'person' - }); - - menuItems.push({ - name: Globalize.translate('ButtonDelete'), - id: 'delete', - ironIcon: 'delete' - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - positionTo: card, - callback: function (id) { - - switch (id) { - - case 'open': - Dashboard.navigate('useredit.html?userId=' + userId); - break; - case 'access': - Dashboard.navigate('userlibraryaccess.html?userId=' + userId); - break; - case 'parentalcontrol': - Dashboard.navigate('userparentalcontrol.html?userId=' + userId); - break; - case 'delete': - deleteUser(page, userId); - break; - default: - break; - } - } - }); - - }); - } - - function getUserHtml(user, addConnectIndicator) { - - var html = ''; - - var cssClass = "card squareCard scalableCard squareCard-scalable"; - - if (user.Policy.IsDisabled) { - cssClass += ' grayscale'; - } - - html += "
"; - - html += '
'; - html += '"; - - html += '
'; - - html += '
'; - html += ''; - html += "
"; - - html += '
'; - html += user.Name; - html += "
"; - - html += '
'; - var lastSeen = getLastSeenText(user.LastActivityDate); - if (lastSeen != "") { - html += lastSeen; - } - else { - html += " "; - } - html += '
'; - - // cardFooter - html += "
"; - - // cardBox - html += "
"; - - // card - html += "
"; - - return html; - } - - function getLastSeenText(lastActivityDate) { - - if (!lastActivityDate) { - return ""; - } - - return "Last seen " + humane_date(lastActivityDate); - } - - function getUserSectionHtml(users, addConnectIndicator) { - - var html = ''; - - html += users.map(function (u) { - - return getUserHtml(u, addConnectIndicator); - - }).join(''); - - return html; - } - - function renderUsersIntoElement(elem, users, addConnectIndicator) { - - var html = getUserSectionHtml(users, addConnectIndicator); - - elem.html(html); - - $('.btnUserMenu', elem).on('click', function () { - showUserMenu(this); - }); - } - - function renderUsers(page, users) { - - renderUsersIntoElement($('.localUsers', page), users.filter(function (u) { - return u.ConnectLinkType != 'Guest'; - }), true); - - renderUsersIntoElement($('.connectUsers', page), users.filter(function (u) { - return u.ConnectLinkType == 'Guest'; - })); - } - - function showPendingUserMenu(elem) { - - var menuItems = []; - - menuItems.push({ - name: Globalize.translate('ButtonCancel'), - id: 'delete', - ironIcon: 'delete' - }); - - require(['actionsheet'], function (actionsheet) { - - var card = $(elem).parents('.card')[0]; - var page = $(elem).parents('.page')[0]; - var id = card.getAttribute('data-id'); - - actionsheet.show({ - items: menuItems, - positionTo: card, - callback: function (menuItemId) { - - switch (menuItemId) { - - case 'delete': - cancelAuthorization(page, id); - break; - default: - break; - } - } - }); - }); - } - - function getPendingUserHtml(user) { - - var html = ''; - - var cssClass = "card squareCard"; - - html += "
"; - - html += '
'; - html += '"; - - html += '
'; - - html += '
'; - html += ''; - html += "
"; - - html += '
'; - html += user.UserName; - html += "
"; - - // cardFooter - html += "
"; - - // cardBox - html += "
"; - - // card - html += "
"; - - return html; - } - - function renderPendingGuests(page, users) { - - if (users.length) { - $('.sectionPendingGuests', page).show(); - } else { - $('.sectionPendingGuests', page).hide(); - } - - var html = users.map(getPendingUserHtml).join(''); - - var elem = $('.pending', page).html(html); - - $('.btnUserMenu', elem).on('click', function () { - showPendingUserMenu(this); - }); - } - - function cancelAuthorization(page, id) { - - Dashboard.showLoadingMsg(); - - // Add/Update connect info - ApiClient.ajax({ - - type: "DELETE", - url: ApiClient.getUrl('Connect/Pending', { - - Id: id - - }) - - }).then(function () { - - loadData(page); - - }); - } - - function loadData(page) { - - Dashboard.showLoadingMsg(); - - ApiClient.getUsers().then(function (users) { - renderUsers(page, users); - Dashboard.hideLoadingMsg(); - }); - - ApiClient.getJSON(ApiClient.getUrl('Connect/Pending')).then(function (pending) { - - renderPendingGuests(page, pending); - }); - } - - function showLinkUser(page, userId) { - - require(['components/guestinviter/connectlink'], function (connectlink) { - - connectlink.show().then(function () { - loadData(page); - }); - }); - } - - function showInvitePopup(page) { - - Dashboard.getCurrentUser().then(function (user) { - - if (!user.ConnectUserId) { - - showLinkUser(page, user.Id); - return; - } - - require(['components/guestinviter/guestinviter'], function (guestinviter) { - - guestinviter.show().then(function () { - loadData(page); - }); - }); - }); - } - - $(document).on('pageinit', "#userProfilesPage", function () { - - var page = this; - - $('.btnInvite', page).on('click', function () { - - showInvitePopup(page); - }); - - $('.btnAddUser', page).on('click', function () { - - Dashboard.navigate('usernew.html'); - }); - - }).on('pagebeforeshow', "#userProfilesPage", function () { - - var page = this; - - loadData(page); - }); - -}); \ No newline at end of file +define(["jQuery","humanedate","paper-icon-button-light","cardStyle"],function($){"use strict";function deleteUser(page,id){var msg=Globalize.translate("DeleteUserConfirmation");require(["confirm"],function(confirm){confirm({title:Globalize.translate("DeleteUser"),text:msg,confirmText:Globalize.translate("ButtonDelete"),primary:"cancel"}).then(function(){Dashboard.showLoadingMsg(),ApiClient.deleteUser(id).then(function(){loadData(page)})})})}function showUserMenu(elem){var card=$(elem).parents(".card")[0],page=$(card).parents(".page")[0],userId=card.getAttribute("data-userid"),menuItems=[];menuItems.push({name:Globalize.translate("ButtonOpen"),id:"open",ironIcon:"mode-edit"}),menuItems.push({name:Globalize.translate("ButtonLibraryAccess"),id:"access",ironIcon:"lock"}),menuItems.push({name:Globalize.translate("ButtonParentalControl"),id:"parentalcontrol",ironIcon:"person"}),menuItems.push({name:Globalize.translate("ButtonDelete"),id:"delete",ironIcon:"delete"}),require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,positionTo:card,callback:function(id){switch(id){case"open":Dashboard.navigate("useredit.html?userId="+userId);break;case"access":Dashboard.navigate("userlibraryaccess.html?userId="+userId);break;case"parentalcontrol":Dashboard.navigate("userparentalcontrol.html?userId="+userId);break;case"delete":deleteUser(page,userId)}}})})}function getUserHtml(user,addConnectIndicator){var html="",cssClass="card squareCard scalableCard squareCard-scalable";user.Policy.IsDisabled&&(cssClass+=" grayscale"),html+="
",html+='
',html+='",html+='
',html+='
',html+='',html+="
",html+='
',html+=user.Name,html+="
",html+='
';var lastSeen=getLastSeenText(user.LastActivityDate);return html+=""!=lastSeen?lastSeen:" ",html+="
",html+="
",html+="
",html+="
"}function getLastSeenText(lastActivityDate){return lastActivityDate?"Last seen "+humane_date(lastActivityDate):""}function getUserSectionHtml(users,addConnectIndicator){var html="";return html+=users.map(function(u){return getUserHtml(u,addConnectIndicator)}).join("")}function renderUsersIntoElement(elem,users,addConnectIndicator){var html=getUserSectionHtml(users,addConnectIndicator);elem.html(html),$(".btnUserMenu",elem).on("click",function(){showUserMenu(this)})}function renderUsers(page,users){renderUsersIntoElement($(".localUsers",page),users.filter(function(u){return"Guest"!=u.ConnectLinkType}),!0),renderUsersIntoElement($(".connectUsers",page),users.filter(function(u){return"Guest"==u.ConnectLinkType}))}function showPendingUserMenu(elem){var menuItems=[];menuItems.push({name:Globalize.translate("ButtonCancel"),id:"delete",ironIcon:"delete"}),require(["actionsheet"],function(actionsheet){var card=$(elem).parents(".card")[0],page=$(elem).parents(".page")[0],id=card.getAttribute("data-id");actionsheet.show({items:menuItems,positionTo:card,callback:function(menuItemId){switch(menuItemId){case"delete":cancelAuthorization(page,id)}}})})}function getPendingUserHtml(user){var html="",cssClass="card squareCard";html+="
",html+='
',html+='",html+='
',html+='
',html+='',html+="
",html+='
',html+=user.UserName,html+="
",html+="
",html+="
",html+="
"}function renderPendingGuests(page,users){users.length?$(".sectionPendingGuests",page).show():$(".sectionPendingGuests",page).hide();var html=users.map(getPendingUserHtml).join(""),elem=$(".pending",page).html(html);$(".btnUserMenu",elem).on("click",function(){showPendingUserMenu(this)})}function cancelAuthorization(page,id){Dashboard.showLoadingMsg(),ApiClient.ajax({type:"DELETE",url:ApiClient.getUrl("Connect/Pending",{Id:id})}).then(function(){loadData(page)})}function loadData(page){Dashboard.showLoadingMsg(),ApiClient.getUsers().then(function(users){renderUsers(page,users),Dashboard.hideLoadingMsg()}),ApiClient.getJSON(ApiClient.getUrl("Connect/Pending")).then(function(pending){renderPendingGuests(page,pending)})}function showLinkUser(page,userId){require(["components/guestinviter/connectlink"],function(connectlink){connectlink.show().then(function(){loadData(page)})})}function showInvitePopup(page){Dashboard.getCurrentUser().then(function(user){return user.ConnectUserId?void require(["components/guestinviter/guestinviter"],function(guestinviter){guestinviter.show().then(function(){loadData(page)})}):void showLinkUser(page,user.Id)})}$(document).on("pageinit","#userProfilesPage",function(){var page=this;$(".btnInvite",page).on("click",function(){showInvitePopup(page)}),$(".btnAddUser",page).on("click",function(){Dashboard.navigate("usernew.html")})}).on("pagebeforeshow","#userProfilesPage",function(){var page=this;loadData(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/videoosd.js b/dashboard-ui/scripts/videoosd.js index cf2ad332d6..78f8162cb5 100644 --- a/dashboard-ui/scripts/videoosd.js +++ b/dashboard-ui/scripts/videoosd.js @@ -1,1047 +1 @@ -define(['playbackManager', 'dom', 'inputmanager', 'datetime', 'itemHelper', 'mediaInfo', 'focusManager', 'imageLoader', 'scrollHelper', 'events', 'connectionManager', 'browser', 'globalize', 'apphost', 'layoutManager', 'scrollStyles', 'emby-slider'], function (playbackManager, dom, inputManager, datetime, itemHelper, mediaInfo, focusManager, imageLoader, scrollHelper, events, connectionManager, browser, globalize, appHost, layoutManager) { - 'use strict'; - - function seriesImageUrl(item, options) { - - if (item.Type !== 'Episode') { - return null; - } - - options = options || {}; - options.type = options.type || "Primary"; - - if (options.type === 'Primary') { - - if (item.SeriesPrimaryImageTag) { - - options.tag = item.SeriesPrimaryImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - } - - if (options.type === 'Thumb') { - - if (item.SeriesThumbImageTag) { - - options.tag = item.SeriesThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId, options); - } - if (item.ParentThumbImageTag) { - - options.tag = item.ParentThumbImageTag; - - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId, options); - } - } - - return null; - } - - function imageUrl(item, options) { - - options = options || {}; - options.type = options.type || "Primary"; - - if (item.ImageTags && item.ImageTags[options.type]) { - - options.tag = item.ImageTags[options.type]; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId || item.Id, options); - } - - if (options.type === 'Primary') { - if (item.AlbumId && item.AlbumPrimaryImageTag) { - - options.tag = item.AlbumPrimaryImageTag; - return connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId, options); - } - } - - return null; - } - - function logoImageUrl(item, apiClient, options) { - - options = options || {}; - options.type = "Logo"; - - if (item.ImageTags && item.ImageTags.Logo) { - - options.tag = item.ImageTags.Logo; - return apiClient.getScaledImageUrl(item.Id, options); - } - - if (item.ParentLogoImageTag) { - options.tag = item.ParentLogoImageTag; - return apiClient.getScaledImageUrl(item.ParentLogoItemId, options); - } - - return null; - } - - return function (view, params) { - - var self = this; - var currentPlayer; - var currentPlayerSupportedCommands = []; - var currentRuntimeTicks = 0; - var lastUpdateTime = 0; - var isEnabled; - var currentItem; - - var nowPlayingVolumeSlider = view.querySelector('.osdVolumeSlider'); - var nowPlayingVolumeSliderContainer = view.querySelector('.osdVolumeSliderContainer'); - - var nowPlayingPositionSlider = view.querySelector('.osdPositionSlider'); - - var nowPlayingPositionText = view.querySelector('.osdPositionText'); - var nowPlayingDurationText = view.querySelector('.osdDurationText'); - var endsAtText = view.querySelector('.endsAtText'); - - var btnRewind = view.querySelector('.btnRewind'); - var btnFastForward = view.querySelector('.btnFastForward'); - - var transitionEndEventName = dom.whichTransitionEvent(); - - var headerElement = document.querySelector('.skinHeader'); - var osdBottomElement = document.querySelector('.videoOsdBottom'); - - function updateNowPlayingInfo(state) { - - var item = state.NowPlayingItem; - currentItem = item; - - setPoster(item); - - if (!item) { - Emby.Page.setTitle(''); - nowPlayingVolumeSlider.disabled = true; - nowPlayingPositionSlider.disabled = true; - btnFastForward.disabled = true; - btnRewind.disabled = true; - - view.querySelector('.btnSubtitles').classList.add('hide'); - view.querySelector('.btnAudio').classList.add('hide'); - - view.querySelector('.osdTitle').innerHTML = ''; - view.querySelector('.osdMediaInfo').innerHTML = ''; - return; - } - - setTitle(item); - - view.querySelector('.osdTitle').innerHTML = itemHelper.getDisplayName(item); - view.querySelector('.osdMediaInfo').innerHTML = mediaInfo.getPrimaryMediaInfoHtml(item, { - runtime: false, - subtitles: false, - tomatoes: false, - endsAt: false - }); - - nowPlayingVolumeSlider.disabled = false; - nowPlayingPositionSlider.disabled = false; - btnFastForward.disabled = false; - btnRewind.disabled = false; - - if (playbackManager.subtitleTracks(currentPlayer).length) { - view.querySelector('.btnSubtitles').classList.remove('hide'); - } else { - view.querySelector('.btnSubtitles').classList.add('hide'); - } - - if (playbackManager.audioTracks(currentPlayer).length > 1) { - view.querySelector('.btnAudio').classList.remove('hide'); - } else { - view.querySelector('.btnAudio').classList.add('hide'); - } - - } - - function setTitle(item) { - - var url = logoImageUrl(item, connectionManager.getApiClient(item.ServerId), {}); - - if (url) { - - //var pageTitle = document.querySelector('.pageTitle'); - //pageTitle.style.backgroundImage = "url('" + url + "')"; - //pageTitle.classList.add('pageTitleWithLogo'); - //pageTitle.innerHTML = ''; - //document.querySelector('.headerLogo').classList.add('hide'); - } else { - Emby.Page.setTitle(''); - } - } - - function setPoster(item) { - - var osdPoster = view.querySelector('.osdPoster'); - - if (item) { - - var imgUrl = seriesImageUrl(item, { type: 'Primary' }) || - seriesImageUrl(item, { type: 'Thumb' }) || - imageUrl(item, { type: 'Primary' }); - - if (imgUrl) { - osdPoster.innerHTML = ''; - return; - } - } - - osdPoster.innerHTML = ''; - } - - var _osdOpen = true; - - function isOsdOpen() { - return _osdOpen; - } - - function showOsd() { - - slideDownToShow(headerElement); - slideUpToShow(osdBottomElement); - startHideTimer(); - } - - function hideOsd() { - - slideUpToHide(headerElement); - slideDownToHide(osdBottomElement); - } - - var hideTimeout; - - function startHideTimer() { - stopHideTimer(); - hideTimeout = setTimeout(hideOsd, 5000); - } - - function stopHideTimer() { - if (hideTimeout) { - clearTimeout(hideTimeout); - hideTimeout = null; - } - } - - function slideDownToShow(elem) { - - elem.classList.remove('osdHeader-hidden'); - } - - function slideUpToHide(elem) { - - elem.classList.add('osdHeader-hidden'); - } - - function clearBottomPanelAnimationEventListeners(elem) { - - dom.removeEventListener(elem, transitionEndEventName, onSlideDownComplete, { - once: true - }); - } - - function slideUpToShow(elem) { - - if (_osdOpen) { - return; - } - - _osdOpen = true; - - clearBottomPanelAnimationEventListeners(elem); - - elem.classList.remove('hide'); - - // trigger a reflow to force it to animate again - void elem.offsetWidth; - - elem.classList.remove('videoOsdBottom-hidden'); - - setTimeout(function () { - focusManager.focus(elem.querySelector('.btnPause')); - }, 50); - - view.dispatchEvent(new CustomEvent('video-osd-show', { - bubbles: true, - cancelable: false - })); - } - - function onSlideDownComplete(e) { - - var elem = e.target; - - elem.classList.add('hide'); - - dom.removeEventListener(elem, transitionEndEventName, onSlideDownComplete, { - once: true - }); - - view.dispatchEvent(new CustomEvent('video-osd-hide', { - bubbles: true, - cancelable: false - })); - } - - function slideDownToHide(elem) { - - if (!_osdOpen) { - return; - } - - clearBottomPanelAnimationEventListeners(elem); - - // trigger a reflow to force it to animate again - void elem.offsetWidth; - - elem.classList.add('videoOsdBottom-hidden'); - - dom.addEventListener(elem, transitionEndEventName, onSlideDownComplete, { - once: true - }); - - _osdOpen = false; - } - - var lastMouseMoveData; - - function onMouseMove(e) { - - var eventX = e.screenX || 0; - var eventY = e.screenY || 0; - - var obj = lastMouseMoveData; - if (!obj) { - lastMouseMoveData = { - x: eventX, - y: eventY - }; - return; - } - - // if coord are same, it didn't move - if (Math.abs(eventX - obj.x) < 10 && Math.abs(eventY - obj.y) < 10) { - return; - } - - obj.x = eventX; - obj.y = eventY; - - showOsd(); - } - - function onInputCommand(e) { - - switch (e.detail.command) { - - case 'left': - if (isOsdOpen()) { - showOsd(); - } else { - e.preventDefault(); - playbackManager.rewind(); - } - break; - case 'right': - if (isOsdOpen()) { - showOsd(); - } else { - e.preventDefault(); - playbackManager.fastForward(); - } - break; - case 'up': - case 'down': - case 'select': - case 'menu': - case 'info': - case 'play': - case 'playpause': - case 'pause': - case 'fastforward': - case 'rewind': - case 'next': - case 'previous': - showOsd(); - break; - default: - break; - } - } - - function updateFullscreenIcon() { - if (playbackManager.isFullscreen(currentPlayer)) { - view.querySelector('.btnFullscreen').setAttribute('title', globalize.translate('ExitFullscreen')); - view.querySelector('.btnFullscreen i').innerHTML = ''; - } else { - view.querySelector('.btnFullscreen').setAttribute('title', globalize.translate('Fullscreen')); - view.querySelector('.btnFullscreen i').innerHTML = ''; - } - } - - view.addEventListener('viewbeforeshow', function (e) { - - headerElement.classList.add('osdHeader'); - // Make sure the UI is completely transparent - Emby.Page.setTransparency('full'); - }); - - view.addEventListener('viewshow', function (e) { - - events.on(playbackManager, 'playerchange', onPlayerChange); - bindToPlayer(playbackManager.getCurrentPlayer()); - - dom.addEventListener(document, 'mousemove', onMouseMove, { - passive: true - }); - document.body.classList.add('autoScrollY'); - - showOsd(); - - inputManager.on(window, onInputCommand); - - dom.addEventListener(window, 'keydown', onWindowKeyDown, { - passive: true - }); - }); - - view.addEventListener('viewbeforehide', function () { - - dom.removeEventListener(window, 'keydown', onWindowKeyDown, { - passive: true - }); - - stopHideTimer(); - headerElement.classList.remove('osdHeader'); - headerElement.classList.remove('osdHeader-hidden'); - dom.removeEventListener(document, 'mousemove', onMouseMove, { - passive: true - }); - document.body.classList.remove('autoScrollY'); - - inputManager.off(window, onInputCommand); - events.off(playbackManager, 'playerchange', onPlayerChange); - releaseCurrentPlayer(); - }); - - if (appHost.supports('remotecontrol') && !layoutManager.tv) { - view.querySelector('.btnCast').classList.remove('hide'); - } - - view.querySelector('.btnCast').addEventListener('click', function () { - var btn = this; - require(['playerSelectionMenu'], function (playerSelectionMenu) { - playerSelectionMenu.show(btn); - }); - }); - - view.querySelector('.btnFullscreen').addEventListener('click', function () { - playbackManager.toggleFullscreen(currentPlayer); - }); - - view.querySelector('.btnPip').addEventListener('click', function () { - playbackManager.togglePictureInPicture(currentPlayer); - }); - - view.querySelector('.btnSettings').addEventListener('click', onSettingsButtonClick); - - function onPlayerChange() { - - var player = playbackManager.getCurrentPlayer(); - - if (player && !player.isLocalPlayer) { - view.querySelector('.btnCast i').innerHTML = ''; - } else { - view.querySelector('.btnCast i').innerHTML = ''; - } - bindToPlayer(player); - } - - function onStateChanged(event, state) { - - //console.log('nowplaying event: ' + e.type); - var player = this; - - if (!state.NowPlayingItem) { - return; - } - - isEnabled = true; - - updatePlayerStateInternal(event, state); - updatePlaylist(player); - - enableStopOnBack(true); - } - - function onPlayPauseStateChanged(e) { - - if (!isEnabled) { - return; - } - - var player = this; - updatePlayPauseState(player.paused()); - } - - function onVolumeChanged(e) { - - if (!isEnabled) { - return; - } - - var player = this; - - updatePlayerVolumeState(player.isMuted(), player.getVolume()); - } - - function onPlaybackStart(e, state) { - - console.log('nowplaying event: ' + e.type); - - var player = this; - - onStateChanged.call(player, e, state); - } - - function onPlaybackStopped(e, state) { - - currentRuntimeTicks = null; - - console.log('nowplaying event: ' + e.type); - - if (state.nextMediaType !== 'Video') { - - view.removeEventListener('viewbeforehide', onViewHideStopPlayback); - - Emby.Page.back(); - } - } - - function bindToPlayer(player) { - - if (player === currentPlayer) { - return; - } - - releaseCurrentPlayer(); - - currentPlayer = player; - - if (!player) { - return; - } - - playbackManager.getPlayerState(player).then(function (state) { - - onStateChanged.call(player, { type: 'init' }, state); - }); - - events.on(player, 'playbackstart', onPlaybackStart); - events.on(player, 'playbackstop', onPlaybackStopped); - events.on(player, 'volumechange', onVolumeChanged); - events.on(player, 'pause', onPlayPauseStateChanged); - events.on(player, 'playing', onPlayPauseStateChanged); - events.on(player, 'timeupdate', onTimeUpdate); - events.on(player, 'fullscreenchange', updateFullscreenIcon); - } - - function releaseCurrentPlayer() { - - var player = currentPlayer; - - if (player) { - - events.off(player, 'playbackstart', onPlaybackStart); - events.off(player, 'playbackstop', onPlaybackStopped); - events.off(player, 'volumechange', onVolumeChanged); - events.off(player, 'pause', onPlayPauseStateChanged); - events.off(player, 'playing', onPlayPauseStateChanged); - events.off(player, 'timeupdate', onTimeUpdate); - events.off(player, 'fullscreenchange', updateFullscreenIcon); - - currentPlayer = null; - } - } - - function onTimeUpdate(e) { - - if (!isEnabled) { - return; - } - - // Try to avoid hammering the document with changes - var now = new Date().getTime(); - if ((now - lastUpdateTime) < 700) { - - return; - } - lastUpdateTime = now; - - var player = this; - currentRuntimeTicks = playbackManager.duration(player); - updateTimeDisplay(playbackManager.currentTime(player), currentRuntimeTicks); - } - - function updatePlayPauseState(isPaused) { - - if (isPaused) { - view.querySelector('.btnPause i').innerHTML = ''; - } else { - view.querySelector('.btnPause i').innerHTML = ''; - } - } - - function updatePlayerStateInternal(event, state) { - - var playerInfo = playbackManager.getPlayerInfo(); - - var playState = state.PlayState || {}; - - updatePlayPauseState(playState.IsPaused); - - var supportedCommands = playerInfo.supportedCommands; - currentPlayerSupportedCommands = supportedCommands; - - //if (supportedCommands.indexOf('SetRepeatMode') == -1) { - // toggleRepeatButton.classList.add('hide'); - //} else { - // toggleRepeatButton.classList.remove('hide'); - //} - - //if (playState.RepeatMode == 'RepeatAll') { - // toggleRepeatButtonIcon.innerHTML = "repeat"; - // toggleRepeatButton.classList.add('repeatActive'); - //} - //else if (playState.RepeatMode == 'RepeatOne') { - // toggleRepeatButtonIcon.innerHTML = "repeat_one"; - // toggleRepeatButton.classList.add('repeatActive'); - //} else { - // toggleRepeatButtonIcon.innerHTML = "repeat"; - // toggleRepeatButton.classList.remove('repeatActive'); - //} - - updatePlayerVolumeState(playState.IsMuted, playState.VolumeLevel); - - if (nowPlayingPositionSlider && !nowPlayingPositionSlider.dragging) { - nowPlayingPositionSlider.disabled = !playState.CanSeek; - } - - btnFastForward.disabled = !playState.CanSeek; - btnRewind.disabled = !playState.CanSeek; - - var nowPlayingItem = state.NowPlayingItem || {}; - updateTimeDisplay(playState.PositionTicks, nowPlayingItem.RunTimeTicks); - - updateNowPlayingInfo(state); - - if (state.MediaSource && state.MediaSource.SupportsTranscoding && supportedCommands.indexOf('SetMaxStreamingBitrate') !== -1) { - view.querySelector('.btnSettings').classList.remove('hide'); - } else { - view.querySelector('.btnSettings').classList.add('hide'); - } - - if (supportedCommands.indexOf('ToggleFullscreen') === -1) { - view.querySelector('.btnFullscreen').classList.add('hide'); - } else { - view.querySelector('.btnFullscreen').classList.remove('hide'); - } - - if (supportedCommands.indexOf('PictureInPicture') === -1) { - view.querySelector('.btnPip').classList.add('hide'); - } else { - view.querySelector('.btnPip').classList.remove('hide'); - } - - updateFullscreenIcon(); - } - - function updateTimeDisplay(positionTicks, runtimeTicks) { - - if (nowPlayingPositionSlider && !nowPlayingPositionSlider.dragging) { - if (runtimeTicks) { - - var pct = positionTicks / runtimeTicks; - pct *= 100; - - nowPlayingPositionSlider.value = pct; - - } else { - - nowPlayingPositionSlider.value = 0; - } - - if (runtimeTicks && positionTicks != null) { - endsAtText.innerHTML = '  -  ' + mediaInfo.getEndsAtFromPosition(runtimeTicks, positionTicks, true); - } else { - endsAtText.innerHTML = ''; - } - } - - updateTimeText(nowPlayingPositionText, positionTicks); - updateTimeText(nowPlayingDurationText, runtimeTicks, true); - } - - function updatePlayerVolumeState(isMuted, volumeLevel) { - - var supportedCommands = currentPlayerSupportedCommands; - - var showMuteButton = true; - var showVolumeSlider = true; - - if (supportedCommands.indexOf('Mute') === -1) { - showMuteButton = false; - } - - if (supportedCommands.indexOf('SetVolume') === -1) { - showVolumeSlider = false; - } - - if (currentPlayer.isLocalPlayer && appHost.supports('physicalvolumecontrol')) { - showMuteButton = false; - showVolumeSlider = false; - } - - if (isMuted) { - view.querySelector('.buttonMute').setAttribute('title', globalize.translate('Unmute')); - view.querySelector('.buttonMute i').innerHTML = ''; - } else { - view.querySelector('.buttonMute').setAttribute('title', globalize.translate('Mute')); - view.querySelector('.buttonMute i').innerHTML = ''; - } - - if (showMuteButton) { - view.querySelector('.buttonMute').classList.remove('hide'); - } else { - view.querySelector('.buttonMute').classList.add('hide'); - } - - // See bindEvents for why this is necessary - if (nowPlayingVolumeSlider) { - - if (showVolumeSlider) { - nowPlayingVolumeSliderContainer.classList.remove('hide'); - } else { - nowPlayingVolumeSliderContainer.classList.add('hide'); - } - - if (!nowPlayingVolumeSlider.dragging) { - nowPlayingVolumeSlider.value = volumeLevel || 0; - } - } - } - - function updatePlaylist(player) { - - var btnPreviousTrack = view.querySelector('.btnPreviousTrack'); - var btnNextTrack = view.querySelector('.btnNextTrack'); - - btnPreviousTrack.classList.remove('hide'); - btnNextTrack.classList.remove('hide'); - - btnNextTrack.disabled = false; - btnPreviousTrack.disabled = false; - } - - function updateTimeText(elem, ticks, divider) { - - if (ticks == null) { - elem.innerHTML = ''; - return; - } - - var html = datetime.getDisplayRunningTime(ticks); - - if (divider) { - html = ' / ' + html; - } - - elem.innerHTML = html; - } - - function onSettingsButtonClick(e) { - - var btn = this; - - require(['playerSettingsMenu'], function (playerSettingsMenu) { - playerSettingsMenu.show({ - mediaType: 'Video', - player: currentPlayer, - positionTo: btn - }); - }); - } - - function showAudioTrackSelection() { - - var player = currentPlayer; - - var audioTracks = playbackManager.audioTracks(player); - - var currentIndex = playbackManager.getAudioStreamIndex(player); - - var menuItems = audioTracks.map(function (stream) { - - var opt = { - name: stream.DisplayTitle, - id: stream.Index - }; - - if (stream.Index === currentIndex) { - opt.selected = true; - } - - return opt; - }); - - var positionTo = this; - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - items: menuItems, - title: globalize.translate('Audio'), - positionTo: positionTo - }).then(function (id) { - var index = parseInt(id); - if (index !== currentIndex) { - playbackManager.setAudioStreamIndex(index, currentPlayer); - } - }); - }); - } - - function showSubtitleTrackSelection() { - - var player = currentPlayer; - - var streams = playbackManager.subtitleTracks(player); - - var currentIndex = playbackManager.getSubtitleStreamIndex(player); - if (currentIndex == null) { - currentIndex = -1; - } - - streams.unshift({ - Index: -1, - DisplayTitle: globalize.translate('Off') - }); - - var menuItems = streams.map(function (stream) { - - var opt = { - name: stream.DisplayTitle, - id: stream.Index - }; - - if (stream.Index === currentIndex) { - opt.selected = true; - } - - return opt; - }); - - var positionTo = this; - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - title: globalize.translate('Subtitles'), - items: menuItems, - positionTo: positionTo - }).then(function (id) { - var index = parseInt(id); - if (index !== currentIndex) { - playbackManager.setSubtitleStreamIndex(index, currentPlayer); - } - }); - - }); - } - - view.addEventListener('viewhide', function () { - - headerElement.classList.remove('hide'); - }); - - function onWindowKeyDown(e) { - if (e.keyCode === 32 && !isOsdOpen()) { - playbackManager.playPause(currentPlayer); - showOsd(); - } - } - - view.querySelector('.pageContainer').addEventListener('click', function () { - - // TODO: Replace this check with click vs tap detection - if (!browser.touch) { - playbackManager.playPause(currentPlayer); - } - showOsd(); - }); - - view.querySelector('.buttonMute').addEventListener('click', function () { - - playbackManager.toggleMute(currentPlayer); - }); - - nowPlayingVolumeSlider.addEventListener('change', function () { - - playbackManager.setVolume(this.value, currentPlayer); - }); - - nowPlayingPositionSlider.addEventListener('change', function () { - - if (currentPlayer) { - - var newPercent = parseFloat(this.value); - - playbackManager.seekPercent(newPercent, currentPlayer); - } - }); - - function getImgUrl(item, chapter, index, maxWidth, apiClient) { - - if (chapter.ImageTag) { - - return apiClient.getScaledImageUrl(item.Id, { - maxWidth: maxWidth, - tag: chapter.ImageTag, - type: "Chapter", - index: index - }); - } - - return null; - } - - function getChapterBubbleHtml(apiClient, item, chapters, positionTicks) { - - var chapter; - var index = -1; - - for (var i = 0, length = chapters.length; i < length; i++) { - - var currentChapter = chapters[i]; - - if (positionTicks >= currentChapter.StartPositionTicks) { - chapter = currentChapter; - index = i; - } - } - - if (!chapter) { - return null; - } - - var src = getImgUrl(item, chapter, index, 400, apiClient); - - if (src) { - - var html = '
'; - html += ''; - - html += '
'; - html += '
'; - html += chapter.Name; - html += '
'; - html += '

'; - html += datetime.getDisplayRunningTime(positionTicks); - html += '

'; - html += '
'; - - html += '
'; - - return html; - } - - return null; - } - - nowPlayingPositionSlider.getBubbleHtml = function (value) { - - showOsd(); - - if (!currentRuntimeTicks) { - return '--:--'; - } - - var ticks = currentRuntimeTicks; - ticks /= 100; - ticks *= value; - - var item = currentItem; - if (item && item.Chapters && item.Chapters.length && item.Chapters[0].ImageTag) { - var html = getChapterBubbleHtml(connectionManager.getApiClient(item.ServerId), item, item.Chapters, ticks); - - if (html) { - return html; - } - } - - return '

' + datetime.getDisplayRunningTime(ticks) + '

'; - }; - - view.querySelector('.btnPreviousTrack').addEventListener('click', function () { - - playbackManager.previousChapter(currentPlayer); - }); - - view.querySelector('.btnPause').addEventListener('click', function () { - - playbackManager.playPause(currentPlayer); - }); - - view.querySelector('.btnNextTrack').addEventListener('click', function () { - - playbackManager.nextChapter(currentPlayer); - }); - - btnRewind.addEventListener('click', function () { - - playbackManager.rewind(currentPlayer); - }); - - btnFastForward.addEventListener('click', function () { - - playbackManager.fastForward(currentPlayer); - }); - - view.querySelector('.btnAudio').addEventListener('click', showAudioTrackSelection); - view.querySelector('.btnSubtitles').addEventListener('click', showSubtitleTrackSelection); - - function onViewHideStopPlayback() { - - if (playbackManager.isPlayingVideo()) { - - var player = currentPlayer; - - // Unbind this event so that we don't go back twice - view.removeEventListener('viewbeforehide', onViewHideStopPlayback); - - releaseCurrentPlayer(); - - playbackManager.stop(player); - - // or - //Emby.Page.setTransparency(Emby.TransparencyLevel.Backdrop); - } - } - - function enableStopOnBack(enabled) { - - view.removeEventListener('viewbeforehide', onViewHideStopPlayback); - - if (enabled) { - if (playbackManager.isPlayingVideo(currentPlayer)) { - view.addEventListener('viewbeforehide', onViewHideStopPlayback); - } - } - } - - }; - -}); \ No newline at end of file +define(["playbackManager","dom","inputmanager","datetime","itemHelper","mediaInfo","focusManager","imageLoader","scrollHelper","events","connectionManager","browser","globalize","apphost","layoutManager","scrollStyles","emby-slider"],function(playbackManager,dom,inputManager,datetime,itemHelper,mediaInfo,focusManager,imageLoader,scrollHelper,events,connectionManager,browser,globalize,appHost,layoutManager){"use strict";function seriesImageUrl(item,options){if("Episode"!==item.Type)return null;if(options=options||{},options.type=options.type||"Primary","Primary"===options.type&&item.SeriesPrimaryImageTag)return options.tag=item.SeriesPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if("Thumb"===options.type){if(item.SeriesThumbImageTag)return options.tag=item.SeriesThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.SeriesId,options);if(item.ParentThumbImageTag)return options.tag=item.ParentThumbImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.ParentThumbItemId,options)}return null}function imageUrl(item,options){return options=options||{},options.type=options.type||"Primary",item.ImageTags&&item.ImageTags[options.type]?(options.tag=item.ImageTags[options.type],connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.PrimaryImageItemId||item.Id,options)):"Primary"===options.type&&item.AlbumId&&item.AlbumPrimaryImageTag?(options.tag=item.AlbumPrimaryImageTag,connectionManager.getApiClient(item.ServerId).getScaledImageUrl(item.AlbumId,options)):null}function logoImageUrl(item,apiClient,options){return options=options||{},options.type="Logo",item.ImageTags&&item.ImageTags.Logo?(options.tag=item.ImageTags.Logo,apiClient.getScaledImageUrl(item.Id,options)):item.ParentLogoImageTag?(options.tag=item.ParentLogoImageTag,apiClient.getScaledImageUrl(item.ParentLogoItemId,options)):null}return function(view,params){function updateNowPlayingInfo(state){var item=state.NowPlayingItem;return currentItem=item,setPoster(item),item?(setTitle(item),view.querySelector(".osdTitle").innerHTML=itemHelper.getDisplayName(item),view.querySelector(".osdMediaInfo").innerHTML=mediaInfo.getPrimaryMediaInfoHtml(item,{runtime:!1,subtitles:!1,tomatoes:!1,endsAt:!1}),nowPlayingVolumeSlider.disabled=!1,nowPlayingPositionSlider.disabled=!1,btnFastForward.disabled=!1,btnRewind.disabled=!1,playbackManager.subtitleTracks(currentPlayer).length?view.querySelector(".btnSubtitles").classList.remove("hide"):view.querySelector(".btnSubtitles").classList.add("hide"),void(playbackManager.audioTracks(currentPlayer).length>1?view.querySelector(".btnAudio").classList.remove("hide"):view.querySelector(".btnAudio").classList.add("hide"))):(Emby.Page.setTitle(""),nowPlayingVolumeSlider.disabled=!0,nowPlayingPositionSlider.disabled=!0,btnFastForward.disabled=!0,btnRewind.disabled=!0,view.querySelector(".btnSubtitles").classList.add("hide"),view.querySelector(".btnAudio").classList.add("hide"),view.querySelector(".osdTitle").innerHTML="",void(view.querySelector(".osdMediaInfo").innerHTML=""))}function setTitle(item){var url=logoImageUrl(item,connectionManager.getApiClient(item.ServerId),{});url||Emby.Page.setTitle("")}function setPoster(item){var osdPoster=view.querySelector(".osdPoster");if(item){var imgUrl=seriesImageUrl(item,{type:"Primary"})||seriesImageUrl(item,{type:"Thumb"})||imageUrl(item,{type:"Primary"});if(imgUrl)return void(osdPoster.innerHTML='')}osdPoster.innerHTML=""}function isOsdOpen(){return _osdOpen}function showOsd(){slideDownToShow(headerElement),slideUpToShow(osdBottomElement),startHideTimer()}function hideOsd(){slideUpToHide(headerElement),slideDownToHide(osdBottomElement)}function startHideTimer(){stopHideTimer(),hideTimeout=setTimeout(hideOsd,5e3)}function stopHideTimer(){hideTimeout&&(clearTimeout(hideTimeout),hideTimeout=null)}function slideDownToShow(elem){elem.classList.remove("osdHeader-hidden")}function slideUpToHide(elem){elem.classList.add("osdHeader-hidden")}function clearBottomPanelAnimationEventListeners(elem){dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0})}function slideUpToShow(elem){_osdOpen||(_osdOpen=!0,clearBottomPanelAnimationEventListeners(elem),elem.classList.remove("hide"),void elem.offsetWidth,elem.classList.remove("videoOsdBottom-hidden"),setTimeout(function(){focusManager.focus(elem.querySelector(".btnPause"))},50),view.dispatchEvent(new CustomEvent("video-osd-show",{bubbles:!0,cancelable:!1})))}function onSlideDownComplete(e){var elem=e.target;elem.classList.add("hide"),dom.removeEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),view.dispatchEvent(new CustomEvent("video-osd-hide",{bubbles:!0,cancelable:!1}))}function slideDownToHide(elem){_osdOpen&&(clearBottomPanelAnimationEventListeners(elem),void elem.offsetWidth,elem.classList.add("videoOsdBottom-hidden"),dom.addEventListener(elem,transitionEndEventName,onSlideDownComplete,{once:!0}),_osdOpen=!1)}function onMouseMove(e){var eventX=e.screenX||0,eventY=e.screenY||0,obj=lastMouseMoveData;return obj?void(Math.abs(eventX-obj.x)<10&&Math.abs(eventY-obj.y)<10||(obj.x=eventX,obj.y=eventY,showOsd())):void(lastMouseMoveData={x:eventX,y:eventY})}function onInputCommand(e){switch(e.detail.command){case"left":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.rewind());break;case"right":isOsdOpen()?showOsd():(e.preventDefault(),playbackManager.fastForward());break;case"up":case"down":case"select":case"menu":case"info":case"play":case"playpause":case"pause":case"fastforward":case"rewind":case"next":case"previous":showOsd()}}function updateFullscreenIcon(){playbackManager.isFullscreen(currentPlayer)?(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("ExitFullscreen")),view.querySelector(".btnFullscreen i").innerHTML=""):(view.querySelector(".btnFullscreen").setAttribute("title",globalize.translate("Fullscreen")),view.querySelector(".btnFullscreen i").innerHTML="")}function onPlayerChange(){var player=playbackManager.getCurrentPlayer();player&&!player.isLocalPlayer?view.querySelector(".btnCast i").innerHTML="":view.querySelector(".btnCast i").innerHTML="",bindToPlayer(player)}function onStateChanged(event,state){var player=this;state.NowPlayingItem&&(isEnabled=!0,updatePlayerStateInternal(event,state),updatePlaylist(player),enableStopOnBack(!0))}function onPlayPauseStateChanged(e){if(isEnabled){var player=this;updatePlayPauseState(player.paused())}}function onVolumeChanged(e){if(isEnabled){var player=this;updatePlayerVolumeState(player.isMuted(),player.getVolume())}}function onPlaybackStart(e,state){console.log("nowplaying event: "+e.type);var player=this;onStateChanged.call(player,e,state)}function onPlaybackStopped(e,state){currentRuntimeTicks=null,console.log("nowplaying event: "+e.type),"Video"!==state.nextMediaType&&(view.removeEventListener("viewbeforehide",onViewHideStopPlayback),Emby.Page.back())}function bindToPlayer(player){player!==currentPlayer&&(releaseCurrentPlayer(),currentPlayer=player,player&&(playbackManager.getPlayerState(player).then(function(state){onStateChanged.call(player,{type:"init"},state)}),events.on(player,"playbackstart",onPlaybackStart),events.on(player,"playbackstop",onPlaybackStopped),events.on(player,"volumechange",onVolumeChanged),events.on(player,"pause",onPlayPauseStateChanged),events.on(player,"playing",onPlayPauseStateChanged),events.on(player,"timeupdate",onTimeUpdate),events.on(player,"fullscreenchange",updateFullscreenIcon)))}function releaseCurrentPlayer(){var player=currentPlayer;player&&(events.off(player,"playbackstart",onPlaybackStart),events.off(player,"playbackstop",onPlaybackStopped),events.off(player,"volumechange",onVolumeChanged),events.off(player,"pause",onPlayPauseStateChanged),events.off(player,"playing",onPlayPauseStateChanged),events.off(player,"timeupdate",onTimeUpdate),events.off(player,"fullscreenchange",updateFullscreenIcon),currentPlayer=null)}function onTimeUpdate(e){if(isEnabled){var now=(new Date).getTime();if(!(now-lastUpdateTime<700)){lastUpdateTime=now;var player=this;currentRuntimeTicks=playbackManager.duration(player),updateTimeDisplay(playbackManager.currentTime(player),currentRuntimeTicks)}}}function updatePlayPauseState(isPaused){isPaused?view.querySelector(".btnPause i").innerHTML="":view.querySelector(".btnPause i").innerHTML=""}function updatePlayerStateInternal(event,state){var playerInfo=playbackManager.getPlayerInfo(),playState=state.PlayState||{};updatePlayPauseState(playState.IsPaused);var supportedCommands=playerInfo.supportedCommands;currentPlayerSupportedCommands=supportedCommands,updatePlayerVolumeState(playState.IsMuted,playState.VolumeLevel),nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging&&(nowPlayingPositionSlider.disabled=!playState.CanSeek),btnFastForward.disabled=!playState.CanSeek,btnRewind.disabled=!playState.CanSeek;var nowPlayingItem=state.NowPlayingItem||{};updateTimeDisplay(playState.PositionTicks,nowPlayingItem.RunTimeTicks),updateNowPlayingInfo(state),state.MediaSource&&state.MediaSource.SupportsTranscoding&&supportedCommands.indexOf("SetMaxStreamingBitrate")!==-1?view.querySelector(".btnSettings").classList.remove("hide"):view.querySelector(".btnSettings").classList.add("hide"),supportedCommands.indexOf("ToggleFullscreen")===-1?view.querySelector(".btnFullscreen").classList.add("hide"):view.querySelector(".btnFullscreen").classList.remove("hide"),supportedCommands.indexOf("PictureInPicture")===-1?view.querySelector(".btnPip").classList.add("hide"):view.querySelector(".btnPip").classList.remove("hide"),updateFullscreenIcon()}function updateTimeDisplay(positionTicks,runtimeTicks){if(nowPlayingPositionSlider&&!nowPlayingPositionSlider.dragging){if(runtimeTicks){var pct=positionTicks/runtimeTicks;pct*=100,nowPlayingPositionSlider.value=pct}else nowPlayingPositionSlider.value=0;runtimeTicks&&null!=positionTicks?endsAtText.innerHTML="  -  "+mediaInfo.getEndsAtFromPosition(runtimeTicks,positionTicks,!0):endsAtText.innerHTML=""}updateTimeText(nowPlayingPositionText,positionTicks),updateTimeText(nowPlayingDurationText,runtimeTicks,!0)}function updatePlayerVolumeState(isMuted,volumeLevel){var supportedCommands=currentPlayerSupportedCommands,showMuteButton=!0,showVolumeSlider=!0;supportedCommands.indexOf("Mute")===-1&&(showMuteButton=!1),supportedCommands.indexOf("SetVolume")===-1&&(showVolumeSlider=!1),currentPlayer.isLocalPlayer&&appHost.supports("physicalvolumecontrol")&&(showMuteButton=!1,showVolumeSlider=!1),isMuted?(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Unmute")),view.querySelector(".buttonMute i").innerHTML=""):(view.querySelector(".buttonMute").setAttribute("title",globalize.translate("Mute")),view.querySelector(".buttonMute i").innerHTML=""),showMuteButton?view.querySelector(".buttonMute").classList.remove("hide"):view.querySelector(".buttonMute").classList.add("hide"),nowPlayingVolumeSlider&&(showVolumeSlider?nowPlayingVolumeSliderContainer.classList.remove("hide"):nowPlayingVolumeSliderContainer.classList.add("hide"),nowPlayingVolumeSlider.dragging||(nowPlayingVolumeSlider.value=volumeLevel||0))}function updatePlaylist(player){var btnPreviousTrack=view.querySelector(".btnPreviousTrack"),btnNextTrack=view.querySelector(".btnNextTrack");btnPreviousTrack.classList.remove("hide"),btnNextTrack.classList.remove("hide"),btnNextTrack.disabled=!1,btnPreviousTrack.disabled=!1}function updateTimeText(elem,ticks,divider){if(null==ticks)return void(elem.innerHTML="");var html=datetime.getDisplayRunningTime(ticks);divider&&(html=" / "+html),elem.innerHTML=html}function onSettingsButtonClick(e){var btn=this;require(["playerSettingsMenu"],function(playerSettingsMenu){playerSettingsMenu.show({mediaType:"Video",player:currentPlayer,positionTo:btn})})}function showAudioTrackSelection(){var player=currentPlayer,audioTracks=playbackManager.audioTracks(player),currentIndex=playbackManager.getAudioStreamIndex(player),menuItems=audioTracks.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({items:menuItems,title:globalize.translate("Audio"),positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setAudioStreamIndex(index,currentPlayer)})})}function showSubtitleTrackSelection(){var player=currentPlayer,streams=playbackManager.subtitleTracks(player),currentIndex=playbackManager.getSubtitleStreamIndex(player);null==currentIndex&&(currentIndex=-1),streams.unshift({Index:-1,DisplayTitle:globalize.translate("Off")});var menuItems=streams.map(function(stream){var opt={name:stream.DisplayTitle,id:stream.Index};return stream.Index===currentIndex&&(opt.selected=!0),opt}),positionTo=this;require(["actionsheet"],function(actionsheet){actionsheet.show({title:globalize.translate("Subtitles"),items:menuItems,positionTo:positionTo}).then(function(id){var index=parseInt(id);index!==currentIndex&&playbackManager.setSubtitleStreamIndex(index,currentPlayer)})})}function onWindowKeyDown(e){32!==e.keyCode||isOsdOpen()||(playbackManager.playPause(currentPlayer),showOsd())}function getImgUrl(item,chapter,index,maxWidth,apiClient){return chapter.ImageTag?apiClient.getScaledImageUrl(item.Id,{maxWidth:maxWidth,tag:chapter.ImageTag,type:"Chapter",index:index}):null}function getChapterBubbleHtml(apiClient,item,chapters,positionTicks){for(var chapter,index=-1,i=0,length=chapters.length;i=currentChapter.StartPositionTicks&&(chapter=currentChapter,index=i)}if(!chapter)return null;var src=getImgUrl(item,chapter,index,400,apiClient);if(src){var html='
';return html+='',html+='
',html+='
',html+=chapter.Name,html+="
",html+='

',html+=datetime.getDisplayRunningTime(positionTicks),html+="

",html+="
",html+="
"}return null}function onViewHideStopPlayback(){if(playbackManager.isPlayingVideo()){var player=currentPlayer;view.removeEventListener("viewbeforehide",onViewHideStopPlayback),releaseCurrentPlayer(),playbackManager.stop(player)}}function enableStopOnBack(enabled){view.removeEventListener("viewbeforehide",onViewHideStopPlayback),enabled&&playbackManager.isPlayingVideo(currentPlayer)&&view.addEventListener("viewbeforehide",onViewHideStopPlayback)}var currentPlayer,isEnabled,currentItem,hideTimeout,lastMouseMoveData,currentPlayerSupportedCommands=[],currentRuntimeTicks=0,lastUpdateTime=0,nowPlayingVolumeSlider=view.querySelector(".osdVolumeSlider"),nowPlayingVolumeSliderContainer=view.querySelector(".osdVolumeSliderContainer"),nowPlayingPositionSlider=view.querySelector(".osdPositionSlider"),nowPlayingPositionText=view.querySelector(".osdPositionText"),nowPlayingDurationText=view.querySelector(".osdDurationText"),endsAtText=view.querySelector(".endsAtText"),btnRewind=view.querySelector(".btnRewind"),btnFastForward=view.querySelector(".btnFastForward"),transitionEndEventName=dom.whichTransitionEvent(),headerElement=document.querySelector(".skinHeader"),osdBottomElement=document.querySelector(".videoOsdBottom"),_osdOpen=!0;view.addEventListener("viewbeforeshow",function(e){headerElement.classList.add("osdHeader"),Emby.Page.setTransparency("full")}),view.addEventListener("viewshow",function(e){events.on(playbackManager,"playerchange",onPlayerChange),bindToPlayer(playbackManager.getCurrentPlayer()),dom.addEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.add("autoScrollY"),showOsd(),inputManager.on(window,onInputCommand),dom.addEventListener(window,"keydown",onWindowKeyDown,{passive:!0})}),view.addEventListener("viewbeforehide",function(){dom.removeEventListener(window,"keydown",onWindowKeyDown,{passive:!0}),stopHideTimer(),headerElement.classList.remove("osdHeader"),headerElement.classList.remove("osdHeader-hidden"),dom.removeEventListener(document,"mousemove",onMouseMove,{passive:!0}),document.body.classList.remove("autoScrollY"),inputManager.off(window,onInputCommand),events.off(playbackManager,"playerchange",onPlayerChange),releaseCurrentPlayer()}),appHost.supports("remotecontrol")&&!layoutManager.tv&&view.querySelector(".btnCast").classList.remove("hide"),view.querySelector(".btnCast").addEventListener("click",function(){var btn=this;require(["playerSelectionMenu"],function(playerSelectionMenu){playerSelectionMenu.show(btn)})}),view.querySelector(".btnFullscreen").addEventListener("click",function(){playbackManager.toggleFullscreen(currentPlayer)}),view.querySelector(".btnPip").addEventListener("click",function(){playbackManager.togglePictureInPicture(currentPlayer)}),view.querySelector(".btnSettings").addEventListener("click",onSettingsButtonClick),view.addEventListener("viewhide",function(){headerElement.classList.remove("hide")}),view.querySelector(".pageContainer").addEventListener("click",function(){browser.touch||playbackManager.playPause(currentPlayer),showOsd()}),view.querySelector(".buttonMute").addEventListener("click",function(){playbackManager.toggleMute(currentPlayer)}),nowPlayingVolumeSlider.addEventListener("change",function(){playbackManager.setVolume(this.value,currentPlayer)}),nowPlayingPositionSlider.addEventListener("change",function(){if(currentPlayer){var newPercent=parseFloat(this.value);playbackManager.seekPercent(newPercent,currentPlayer)}}),nowPlayingPositionSlider.getBubbleHtml=function(value){if(showOsd(),!currentRuntimeTicks)return"--:--";var ticks=currentRuntimeTicks;ticks/=100,ticks*=value;var item=currentItem;if(item&&item.Chapters&&item.Chapters.length&&item.Chapters[0].ImageTag){var html=getChapterBubbleHtml(connectionManager.getApiClient(item.ServerId),item,item.Chapters,ticks);if(html)return html}return'

'+datetime.getDisplayRunningTime(ticks)+"

"},view.querySelector(".btnPreviousTrack").addEventListener("click",function(){playbackManager.previousChapter(currentPlayer)}),view.querySelector(".btnPause").addEventListener("click",function(){playbackManager.playPause(currentPlayer)}),view.querySelector(".btnNextTrack").addEventListener("click",function(){playbackManager.nextChapter(currentPlayer)}),btnRewind.addEventListener("click",function(){playbackManager.rewind(currentPlayer)}),btnFastForward.addEventListener("click",function(){playbackManager.fastForward(currentPlayer)}),view.querySelector(".btnAudio").addEventListener("click",showAudioTrackSelection),view.querySelector(".btnSubtitles").addEventListener("click",showSubtitleTrackSelection)}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardagreement.js b/dashboard-ui/scripts/wizardagreement.js index 9e39c04826..ebc72636c7 100644 --- a/dashboard-ui/scripts/wizardagreement.js +++ b/dashboard-ui/scripts/wizardagreement.js @@ -1,26 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function onSubmit() { - - var page = $(this).parents('.page')[0]; - - if (page.querySelector('.chkAccept').checked) { - Dashboard.navigate('wizardfinish.html'); - } else { - - Dashboard.alert({ - message: Globalize.translate('MessagePleaseAcceptTermsOfServiceBeforeContinuing'), - title: '' - }); - } - - return false; - } - - $(document).on('pageinit', '#wizardAgreementPage', function () { - - $('.wizardAgreementForm').off('submit', onSubmit).on('submit', onSubmit); - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function onSubmit(){var page=$(this).parents(".page")[0];return page.querySelector(".chkAccept").checked?Dashboard.navigate("wizardfinish.html"):Dashboard.alert({message:Globalize.translate("MessagePleaseAcceptTermsOfServiceBeforeContinuing"),title:""}),!1}$(document).on("pageinit","#wizardAgreementPage",function(){$(".wizardAgreementForm").off("submit",onSubmit).on("submit",onSubmit)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardcontroller.js b/dashboard-ui/scripts/wizardcontroller.js index 3f2e5c73cb..7ec6969576 100644 --- a/dashboard-ui/scripts/wizardcontroller.js +++ b/dashboard-ui/scripts/wizardcontroller.js @@ -1,21 +1 @@ -define([], function () { - 'use strict'; - - function navigateToComponents() { - var apiClient = ApiClient; - - apiClient.getJSON(apiClient.getUrl('Startup/Info')).then(function (info) { - - if (info.HasMediaEncoder) { - Dashboard.navigate('wizardagreement.html'); - - } else { - Dashboard.navigate('wizardcomponents.html'); - } - }); - } - - return { - navigateToComponents: navigateToComponents - }; -}); \ No newline at end of file +define([],function(){"use strict";function navigateToComponents(){var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Info")).then(function(info){info.HasMediaEncoder?Dashboard.navigate("wizardagreement.html"):Dashboard.navigate("wizardcomponents.html")})}return{navigateToComponents:navigateToComponents}}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardlivetvguide.js b/dashboard-ui/scripts/wizardlivetvguide.js index 6081f8972e..23d2fd68e8 100644 --- a/dashboard-ui/scripts/wizardlivetvguide.js +++ b/dashboard-ui/scripts/wizardlivetvguide.js @@ -1,93 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - var guideController; - - function init(page, type) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - apiClient.getJSON(apiClient.getUrl('Startup/Configuration')).then(function (config) { - - var providerId = null; - - if ((config.LiveTvGuideProviderType || '').toLowerCase() == type.toLowerCase()) { - if (config.LiveTvGuideProviderId) { - providerId = config.LiveTvGuideProviderId; - } - } - - var url = 'components/tvproviders/' + type.toLowerCase() + '.js'; - - require([url], function (factory) { - - var instance = new factory(page, providerId, { - showCancelButton: false, - showSubmitButton: false, - showConfirmation: false - }); - - Dashboard.hideLoadingMsg(); - instance.init(); - guideController = instance; - - Events.on(guideController, 'submitted', skip); - }); - }); - } - - function loadTemplate(page, type) { - - guideController = null; - - ApiClient.ajax({ - - type: 'GET', - url: 'components/tvproviders/' + type.toLowerCase() + '.template.html' - - }).then(function (html) { - - var elem = page.querySelector('.providerTemplate'); - elem.innerHTML = Globalize.translateDocument(html); - - init(page, type); - }); - } - - function skip() { - require(['scripts/wizardcontroller'], function (wizardcontroller) { - wizardcontroller.navigateToComponents(); - }); - } - - function next() { - guideController.submit(); - } - - function reload(page) { - - $('#selectType', page).trigger('change'); - } - - $(document).on('pageinit', "#wizardGuidePage", function () { - - var page = this; - - $('#selectType', page).on('change', function () { - - loadTemplate(page, this.value); - }); - - $('.btnSkip', page).on('click', skip); - $('.btnNext', page).on('click', next); - - }).on('pageshow', "#wizardGuidePage", function () { - - var page = this; - - reload(page); - }); - -}); +define(["jQuery"],function($){"use strict";function init(page,type){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Configuration")).then(function(config){var providerId=null;(config.LiveTvGuideProviderType||"").toLowerCase()==type.toLowerCase()&&config.LiveTvGuideProviderId&&(providerId=config.LiveTvGuideProviderId);var url="components/tvproviders/"+type.toLowerCase()+".js";require([url],function(factory){var instance=new factory(page,providerId,{showCancelButton:!1,showSubmitButton:!1,showConfirmation:!1});Dashboard.hideLoadingMsg(),instance.init(),guideController=instance,Events.on(guideController,"submitted",skip)})})}function loadTemplate(page,type){guideController=null,ApiClient.ajax({type:"GET",url:"components/tvproviders/"+type.toLowerCase()+".template.html"}).then(function(html){var elem=page.querySelector(".providerTemplate");elem.innerHTML=Globalize.translateDocument(html),init(page,type)})}function skip(){require(["scripts/wizardcontroller"],function(wizardcontroller){wizardcontroller.navigateToComponents()})}function next(){guideController.submit()}function reload(page){$("#selectType",page).trigger("change")}var guideController;$(document).on("pageinit","#wizardGuidePage",function(){var page=this;$("#selectType",page).on("change",function(){loadTemplate(page,this.value)}),$(".btnSkip",page).on("click",skip),$(".btnNext",page).on("click",next)}).on("pageshow","#wizardGuidePage",function(){var page=this;reload(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardlivetvtuner.js b/dashboard-ui/scripts/wizardlivetvtuner.js index 1e654deef5..07d3905d98 100644 --- a/dashboard-ui/scripts/wizardlivetvtuner.js +++ b/dashboard-ui/scripts/wizardlivetvtuner.js @@ -1,92 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function save(page) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - // After saving chapter task, now save server config - apiClient.getJSON(apiClient.getUrl('Startup/Configuration')).then(function (config) { - - config.LiveTvTunerType = $('#selectTunerType', page).val(); - config.LiveTvTunerPath = $('.txtDevicePath', page).val(); - - apiClient.ajax({ - - type: 'POST', - data: config, - url: apiClient.getUrl('Startup/Configuration') - - }).then(function () { - - Dashboard.hideLoadingMsg(); - navigateToNextPage(config); - - }, function () { - - Dashboard.hideLoadingMsg(); - Dashboard.alert({ - message: Globalize.translate('ErrorSavingTvProvider') - }); - - }); - }); - - } - - function reload(page) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - apiClient.getJSON(apiClient.getUrl('Startup/Configuration')).then(function (config) { - - $('#selectTunerType', page).val(config.LiveTvTunerType || 'hdhomerun'); - page.querySelector('.txtDevicePath').value = config.LiveTvTunerPath || ''; - - Dashboard.hideLoadingMsg(); - }); - } - - function navigateToNextPage(config) { - - if (config.LiveTvTunerPath && config.LiveTvTunerType) { - Dashboard.navigate('wizardlivetvguide.html'); - } else { - skip(); - } - } - - function skip() { - require(['scripts/wizardcontroller'], function (wizardcontroller) { - wizardcontroller.navigateToComponents(); - }); - } - - function onSubmit() { - var form = this; - - save(form); - - return false; - } - - $(document).on('pageinit', "#wizardTunerPage", function () { - - var page = this; - - $('form', page).off('submit', onSubmit).on('submit', onSubmit); - - $('.btnSkip', page).on('click', skip); - - }).on('pageshow', "#wizardTunerPage", function () { - - var page = this; - - reload(page); - }); - -}); +define(["jQuery"],function($){"use strict";function save(page){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Configuration")).then(function(config){config.LiveTvTunerType=$("#selectTunerType",page).val(),config.LiveTvTunerPath=$(".txtDevicePath",page).val(),apiClient.ajax({type:"POST",data:config,url:apiClient.getUrl("Startup/Configuration")}).then(function(){Dashboard.hideLoadingMsg(),navigateToNextPage(config)},function(){Dashboard.hideLoadingMsg(),Dashboard.alert({message:Globalize.translate("ErrorSavingTvProvider")})})})}function reload(page){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Configuration")).then(function(config){$("#selectTunerType",page).val(config.LiveTvTunerType||"hdhomerun"),page.querySelector(".txtDevicePath").value=config.LiveTvTunerPath||"",Dashboard.hideLoadingMsg()})}function navigateToNextPage(config){config.LiveTvTunerPath&&config.LiveTvTunerType?Dashboard.navigate("wizardlivetvguide.html"):skip()}function skip(){require(["scripts/wizardcontroller"],function(wizardcontroller){wizardcontroller.navigateToComponents()})}function onSubmit(){var form=this;return save(form),!1}$(document).on("pageinit","#wizardTunerPage",function(){var page=this;$("form",page).off("submit",onSubmit).on("submit",onSubmit),$(".btnSkip",page).on("click",skip)}).on("pageshow","#wizardTunerPage",function(){var page=this;reload(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardsettings.js b/dashboard-ui/scripts/wizardsettings.js index 51ab666881..2d94d09815 100644 --- a/dashboard-ui/scripts/wizardsettings.js +++ b/dashboard-ui/scripts/wizardsettings.js @@ -1,117 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function save(page) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - // After saving chapter task, now save server config - apiClient.getJSON(apiClient.getUrl('Startup/Configuration')).then(function (config) { - - config.PreferredMetadataLanguage = $('#selectLanguage', page).val(); - config.MetadataCountryCode = $('#selectCountry', page).val(); - - apiClient.ajax({ - - type: 'POST', - data: config, - url: apiClient.getUrl('Startup/Configuration') - - }).then(function () { - - navigateToNextPage(); - - }); - }); - - } - - function populateLanguages(select, languages) { - - var html = ""; - - html += ""; - - for (var i = 0, length = languages.length; i < length; i++) { - - var culture = languages[i]; - - html += ""; - } - - select.innerHTML = html; - } - - function populateCountries (select, allCountries) { - - var html = ""; - - html += ""; - - for (var i = 0, length = allCountries.length; i < length; i++) { - - var culture = allCountries[i]; - - html += ""; - } - - select.innerHTML = html; - } - - function reloadData(page, config, cultures, countries) { - - populateLanguages(page.querySelector('#selectLanguage'), cultures); - populateCountries(page.querySelector('#selectCountry'), countries); - - $('#selectLanguage', page).val(config.PreferredMetadataLanguage); - $('#selectCountry', page).val(config.MetadataCountryCode); - - Dashboard.hideLoadingMsg(); - } - - function reload(page) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - var promise1 = apiClient.getJSON(apiClient.getUrl('Startup/Configuration')); - var promise2 = apiClient.getCultures(); - var promise3 = apiClient.getCountries(); - - Promise.all([promise1, promise2, promise3]).then(function (responses) { - - reloadData(page, responses[0], responses[1], responses[2]); - - }); - } - - function navigateToNextPage() { - - Dashboard.navigate('wizardlivetvtuner.html'); - } - - function onSubmit() { - var form = this; - - save(form); - - return false; - } - - $(document).on('pageinit', "#wizardSettingsPage", function () { - - var page = this; - - $('.wizardSettingsForm', page).off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#wizardSettingsPage", function () { - - var page = this; - - reload(page); - }); - -}); +define(["jQuery"],function($){"use strict";function save(page){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Configuration")).then(function(config){config.PreferredMetadataLanguage=$("#selectLanguage",page).val(),config.MetadataCountryCode=$("#selectCountry",page).val(),apiClient.ajax({type:"POST",data:config,url:apiClient.getUrl("Startup/Configuration")}).then(function(){navigateToNextPage()})})}function populateLanguages(select,languages){var html="";html+="";for(var i=0,length=languages.length;i"+culture.DisplayName+""}select.innerHTML=html}function populateCountries(select,allCountries){var html="";html+="";for(var i=0,length=allCountries.length;i"+culture.DisplayName+""}select.innerHTML=html}function reloadData(page,config,cultures,countries){populateLanguages(page.querySelector("#selectLanguage"),cultures),populateCountries(page.querySelector("#selectCountry"),countries),$("#selectLanguage",page).val(config.PreferredMetadataLanguage),$("#selectCountry",page).val(config.MetadataCountryCode),Dashboard.hideLoadingMsg()}function reload(page){Dashboard.showLoadingMsg();var apiClient=ApiClient,promise1=apiClient.getJSON(apiClient.getUrl("Startup/Configuration")),promise2=apiClient.getCultures(),promise3=apiClient.getCountries();Promise.all([promise1,promise2,promise3]).then(function(responses){reloadData(page,responses[0],responses[1],responses[2])})}function navigateToNextPage(){Dashboard.navigate("wizardlivetvtuner.html")}function onSubmit(){var form=this;return save(form),!1}$(document).on("pageinit","#wizardSettingsPage",function(){var page=this;$(".wizardSettingsForm",page).off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#wizardSettingsPage",function(){var page=this;reload(page)})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizardstartpage.js b/dashboard-ui/scripts/wizardstartpage.js index e434c602aa..c5e7081dbf 100644 --- a/dashboard-ui/scripts/wizardstartpage.js +++ b/dashboard-ui/scripts/wizardstartpage.js @@ -1,71 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function loadPage(page, config, languageOptions) { - - $('#selectLocalizationLanguage', page).html(languageOptions.map(function (l) { - - return ''; - - })).val(config.UICulture); - - Dashboard.hideLoadingMsg(); - } - - function save(page) { - - Dashboard.showLoadingMsg(); - - var apiClient = ApiClient; - - apiClient.getJSON(apiClient.getUrl('Startup/Configuration')).then(function (config) { - - config.UICulture = $('#selectLocalizationLanguage', page).val(); - - apiClient.ajax({ - - type: 'POST', - data: config, - url: apiClient.getUrl('Startup/Configuration') - - }).then(function () { - - Dashboard.navigate('wizarduser.html'); - - }); - }); - - } - - function onSubmit() { - save($(this).parents('.page')); - - return false; - } - - $(document).on('pageinit', "#wizardStartPage", function () { - - $('.wizardStartForm').off('submit', onSubmit).on('submit', onSubmit); - - window.ConnectionManager.clearData(); - - - }).on('pageshow', "#wizardStartPage", function () { - - Dashboard.showLoadingMsg(); - var page = this; - - var apiClient = ApiClient; - - var promise1 = apiClient.getJSON(apiClient.getUrl('Startup/Configuration')); - - var promise2 = apiClient.getJSON(apiClient.getUrl("Localization/Options")); - - Promise.all([promise1, promise2]).then(function (responses) { - - loadPage(page, responses[0], responses[1]); - - }); - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function loadPage(page,config,languageOptions){$("#selectLocalizationLanguage",page).html(languageOptions.map(function(l){return'"})).val(config.UICulture),Dashboard.hideLoadingMsg()}function save(page){Dashboard.showLoadingMsg();var apiClient=ApiClient;apiClient.getJSON(apiClient.getUrl("Startup/Configuration")).then(function(config){config.UICulture=$("#selectLocalizationLanguage",page).val(),apiClient.ajax({type:"POST",data:config,url:apiClient.getUrl("Startup/Configuration")}).then(function(){Dashboard.navigate("wizarduser.html")})})}function onSubmit(){return save($(this).parents(".page")),!1}$(document).on("pageinit","#wizardStartPage",function(){$(".wizardStartForm").off("submit",onSubmit).on("submit",onSubmit),window.ConnectionManager.clearData()}).on("pageshow","#wizardStartPage",function(){Dashboard.showLoadingMsg();var page=this,apiClient=ApiClient,promise1=apiClient.getJSON(apiClient.getUrl("Startup/Configuration")),promise2=apiClient.getJSON(apiClient.getUrl("Localization/Options"));Promise.all([promise1,promise2]).then(function(responses){loadPage(page,responses[0],responses[1])})})}); \ No newline at end of file diff --git a/dashboard-ui/scripts/wizarduserpage.js b/dashboard-ui/scripts/wizarduserpage.js index f87b4781f2..0c8facfb52 100644 --- a/dashboard-ui/scripts/wizarduserpage.js +++ b/dashboard-ui/scripts/wizarduserpage.js @@ -1,104 +1 @@ -define(['jQuery'], function ($) { - 'use strict'; - - function getApiClient() { - return ApiClient; - } - - function onUpdateUserComplete(result) { - - Dashboard.hideLoadingMsg(); - - if (result.UserLinkResult) { - - var msgKey = result.UserLinkResult.IsPending ? 'MessagePendingEmbyAccountAdded' : 'MessageEmbyAccountAdded'; - - Dashboard.alert({ - message: Globalize.translate(msgKey), - title: Globalize.translate('HeaderEmbyAccountAdded'), - - callback: function () { - Dashboard.navigate('wizardlibrary.html'); - } - - }); - - } else { - Dashboard.navigate('wizardlibrary.html'); - } - } - - function submit(form) { - - Dashboard.showLoadingMsg(); - - var apiClient = getApiClient(); - - apiClient.ajax({ - - type: 'POST', - data: { - - Name: form.querySelector('#txtUsername').value, - ConnectUserName: form.querySelector('#txtConnectUserName').value - - }, - url: apiClient.getUrl('Startup/User'), - dataType: 'json' - - }).then(onUpdateUserComplete, function () { - - showEmbyConnectErrorMessage(form.querySelector('#txtConnectUserName').value); - }); - } - - function showEmbyConnectErrorMessage(username) { - - var msg; - - if (username) { - - msg = Globalize.translate('ErrorAddingEmbyConnectAccount1', 'https://emby.media/connect'); - msg += '

' + Globalize.translate('ErrorAddingEmbyConnectAccount2', 'apps@emby.media'); - - } else { - msg = Globalize.translate('DefaultErrorMessage'); - } - - Dashboard.alert({ - - message: msg - - }); - } - - function onSubmit() { - var form = this; - - submit(form); - - return false; - } - - $(document).on('pageinit', "#wizardUserPage", function () { - - $('.wizardUserForm').off('submit', onSubmit).on('submit', onSubmit); - - }).on('pageshow', "#wizardUserPage", function () { - - Dashboard.showLoadingMsg(); - - var page = this; - - var apiClient = getApiClient(); - - apiClient.getJSON(apiClient.getUrl('Startup/User')).then(function (user) { - - page.querySelector('#txtUsername').value = user.Name || ''; - page.querySelector('#txtConnectUserName').value = user.ConnectUserName || ''; - - Dashboard.hideLoadingMsg(); - }); - }); - -}); \ No newline at end of file +define(["jQuery"],function($){"use strict";function getApiClient(){return ApiClient}function onUpdateUserComplete(result){if(Dashboard.hideLoadingMsg(),result.UserLinkResult){var msgKey=result.UserLinkResult.IsPending?"MessagePendingEmbyAccountAdded":"MessageEmbyAccountAdded";Dashboard.alert({message:Globalize.translate(msgKey),title:Globalize.translate("HeaderEmbyAccountAdded"),callback:function(){Dashboard.navigate("wizardlibrary.html")}})}else Dashboard.navigate("wizardlibrary.html")}function submit(form){Dashboard.showLoadingMsg();var apiClient=getApiClient();apiClient.ajax({type:"POST",data:{Name:form.querySelector("#txtUsername").value,ConnectUserName:form.querySelector("#txtConnectUserName").value},url:apiClient.getUrl("Startup/User"),dataType:"json"}).then(onUpdateUserComplete,function(){showEmbyConnectErrorMessage(form.querySelector("#txtConnectUserName").value)})}function showEmbyConnectErrorMessage(username){var msg;username?(msg=Globalize.translate("ErrorAddingEmbyConnectAccount1",'https://emby.media/connect'),msg+="

"+Globalize.translate("ErrorAddingEmbyConnectAccount2","apps@emby.media")):msg=Globalize.translate("DefaultErrorMessage"),Dashboard.alert({message:msg})}function onSubmit(){var form=this;return submit(form),!1}$(document).on("pageinit","#wizardUserPage",function(){$(".wizardUserForm").off("submit",onSubmit).on("submit",onSubmit)}).on("pageshow","#wizardUserPage",function(){Dashboard.showLoadingMsg();var page=this,apiClient=getApiClient();apiClient.getJSON(apiClient.getUrl("Startup/User")).then(function(user){page.querySelector("#txtUsername").value=user.Name||"",page.querySelector("#txtConnectUserName").value=user.ConnectUserName||"",Dashboard.hideLoadingMsg()})})}); \ No newline at end of file diff --git a/dashboard-ui/themes/halloween/style.css b/dashboard-ui/themes/halloween/style.css index 9feb2f9458..ce0304c124 100644 --- a/dashboard-ui/themes/halloween/style.css +++ b/dashboard-ui/themes/halloween/style.css @@ -1,41 +1 @@ -.ui-body-b h1, .ui-body-b h2 { - color: #FF9100; -} - -.viewMenuBar, .halloweenInfoButton { - color: #FF9100 !important; -} - -.barsMenuButton { - color: #FF9100 !important; -} - -.libraryViewNav .ui-btn-active { - border-bottom-color: #FF9100 !important; - color: #FF9100 !important; -} - -.button-submit, .button-accent { - background: #FF9100 !important; -} - -.channelTimeslotHeader, .timeslotHeader { - background: #FF9100 !important; -} - -.channelTimeslotHeader { - border-right-color: #FF9100 !important; -} - -.emby-tab-button-active, .ui-body-b .emby-tab-button-active { - color: #FF9100 !important; - border-color: #FF9100 !important; -} - -.darkDrawer .sidebarLink.selectedSidebarLink, .darkDrawer .selectedMediaFolder { - color: #FF9100 !important; -} - -.visualCardBox-cardFooter { - color: #FF9100; -} \ No newline at end of file +.ui-body-b h1,.ui-body-b h2{color:#FF9100}.barsMenuButton,.darkDrawer .selectedMediaFolder,.darkDrawer .sidebarLink.selectedSidebarLink,.halloweenInfoButton,.libraryViewNav .ui-btn-active,.viewMenuBar{color:#FF9100!important}.libraryViewNav .ui-btn-active{border-bottom-color:#FF9100!important}.button-accent,.button-submit,.channelTimeslotHeader,.timeslotHeader{background:#FF9100!important}.channelTimeslotHeader{border-right-color:#FF9100!important}.emby-tab-button-active,.ui-body-b .emby-tab-button-active{color:#FF9100!important;border-color:#FF9100!important}.visualCardBox-cardFooter{color:#FF9100} \ No newline at end of file diff --git a/dashboard-ui/themes/halloween/theme.js b/dashboard-ui/themes/halloween/theme.js index 014954e81e..3fbcf0ae64 100644 --- a/dashboard-ui/themes/halloween/theme.js +++ b/dashboard-ui/themes/halloween/theme.js @@ -1,125 +1 @@ -define(['appSettings', 'backdrop', 'browser', 'globalize', 'require', 'paper-icon-button-light'], function (appSettings, backdrop, browser, globalize, require) { - 'use strict'; - - var lastSound = 0; - var iconCreated; - var destroyed; - var currentSound; - var cancelKey = 'cancelHalloween2015'; - var cancelValue = '6'; - - function onPageShow() { - var page = this; - - if (!destroyed) { - - if (appSettings.get(cancelKey) == cancelValue) { - - destroyed = true; - return; - } - - if (!browser.mobile) { - - require(['css!./style.css']); - - if (!page.classList.contains('itemDetailPage')) { - backdrop.setBackdrop('themes/halloween/bg.jpg'); - } - - if (lastSound == 0) { - playSound('http://github.com/MediaBrowser/Emby.Resources/raw/master/themes/halloween/monsterparadefade.mp3', .1); - } else if ((new Date().getTime() - lastSound) > 30000) { - playSound('http://github.com/MediaBrowser/Emby.Resources/raw/master/themes/halloween/howl.wav'); - } - - addIcon(); - } - } - } - - function addIcon() { - - if (iconCreated) { - return; - } - - iconCreated = true; - - var viewMenuSecondary = document.querySelector('.viewMenuSecondary'); - - if (viewMenuSecondary) { - - var html = ''; - - viewMenuSecondary.insertAdjacentHTML('afterbegin', html); - - viewMenuSecondary.querySelector('.halloweenInfoButton').addEventListener('click', onIconClick); - } - } - - function onIconClick() { - - require(['dialog'], function (dialog) { - dialog({ - - title: "Happy Halloween", - text: "Happy Halloween from the Emby Team. We hope your Halloween is spooktacular! Would you like to allow the Halloween theme to continue?", - - buttons: [ - { - id: 'yes', - name: globalize.translate('ButtonYes'), - type: 'submit' - }, - { - id: 'no', - name: globalize.translate('ButtonNo'), - type: 'cancel' - } - ] - - }).then(function (result) { - if (result == 'no') { - destroyTheme(); - } - }); - }); - } - - function destroyTheme() { - - destroyed = true; - - var halloweenInfoButton = document.querySelector('.halloweenInfoButton'); - if (halloweenInfoButton) { - halloweenInfoButton.parentNode.removeChild(halloweenInfoButton); - } - - if (currentSound) { - currentSound.stop(); - } - - backdrop.clear(); - appSettings.set(cancelKey, cancelValue); - window.location.reload(true); - } - - pageClassOn('pageshow', "libraryPage", onPageShow); - - function playSound(path, volume) { - - require(['howler'], function (howler) { - - var sound = new Howl({ - urls: [path], - volume: volume || .3 - }); - - sound.play(); - currentSound = sound; - lastSound = new Date().getTime(); - }); - } - -}); \ No newline at end of file +define(["appSettings","backdrop","browser","globalize","require","paper-icon-button-light"],function(appSettings,backdrop,browser,globalize,require){"use strict";function onPageShow(){var page=this;if(!destroyed){if(appSettings.get(cancelKey)==cancelValue)return void(destroyed=!0);browser.mobile||(require(["css!./style.css"]),page.classList.contains("itemDetailPage")||backdrop.setBackdrop("themes/halloween/bg.jpg"),0==lastSound?playSound("http://github.com/MediaBrowser/Emby.Resources/raw/master/themes/halloween/monsterparadefade.mp3",.1):(new Date).getTime()-lastSound>3e4&&playSound("http://github.com/MediaBrowser/Emby.Resources/raw/master/themes/halloween/howl.wav"),addIcon())}}function addIcon(){if(!iconCreated){iconCreated=!0;var viewMenuSecondary=document.querySelector(".viewMenuSecondary");if(viewMenuSecondary){var html='';viewMenuSecondary.insertAdjacentHTML("afterbegin",html),viewMenuSecondary.querySelector(".halloweenInfoButton").addEventListener("click",onIconClick)}}}function onIconClick(){require(["dialog"],function(dialog){dialog({title:"Happy Halloween",text:"Happy Halloween from the Emby Team. We hope your Halloween is spooktacular! Would you like to allow the Halloween theme to continue?",buttons:[{id:"yes",name:globalize.translate("ButtonYes"),type:"submit"},{id:"no",name:globalize.translate("ButtonNo"),type:"cancel"}]}).then(function(result){"no"==result&&destroyTheme()})})}function destroyTheme(){destroyed=!0;var halloweenInfoButton=document.querySelector(".halloweenInfoButton");halloweenInfoButton&&halloweenInfoButton.parentNode.removeChild(halloweenInfoButton),currentSound&¤tSound.stop(),backdrop.clear(),appSettings.set(cancelKey,cancelValue),window.location.reload(!0)}function playSound(path,volume){require(["howler"],function(howler){var sound=new Howl({urls:[path],volume:volume||.3});sound.play(),currentSound=sound,lastSound=(new Date).getTime()})}var iconCreated,destroyed,currentSound,lastSound=0,cancelKey="cancelHalloween2015",cancelValue="6";pageClassOn("pageshow","libraryPage",onPageShow)}); \ No newline at end of file diff --git a/dashboard-ui/themes/holiday/style.css b/dashboard-ui/themes/holiday/style.css index 23dd540588..fb5ce6261f 100644 --- a/dashboard-ui/themes/holiday/style.css +++ b/dashboard-ui/themes/holiday/style.css @@ -1,65 +1 @@ -.background-theme-b .backgroundContainer.withBackdrop { - background: rgba(6, 6, 6, .86) !important; -} - -.ui-body-b h1, .ui-body-b h2 { - color: #E53A35; -} - -.holidayInfoButton { - color: #E53A35 !important; -} - -.libraryViewNav .ui-btn-active { - border-bottom-color: #AC3326 !important; - color: #AC3326 !important; -} - -.channelTimeslotHeader, .timeslotHeader { - background: #cc3333 !important; -} - -.channelTimeslotHeader { - border-right-color: #cc3333 !important; -} - -.playedIndicator { - background-color: #cc3333 !important; -} - -.darkDrawer .sidebarLink:hover { - background: #AC3326; -} - -.darkDrawer .sidebarLink.selectedSidebarLink, .darkDrawer .selectedMediaFolder { - background: #AC3326 !important; -} - -#snowflakeContainer { - position: absolute; - left: 0px; - top: 0px; - pointer-events: none; -} - -.snowflake { - padding-left: 15px; - font-family: Cambria, Georgia, serif; - font-size: 14px; - line-height: 24px; - position: fixed; - color: #FFFFFF; - user-select: none; - z-index: 1000; -} - - .snowflake:hover { - cursor: default; - } - -.christmas .mainDrawer { - background-image: url(https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/drawer.jpg); - background-size: cover; - background-position: 60% center; - background-repeat: no-repeat; -} +.background-theme-b .backgroundContainer.withBackdrop{background:rgba(6,6,6,.86)!important}.ui-body-b h1,.ui-body-b h2{color:#E53A35}.holidayInfoButton{color:#E53A35!important}.libraryViewNav .ui-btn-active{border-bottom-color:#AC3326!important;color:#AC3326!important}.channelTimeslotHeader,.timeslotHeader{background:#c33!important}.channelTimeslotHeader{border-right-color:#c33!important}.playedIndicator{background-color:#c33!important}.darkDrawer .sidebarLink:hover{background:#AC3326}.darkDrawer .selectedMediaFolder,.darkDrawer .sidebarLink.selectedSidebarLink{background:#AC3326!important}#snowflakeContainer{position:absolute;left:0;top:0;pointer-events:none}.snowflake{padding-left:15px;font-family:Cambria,Georgia,serif;font-size:14px;line-height:24px;position:fixed;color:#FFF;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;z-index:1000}.snowflake:hover{cursor:default}.christmas .mainDrawer{background-image:url(https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/drawer.jpg);-webkit-background-size:cover;background-size:cover;background-position:60% center;background-repeat:no-repeat} \ No newline at end of file diff --git a/dashboard-ui/themes/holiday/theme.js b/dashboard-ui/themes/holiday/theme.js index 6b729054e3..30004e1116 100644 --- a/dashboard-ui/themes/holiday/theme.js +++ b/dashboard-ui/themes/holiday/theme.js @@ -1,409 +1 @@ -define(['appSettings', 'backdrop', 'browser', 'globalize', 'require', 'events', 'paper-icon-button-light'], function (appSettings, backdrop, browser, globalize, require, events) { - 'use strict'; - - var lastSound = 0; - var iconCreated; - var destroyed; - var currentSound; - - function onPageShow() { - - if (!browser.mobile) { - - if (getHolidayTheme() == 'off') { - return; - } - - var page = this; - - require(['css!./style.css']); - - if (!page.classList.contains('itemDetailPage')) { - setBackdrop(page); - } - - playThemeMusic(); - - addSnowflakes(); - - addIcon(); - - setBodyClass(); - } - } - - function playThemeMusic() { - - if (getHolidayTheme() == 'off') { - return; - } - - if (lastSound == 0) { - playSound('https://github.com/MediaBrowser/Emby.Resources/raw/master/themes/holiday/christmas.wav', .1); - } else if ((new Date().getTime() - lastSound) > 30000) { - playSound('https://github.com/MediaBrowser/Emby.Resources/raw/master/themes/holiday/sleighbells.wav', .25); - } - } - - function destroyTheme() { - - document.documentElement.classList.remove('christmas'); - stopSnowflakes(); - - if (currentSound) { - currentSound.stop(); - } - - var holidayInfoButton = document.querySelector('.holidayInfoButton'); - if (holidayInfoButton) { - holidayInfoButton.parentNode.removeChild(holidayInfoButton); - } - - backdrop.clear(); - window.location.reload(true); - } - - var snowFlakesInitialized; - function addSnowflakes() { - - if (!snowFlakesInitialized) { - snowFlakesInitialized = true; - document.body.insertAdjacentHTML('beforeend', '

*

'); - generateSnowflakes(); - events.on(MediaController, 'beforeplaybackstart', onPlaybackStart); - } - } - - function onPlaybackStart() { - - if (currentSound) { - currentSound.stop(); - } - - stopSnowflakes(); - } - - function setBackdrop(page) { - - if (!page.classList.contains('itemDetailPage')) { - - if (getHolidayTheme() == 'christmas') { - backdrop.setBackdrop('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/bgc.jpg'); - } else { - backdrop.setBackdrop('https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/bg.jpg'); - } - } - } - - var holidayThemeKey = 'holidaytheme9'; - function getHolidayTheme() { - return appSettings.get(holidayThemeKey); - } - - function setHolidayTheme(value) { - appSettings.set(holidayThemeKey, value); - setBodyClass(); - playThemeMusic(); - } - - function setBodyClass() { - if (getHolidayTheme() == 'christmas') { - document.documentElement.classList.add('christmas'); - } else { - document.documentElement.classList.remove('christmas'); - } - } - - function onIconClick(e) { - - // todo: switch this to action sheet - - var items = []; - - var current = getHolidayTheme(); - - items.push({ - name: 'None', - id: 'none', - ironIcon: current == 'off' ? 'check' : null - }); - items.push({ - name: 'Joy!', - id: 'joy', - ironIcon: current != 'off' && current != 'christmas' ? 'check' : null - }); - - items.push({ - name: 'Christmas', - id: 'christmas', - ironIcon: current == 'christmas' ? 'check' : null - }); - - require(['actionsheet'], function (actionsheet) { - - actionsheet.show({ - title: 'Happy holidays from the Emby team! Select your holiday theme:', - items: items, - callback: function (id) { - - switch (id) { - - case 'none': - setHolidayTheme('off'); - destroyTheme(); - break; - case 'joy': - setHolidayTheme(''); - setBackdrop($.mobile.activePage); - break; - case 'christmas': - setHolidayTheme('christmas'); - setBackdrop($.mobile.activePage); - break; - default: - break; - } - } - }); - - }); - } - - function addIcon() { - - if (iconCreated) { - return; - } - - iconCreated = true; - - var viewMenuSecondary = document.querySelector('.viewMenuSecondary'); - - if (viewMenuSecondary) { - - var html = ''; - - viewMenuSecondary.insertAdjacentHTML('afterbegin', html); - - viewMenuSecondary.querySelector('.holidayInfoButton').addEventListener('click', onIconClick); - } - } - - pageClassOn('pageshow', "libraryPage", onPageShow); - - function playSound(path, volume) { - - require(['howler'], function (howler) { - - var sound = new Howl({ - urls: [path], - volume: volume || .3 - }); - - sound.play(); - currentSound = sound; - lastSound = new Date().getTime(); - }); - } - -}); - -(function () { - - // The star of every good animation - var requestAnimationFrame = window.requestAnimationFrame || - window.mozRequestAnimationFrame || - window.webkitRequestAnimationFrame || - window.msRequestAnimationFrame; - - var transforms = ["transform", - "msTransform", - "webkitTransform", - "mozTransform", - "oTransform"]; - - var transformProperty = getSupportedPropertyName(transforms); - - // Array to store our Snowflake objects - var snowflakes = []; - - // Global variables to store our browser's window size - var browserWidth; - var browserHeight; - - // Specify the number of snowflakes you want visible - var numberOfSnowflakes = 50; - - // Flag to reset the position of the snowflakes - var resetPosition = false; - - // - // It all starts here... - // - function setup() { - window.addEventListener("resize", setResetFlag, false); - } - setup(); - - // - // Vendor prefix management - // - function getSupportedPropertyName(properties) { - for (var i = 0; i < properties.length; i++) { - if (typeof document.body.style[properties[i]] != "undefined") { - return properties[i]; - } - } - return null; - } - - // - // Constructor for our Snowflake object - // - function Snowflake(element, radius, speed, xPos, yPos) { - - // set initial snowflake properties - this.element = element; - this.radius = radius; - this.speed = speed; - this.xPos = xPos; - this.yPos = yPos; - - // declare variables used for snowflake's motion - this.counter = 0; - this.sign = Math.random() < 0.5 ? 1 : -1; - - // setting an initial opacity and size for our snowflake - this.element.style.opacity = .1 + Math.random(); - this.element.style.fontSize = 12 + Math.random() * 50 + "px"; - } - - // - // The function responsible for actually moving our snowflake - // - Snowflake.prototype.update = function () { - - // using some trigonometry to determine our x and y position - this.counter += this.speed / 5000; - this.xPos += this.sign * this.speed * Math.cos(this.counter) / 40; - this.yPos += Math.sin(this.counter) / 40 + this.speed / 30; - - // setting our snowflake's position - setTranslate3DTransform(this.element, Math.round(this.xPos), Math.round(this.yPos)); - - // if snowflake goes below the browser window, move it back to the top - if (this.yPos > browserHeight) { - this.yPos = -50; - } - } - - // - // A performant way to set your snowflake's position - // - function setTranslate3DTransform(element, xPosition, yPosition) { - var val = "translate3d(" + xPosition + "px, " + yPosition + "px" + ", 0)"; - element.style[transformProperty] = val; - } - - // - // The function responsible for creating the snowflake - // - function generateSnowflakes() { - - // get our snowflake element from the DOM and store it - var originalSnowflake = document.querySelector(".snowflake"); - - // access our snowflake element's parent container - var snowflakeContainer = originalSnowflake.parentNode; - - // get our browser's size - browserWidth = document.documentElement.clientWidth; - browserHeight = document.documentElement.clientHeight; - - // create each individual snowflake - for (var i = 0; i < numberOfSnowflakes; i++) { - - // clone our original snowflake and add it to snowflakeContainer - var snowflakeCopy = originalSnowflake.cloneNode(true); - snowflakeContainer.appendChild(snowflakeCopy); - - // set our snowflake's initial position and related properties - var initialXPos = getPosition(50, browserWidth); - var initialYPos = getPosition(50, browserHeight); - var speed = 5 + Math.random() * 40; - var radius = 4 + Math.random() * 10; - - // create our Snowflake object - var snowflakeObject = new Snowflake(snowflakeCopy, - radius, - speed, - initialXPos, - initialYPos); - snowflakes.push(snowflakeObject); - } - - // remove the original snowflake because we no longer need it visible - snowflakeContainer.removeChild(originalSnowflake); - - // call the moveSnowflakes function every 30 milliseconds - moveSnowflakes(); - } - - var stopped = false; - - window.generateSnowflakes = generateSnowflakes; - window.stopSnowflakes = function () { - stopped = true; - - var elems = document.querySelectorAll('.snowflake'); - for (var i = 0, length = elems.length; i < length; i++) { - elems[i].parentNode.removeChild(elems[i]); - } - }; - - // - // Responsible for moving each snowflake by calling its update function - // - function moveSnowflakes() { - - if (stopped) { - return; - } - - for (var i = 0; i < snowflakes.length; i++) { - var snowflake = snowflakes[i]; - snowflake.update(); - } - - // Reset the position of all the snowflakes to a new value - if (resetPosition) { - browserWidth = document.documentElement.clientWidth; - browserHeight = document.documentElement.clientHeight; - - for (var i = 0; i < snowflakes.length; i++) { - var snowflake = snowflakes[i]; - - snowflake.xPos = getPosition(50, browserWidth); - snowflake.yPos = getPosition(50, browserHeight); - } - - resetPosition = false; - } - - requestAnimationFrame(moveSnowflakes); - } - - // - // This function returns a number between (maximum - offset) and (maximum + offset) - // - function getPosition(offset, size) { - return Math.round(-1 * offset + Math.random() * (size + 2 * offset)); - } - - // - // Trigger a reset of all the snowflakes' positions - // - function setResetFlag(e) { - resetPosition = true; - } -})(); \ No newline at end of file +define(["appSettings","backdrop","browser","globalize","require","events","paper-icon-button-light"],function(appSettings,backdrop,browser,globalize,require,events){"use strict";function onPageShow(){if(!browser.mobile){if("off"==getHolidayTheme())return;var page=this;require(["css!./style.css"]),page.classList.contains("itemDetailPage")||setBackdrop(page),playThemeMusic(),addSnowflakes(),addIcon(),setBodyClass()}}function playThemeMusic(){"off"!=getHolidayTheme()&&(0==lastSound?playSound("https://github.com/MediaBrowser/Emby.Resources/raw/master/themes/holiday/christmas.wav",.1):(new Date).getTime()-lastSound>3e4&&playSound("https://github.com/MediaBrowser/Emby.Resources/raw/master/themes/holiday/sleighbells.wav",.25))}function destroyTheme(){document.documentElement.classList.remove("christmas"),stopSnowflakes(),currentSound&¤tSound.stop();var holidayInfoButton=document.querySelector(".holidayInfoButton");holidayInfoButton&&holidayInfoButton.parentNode.removeChild(holidayInfoButton),backdrop.clear(),window.location.reload(!0)}function addSnowflakes(){snowFlakesInitialized||(snowFlakesInitialized=!0,document.body.insertAdjacentHTML("beforeend",'

*

'),generateSnowflakes(),events.on(MediaController,"beforeplaybackstart",onPlaybackStart))}function onPlaybackStart(){currentSound&¤tSound.stop(),stopSnowflakes()}function setBackdrop(page){page.classList.contains("itemDetailPage")||("christmas"==getHolidayTheme()?backdrop.setBackdrop("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/bgc.jpg"):backdrop.setBackdrop("https://raw.githubusercontent.com/MediaBrowser/Emby.Resources/master/themes/holiday/bg.jpg"))}function getHolidayTheme(){return appSettings.get(holidayThemeKey)}function setHolidayTheme(value){appSettings.set(holidayThemeKey,value),setBodyClass(),playThemeMusic()}function setBodyClass(){"christmas"==getHolidayTheme()?document.documentElement.classList.add("christmas"):document.documentElement.classList.remove("christmas")}function onIconClick(e){var items=[],current=getHolidayTheme();items.push({name:"None",id:"none",ironIcon:"off"==current?"check":null}),items.push({name:"Joy!",id:"joy",ironIcon:"off"!=current&&"christmas"!=current?"check":null}),items.push({name:"Christmas",id:"christmas",ironIcon:"christmas"==current?"check":null}),require(["actionsheet"],function(actionsheet){actionsheet.show({title:"Happy holidays from the Emby team! Select your holiday theme:",items:items,callback:function(id){switch(id){case"none":setHolidayTheme("off"),destroyTheme();break;case"joy":setHolidayTheme(""),setBackdrop($.mobile.activePage);break;case"christmas":setHolidayTheme("christmas"),setBackdrop($.mobile.activePage)}}})})}function addIcon(){if(!iconCreated){iconCreated=!0;var viewMenuSecondary=document.querySelector(".viewMenuSecondary");if(viewMenuSecondary){var html='';viewMenuSecondary.insertAdjacentHTML("afterbegin",html),viewMenuSecondary.querySelector(".holidayInfoButton").addEventListener("click",onIconClick)}}}function playSound(path,volume){require(["howler"],function(howler){var sound=new Howl({urls:[path],volume:volume||.3});sound.play(),currentSound=sound,lastSound=(new Date).getTime()})}var iconCreated,currentSound,snowFlakesInitialized,lastSound=0,holidayThemeKey="holidaytheme9";pageClassOn("pageshow","libraryPage",onPageShow)}),function(){function setup(){window.addEventListener("resize",setResetFlag,!1)}function getSupportedPropertyName(properties){for(var i=0;ibrowserHeight&&(this.yPos=-50)};var stopped=!1;window.generateSnowflakes=generateSnowflakes,window.stopSnowflakes=function(){stopped=!0;for(var elems=document.querySelectorAll(".snowflake"),i=0,length=elems.length;i li { - margin: 0; - padding: 0; - list-style: none; - border-color: #ddd; - } - -/*.ui-content ul[data-role="listview"], -.ui-panel-inner > ul[data-role="listview"] { - margin: 1em 0; -}*/ - -.ui-collapsible-content > ul[data-role="listview"] { - margin: .5em 0; -} - -ul[data-role="listview"] > li { - display: block; - position: relative; - overflow: visible; -} - - ul[data-role="listview"] > li, - ul[data-role="listview"] > li[data-role="list-divider"], - ul[data-role="listview"] > li > a { - margin: 0; - display: block; - position: relative; - text-align: left; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - color: inherit !important; - font-weight: inherit !important; - font-size: inherit !important; - } - -ul[data-role="listview"] > li[data-role="list-divider"] { - background: #ddd; -} - -ul[data-role="listview"] > li > a:focus { - z-index: 1; -} - -ul[data-role="listview"] > li, -ul[data-role="listview"] > li[data-role="list-divider"] { - border-width: 1px 0 0 0; - border-style: solid; -} - - ul[data-role="listview"] > li, - ul[data-role="listview"] > li[data-role="list-divider"] { - border-right-width: 1px; - border-left-width: 1px; - } - - ul[data-role="listview"] > li:last-child, - ul[data-role="listview"] > li[data-role="list-divider"]:last-child, - ul[data-role="listview"] > li:last-child > a { - border-bottom-width: 1px; - } - -.ui-collapsible-content > ul[data-role="listview"]:not(ul[data-role="listview"]) > li:first-child, -.ui-collapsible-content > ul[data-role="listview"]:not(ul[data-role="listview"]) > li:first-child > a { - border-top-width: 0; -} - -.ui-collapsible-themed-content ul[data-role="listview"]:not(ul[data-role="listview"]) > li:last-child, -.ui-collapsible-themed-content ul[data-role="listview"]:not(ul[data-role="listview"]) > li:last-child > a { - border-bottom-width: 0; -} - -ul[data-role="listview"] > li:first-child, -ul[data-role="listview"] > li:first-child > a { - -webkit-border-top-right-radius: inherit; - border-top-right-radius: inherit; - -webkit-border-top-left-radius: inherit; - border-top-left-radius: inherit; -} - -ul[data-role="listview"] > li:last-child, -ul[data-role="listview"] > li:last-child > a { - -webkit-border-bottom-right-radius: inherit; - border-bottom-right-radius: inherit; - -webkit-border-bottom-left-radius: inherit; - border-bottom-left-radius: inherit; -} - -ul[data-role="listview"] > li.ui-li-has-alt > a { - -webkit-border-top-right-radius: 0; - border-top-right-radius: 0; - -webkit-border-bottom-right-radius: 0; - border-bottom-right-radius: 0; -} - -ul[data-role="listview"] > li:first-child > a + a { - -webkit-border-top-left-radius: 0; - border-top-left-radius: 0; - -webkit-border-top-right-radius: inherit; - border-top-right-radius: inherit; -} - -ul[data-role="listview"] > li:last-child > a + a { - -webkit-border-bottom-left-radius: 0; - border-bottom-left-radius: 0; - -webkit-border-bottom-right-radius: inherit; - border-bottom-right-radius: inherit; -} - -ul[data-role="listview"] > li:first-child img:first-child:not(.ui-li-icon) { - -webkit-border-top-left-radius: inherit; - border-top-left-radius: inherit; -} - -ul[data-role="listview"] > li:last-child img:first-child:not(.ui-li-icon) { - -webkit-border-bottom-left-radius: inherit; - border-bottom-left-radius: inherit; -} - -.ui-collapsible-content > ul[data-role="listview"]:not(ul[data-role="listview"]) { - -webkit-border-radius: inherit; - border-radius: inherit; -} - -ul[data-role="listview"] > li { - padding: .7em 1em; -} - - ul[data-role="listview"] > li[data-role="list-divider"] { - padding: .5em 1.143em; - font-size: 14px; - font-weight: bold; - cursor: default; - outline: 0; /* Dividers in custom selectmenus have tabindex */ - } - - ul[data-role="listview"] > .ui-li-has-count > a, - ul[data-role="listview"] > .ui-li-static.ui-li-has-count, - ul[data-role="listview"] > li[data-role="list-divider"].ui-li-has-count { - padding-right: 2.8125em; - } - -ul[data-role="listview"] > .ui-li-has-count > .ui-btn-icon-right { - padding-right: 4.6875em; -} - -ul[data-role="listview"] > .ui-li-has-thumb > a, -ul[data-role="listview"] > .ui-li-static.ui-li-has-thumb { - min-height: 3.625em; - padding-left: 6.25em; -} -/* ui-li-has-icon deprecated in 1.4. TODO: remove in 1.5 */ -ul[data-role="listview"] > .ui-li-has-icon > a, -ul[data-role="listview"] > a + a { - min-height: 1.25em; - padding-left: 2.5em; -} -/* Used by both listview and custom multiple select button */ -.ui-li-count { - position: absolute; - font-size: 12.5px; - font-weight: bold; - text-align: center; - border-width: 1px; - border-style: solid; - padding: 0 .48em; - line-height: 1.6em; - min-height: 1.6em; - min-width: .64em; - right: .8em; - top: 50%; - margin-top: -.88em; -} - -ul[data-role="listview"] .ui-btn-icon-right .ui-li-count { - right: 3.2em; -} - -ul[data-role="listview"] > li h1, -ul[data-role="listview"] > li h2, -ul[data-role="listview"] > li h3, -ul[data-role="listview"] > li h4, -ul[data-role="listview"] > li h5, -ul[data-role="listview"] > li h6 { - font-size: 1em; - display: block; - margin: .45em 0; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} - -ul[data-role="listview"] > li p { - font-size: .75em; - font-weight: normal; - display: block; - margin: .6em 0; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -} - -ul[data-role="listview"] .ui-li-aside { - position: absolute; - top: 1em; - right: 3.333em; - margin: 0; - text-align: right; -} - -ul[data-role="listview"] > li.ui-li-has-alt > a { - margin-right: 2.5em; - border-right-width: 0; -} - -ul[data-role="listview"] > li > a + a { - position: absolute; - width: 2.5em; - height: 100%; - min-height: auto; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - border-left-width: 1px; - top: 0; - right: 0; - margin: 0; - padding: 0; - z-index: 2; -} - -ul[data-role="listview"] > li > a + a { - border-right-width: 1px; -} - - ul[data-role="listview"] > li > a + a:focus { - z-index: 3; - } +ul[data-role=listview]{-webkit-border-radius:3px;border-radius:3px}ul[data-role=listview],ul[data-role=listview]>li{margin:0;padding:0;list-style:none;border-color:#ddd}.ui-collapsible-content>ul[data-role=listview]{margin:.5em 0}ul[data-role=listview]>li,ul[data-role=listview]>li>a,ul[data-role=listview]>li[data-role=list-divider]{margin:0;display:block;position:relative;text-align:left;-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;color:inherit!important;font-weight:inherit!important;font-size:inherit!important}ul[data-role=listview]>li>a:focus{z-index:1}ul[data-role=listview]>li,ul[data-role=listview]>li[data-role=list-divider]{border-width:1px 1px 0;border-style:solid}ul[data-role=listview]>li:last-child,ul[data-role=listview]>li:last-child>a,ul[data-role=listview]>li[data-role=list-divider]:last-child{border-bottom-width:1px}.ui-collapsible-content>ul[data-role=listview]:not(ul[data-role=listview])>li:first-child,.ui-collapsible-content>ul[data-role=listview]:not(ul[data-role=listview])>li:first-child>a{border-top-width:0}.ui-collapsible-themed-content ul[data-role=listview]:not(ul[data-role=listview])>li:last-child,.ui-collapsible-themed-content ul[data-role=listview]:not(ul[data-role=listview])>li:last-child>a{border-bottom-width:0}ul[data-role=listview]>li:first-child,ul[data-role=listview]>li:first-child>a{-webkit-border-top-right-radius:inherit;border-top-right-radius:inherit;-webkit-border-top-left-radius:inherit;border-top-left-radius:inherit}ul[data-role=listview]>li:last-child,ul[data-role=listview]>li:last-child>a{-webkit-border-bottom-right-radius:inherit;border-bottom-right-radius:inherit;-webkit-border-bottom-left-radius:inherit;border-bottom-left-radius:inherit}ul[data-role=listview]>li.ui-li-has-alt>a{-webkit-border-top-right-radius:0;border-top-right-radius:0;-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0}ul[data-role=listview]>li:first-child>a+a{-webkit-border-top-left-radius:0;border-top-left-radius:0;-webkit-border-top-right-radius:inherit;border-top-right-radius:inherit}ul[data-role=listview]>li:last-child>a+a{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-webkit-border-bottom-right-radius:inherit;border-bottom-right-radius:inherit}ul[data-role=listview]>li:first-child img:first-child:not(.ui-li-icon){-webkit-border-top-left-radius:inherit;border-top-left-radius:inherit}ul[data-role=listview]>li:last-child img:first-child:not(.ui-li-icon){-webkit-border-bottom-left-radius:inherit;border-bottom-left-radius:inherit}.ui-collapsible-content>ul[data-role=listview]:not(ul[data-role=listview]){-webkit-border-radius:inherit;border-radius:inherit}ul[data-role=listview]>li{padding:.7em 1em}ul[data-role=listview]>li[data-role=list-divider]{background:#ddd;padding:.5em 1.143em;font-size:14px;font-weight:700;cursor:default;outline:0}ul[data-role=listview]>.ui-li-has-count>a,ul[data-role=listview]>.ui-li-static.ui-li-has-count,ul[data-role=listview]>li[data-role=list-divider].ui-li-has-count{padding-right:2.8125em}ul[data-role=listview]>.ui-li-has-count>.ui-btn-icon-right{padding-right:4.6875em}ul[data-role=listview]>.ui-li-has-thumb>a,ul[data-role=listview]>.ui-li-static.ui-li-has-thumb{min-height:3.625em;padding-left:6.25em}ul[data-role=listview]>.ui-li-has-icon>a,ul[data-role=listview]>a+a{min-height:1.25em;padding-left:2.5em}.ui-li-count{position:absolute;font-size:12.5px;font-weight:700;text-align:center;border-width:1px;border-style:solid;padding:0 .48em;line-height:1.6em;min-height:1.6em;min-width:.64em;right:.8em;top:50%;margin-top:-.88em}ul[data-role=listview] .ui-btn-icon-right .ui-li-count{right:3.2em}ul[data-role=listview]>li h1,ul[data-role=listview]>li h2,ul[data-role=listview]>li h3,ul[data-role=listview]>li h4,ul[data-role=listview]>li h5,ul[data-role=listview]>li h6{font-size:1em;display:block;margin:.45em 0;-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}ul[data-role=listview]>li p{font-size:.75em;font-weight:400;display:block;margin:.6em 0;-o-text-overflow:ellipsis;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}ul[data-role=listview] .ui-li-aside{position:absolute;top:1em;right:3.333em;margin:0;text-align:right}ul[data-role=listview]>li.ui-li-has-alt>a{margin-right:2.5em;border-right-width:0}ul[data-role=listview]>li>a+a{position:absolute;width:2.5em;height:100%;min-height:auto;-webkit-box-sizing:border-box;box-sizing:border-box;border-left-width:1px;top:0;right:0;margin:0;padding:0;z-index:2;border-right-width:1px}ul[data-role=listview]>li>a+a:focus{z-index:3} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.css b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.css index 929f626c90..360cbfaf90 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.css +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.css @@ -1,288 +1 @@ -/* "page" containers - full-screen views, one should always be in view post-pageload */ -.ui-mobile [data-role=dialog] { - top: 0; - left: 0; - width: 100%; - min-height: 100%; - position: absolute; - border: 0; -} - -/* preset breakpoint to switch to stacked grid styles below 35em (560px) */ -@media (max-width: 35em) { - .ui-responsive > .ui-block-a, - .ui-responsive > .ui-block-b, - .ui-responsive > .ui-block-c, - .ui-responsive > .ui-block-d, - .ui-responsive > .ui-block-e { - width: 100%; - float: none; - } -} - -/* Panel */ -.ui-panel { - width: 17em; - min-height: 100%; - max-height: none; - border-width: 0; - position: absolute; - top: 0; - display: block; -} - -.ui-panel-closed { - width: 0; - max-height: 100%; - overflow: hidden; - visibility: hidden; - left: 0; - clip: rect(1px,1px,1px,1px); -} - -.ui-panel-fixed { - position: fixed; - bottom: -1px; /* Fixes gap on Chrome for Android */ - padding-bottom: 1px; -} - -.ui-panel-display-reveal { - z-index: 1; -} - -.ui-panel-display-push { - z-index: 999; -} - -.ui-panel-display-overlay { - z-index: 1001; /* Fixed toolbars have z-index 1000 */ -} - -.ui-panel-inner { - padding: 1em; -} - -/* Container, page and wrapper */ -.ui-panel-page-container { - overflow-x: visible; -} - -.ui-panel-page-container-themed .ui-page-active { - background: none; -} - -.ui-panel-wrapper { - position: relative; - min-height: inherit; - border: 0; - overflow-x: hidden; - z-index: 999; -} - -/* Fixed toolbars */ -.ui-panel-fixed-toolbar { - overflow-x: hidden; -} - -/* Dismiss */ -.ui-panel-dismiss { - position: absolute; - top: 0; - left: 0; - right: 0; - height: 100%; - z-index: 1002; - display: none; -} - -.ui-panel-dismiss-open { - display: block; -} - -/* Animate class is added to panel, wrapper and fixed toolbars */ -.ui-panel-animate { - -webkit-transition: -webkit-transform 300ms ease; - -webkit-transition-duration: 300ms; - -moz-transition: -moz-transform 300ms ease; - transition: transform 300ms ease; -} - -/* Fix for Windows Phone issue #6349: unset the transition for transforms in case of fixed toolbars. */ -@media screen and ( max-device-width: 768px ) { - .ui-page-header-fixed .ui-panel-animate.ui-panel-wrapper, - .ui-page-footer-fixed .ui-panel-animate.ui-panel-wrapper, - .ui-panel-animate.ui-panel-fixed-toolbar { - -ms-transition: none; - } - /* We need a transitionend event ... */ - .ui-panel-animate.ui-panel-fixed-toolbar { - -ms-transition: -ms-transform 1ms; - -ms-transform: rotate(0deg); - } -} - -/* Hardware acceleration for smoother transitions on WebKit browsers */ -.ui-panel-animate.ui-panel:not(.ui-panel-display-reveal) { - -webkit-backface-visibility: hidden; - -webkit-transform: translate3d(0,0,0); -} - -/* Panel positioning (for overlay and push) */ -/* Panel left closed */ -.ui-panel-position-left { - left: -17em; -} -/* Panel left closed animated */ -.ui-panel-animate.ui-panel-position-left.ui-panel-display-overlay, -.ui-panel-animate.ui-panel-position-left.ui-panel-display-push { - left: 0; - -webkit-transform: translate3d(-17em,0,0); - -moz-transform: translate3d(-17em,0,0); - transform: translate3d(-17em,0,0); -} -/* Panel left open */ -.ui-panel-position-left.ui-panel-display-reveal, /* Unset "panel left closed" for reveal */ -.ui-panel-open.ui-panel-position-left { - left: 0; -} -/* Panel left open animated */ -.ui-panel-animate.ui-panel-open.ui-panel-position-left.ui-panel-display-overlay, -.ui-panel-animate.ui-panel-open.ui-panel-position-left.ui-panel-display-push { - -webkit-transform: translate3d(0,0,0); - transform: translate3d(0,0,0); - -moz-transform: none; -} -/* Panel right closed */ -.ui-panel-position-right { - right: -17em; -} -/* Panel right closed animated */ -.ui-panel-animate.ui-panel-position-right.ui-panel-display-overlay, -.ui-panel-animate.ui-panel-position-right.ui-panel-display-push { - right: 0; - -webkit-transform: translate3d(17em,0,0); - -moz-transform: translate3d(17em,0,0); - transform: translate3d(17em,0,0); -} -/* Panel right open */ -.ui-panel-position-right.ui-panel-display-reveal, /* Unset "panel right closed" for reveal */ -.ui-panel-position-right.ui-panel-open { - right: 0; -} -/* Panel right open animated */ -.ui-panel-animate.ui-panel-open.ui-panel-position-right.ui-panel-display-overlay, -.ui-panel-animate.ui-panel-open.ui-panel-position-right.ui-panel-display-push { - -webkit-transform: translate3d(0,0,0); - transform: translate3d(0,0,0); - -moz-transform: none; -} - -/* Wrapper and fixed toolbars positioning (for reveal and push) */ -/* Panel left open */ -.ui-panel-page-content-position-left { - left: 17em; - right: -17em; -} -/* Panel left open animated */ -.ui-panel-animate.ui-panel-page-content-position-left { - left: 0; - right: 0; - -webkit-transform: translate3d(17em,0,0); - -moz-transform: translate3d(17em,0,0); - transform: translate3d(17em,0,0); -} -/* Panel right open */ -.ui-panel-page-content-position-right { - left: -17em; - right: 17em; -} -/* Panel right open animated */ -.ui-panel-animate.ui-panel-page-content-position-right { - left: 0; - right: 0; - -webkit-transform: translate3d(-17em,0,0); - -moz-transform: translate3d(-17em,0,0); - transform: translate3d(-17em,0,0); -} - -/* Dismiss model open */ -.ui-panel-dismiss-open.ui-panel-dismiss-position-left { - left: 17em; -} - -.ui-panel-dismiss-open.ui-panel-dismiss-position-right { - right: 17em; -} - -/* Shadows and borders */ -.ui-panel-display-reveal { - -webkit-box-shadow: inset -5px 0 5px rgba(0,0,0,.15); - -moz-box-shadow: inset -5px 0 5px rgba(0,0,0,.15); - box-shadow: inset -5px 0 5px rgba(0,0,0,.15); -} - -.ui-panel-position-right.ui-panel-display-reveal { - -webkit-box-shadow: inset 5px 0 5px rgba(0,0,0,.15); - -moz-box-shadow: inset 5px 0 5px rgba(0,0,0,.15); - box-shadow: inset 5px 0 5px rgba(0,0,0,.15); -} - -.ui-panel-display-overlay { - -webkit-box-shadow: 5px 0 5px rgba(0,0,0,.15); - -moz-box-shadow: 5px 0 5px rgba(0,0,0,.15); - box-shadow: 5px 0 5px rgba(0,0,0,.15); -} - -.ui-panel-position-right.ui-panel-display-overlay { - -webkit-box-shadow: -5px 0 5px rgba(0,0,0,.15); - -moz-box-shadow: -5px 0 5px rgba(0,0,0,.15); - box-shadow: -5px 0 5px rgba(0,0,0,.15); -} - -.ui-panel-open.ui-panel-position-left.ui-panel-display-push { - border-right-width: 1px; - margin-right: -1px; -} - -.ui-panel-page-content-position-left.ui-panel-page-content-display-push { - margin-left: 1px; - width: auto; -} - -.ui-panel-open.ui-panel-position-right.ui-panel-display-push { - border-left-width: 1px; - margin-left: -1px; -} - -.ui-panel-page-content-position-right.ui-panel-page-content-display-push { - margin-right: 1px; - width: auto; -} - -/* Responsive: wrap on wide viewports once open */ -@media (min-width:55em) { - .ui-responsive-panel .ui-panel-page-content-open.ui-panel-page-content-position-left { - margin-right: 17em; - } - - .ui-responsive-panel .ui-panel-page-content-open.ui-panel-page-content-position-right { - margin-left: 17em; - } - - .ui-responsive-panel .ui-panel-page-content-open { - width: auto; - } - - .ui-responsive-panel .ui-panel-dismiss-display-push, - .ui-responsive-panel.ui-page-active ~ .ui-panel-dismiss-display-push { - display: none; - } -} - -.ui-body-a.ui-panel { - background-color: #fff; -} - -.ui-body-b.ui-panel { - background-color: #222; -} +.ui-mobile [data-role=dialog],.ui-panel{min-height:100%;position:absolute;top:0}.ui-mobile [data-role=dialog]{left:0;width:100%;border:0}@media (max-width:35em){.ui-responsive>.ui-block-a,.ui-responsive>.ui-block-b,.ui-responsive>.ui-block-c,.ui-responsive>.ui-block-d,.ui-responsive>.ui-block-e{width:100%;float:none}}.ui-panel{width:17em;max-height:none;border-width:0;display:block}.ui-panel-closed{width:0;max-height:100%;overflow:hidden;visibility:hidden;left:0;clip:rect(1px,1px,1px,1px)}.ui-panel-fixed{position:fixed;bottom:-1px;padding-bottom:1px}.ui-panel-display-reveal{z-index:1;-webkit-box-shadow:inset -5px 0 5px rgba(0,0,0,.15);box-shadow:inset -5px 0 5px rgba(0,0,0,.15)}.ui-panel-display-push{z-index:999}.ui-panel-display-overlay{z-index:1001}.ui-panel-inner{padding:1em}.ui-panel-page-container{overflow-x:visible}.ui-panel-fixed-toolbar,.ui-panel-wrapper{overflow-x:hidden}.ui-panel-page-container-themed .ui-page-active{background:0 0}.ui-panel-wrapper{position:relative;min-height:inherit;border:0;z-index:999}.ui-panel-dismiss{position:absolute;top:0;left:0;right:0;height:100%;z-index:1002;display:none}.ui-panel-dismiss-open{display:block}.ui-panel-animate{-webkit-transition:-webkit-transform .3s ease;-o-transition:transform .3s ease;transition:transform .3s ease}@media screen and (max-device-width:768px){.ui-page-footer-fixed .ui-panel-animate.ui-panel-wrapper,.ui-page-header-fixed .ui-panel-animate.ui-panel-wrapper,.ui-panel-animate.ui-panel-fixed-toolbar{-ms-transition:none}.ui-panel-animate.ui-panel-fixed-toolbar{-ms-transition:-ms-transform 1ms;-ms-transform:rotate(0)}}.ui-panel-animate.ui-panel:not(.ui-panel-display-reveal){-webkit-backface-visibility:hidden;-webkit-transform:translate3d(0,0,0)}.ui-panel-position-left{left:-17em}.ui-panel-animate.ui-panel-position-left.ui-panel-display-overlay,.ui-panel-animate.ui-panel-position-left.ui-panel-display-push{left:0;-webkit-transform:translate3d(-17em,0,0);transform:translate3d(-17em,0,0)}.ui-panel-open.ui-panel-position-left,.ui-panel-position-left.ui-panel-display-reveal{left:0}.ui-panel-animate.ui-panel-open.ui-panel-position-left.ui-panel-display-overlay,.ui-panel-animate.ui-panel-open.ui-panel-position-left.ui-panel-display-push{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);-moz-transform:none}.ui-panel-position-right{right:-17em}.ui-panel-animate.ui-panel-position-right.ui-panel-display-overlay,.ui-panel-animate.ui-panel-position-right.ui-panel-display-push{right:0;-webkit-transform:translate3d(17em,0,0);transform:translate3d(17em,0,0)}.ui-panel-position-right.ui-panel-display-reveal,.ui-panel-position-right.ui-panel-open{right:0}.ui-panel-animate.ui-panel-open.ui-panel-position-right.ui-panel-display-overlay,.ui-panel-animate.ui-panel-open.ui-panel-position-right.ui-panel-display-push{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);-moz-transform:none}.ui-panel-page-content-position-left{left:17em;right:-17em}.ui-panel-animate.ui-panel-page-content-position-left{left:0;right:0;-webkit-transform:translate3d(17em,0,0);transform:translate3d(17em,0,0)}.ui-panel-page-content-position-right{left:-17em;right:17em}.ui-panel-animate.ui-panel-page-content-position-right{left:0;right:0;-webkit-transform:translate3d(-17em,0,0);transform:translate3d(-17em,0,0)}.ui-panel-dismiss-open.ui-panel-dismiss-position-left{left:17em}.ui-panel-dismiss-open.ui-panel-dismiss-position-right{right:17em}.ui-panel-position-right.ui-panel-display-reveal{-webkit-box-shadow:inset 5px 0 5px rgba(0,0,0,.15);box-shadow:inset 5px 0 5px rgba(0,0,0,.15)}.ui-panel-display-overlay{-webkit-box-shadow:5px 0 5px rgba(0,0,0,.15);box-shadow:5px 0 5px rgba(0,0,0,.15)}.ui-panel-position-right.ui-panel-display-overlay{-webkit-box-shadow:-5px 0 5px rgba(0,0,0,.15);box-shadow:-5px 0 5px rgba(0,0,0,.15)}.ui-panel-open.ui-panel-position-left.ui-panel-display-push{border-right-width:1px;margin-right:-1px}.ui-panel-page-content-position-left.ui-panel-page-content-display-push{margin-left:1px;width:auto}.ui-panel-open.ui-panel-position-right.ui-panel-display-push{border-left-width:1px;margin-left:-1px}.ui-panel-page-content-position-right.ui-panel-page-content-display-push{margin-right:1px;width:auto}@media (min-width:55em){.ui-responsive-panel .ui-panel-page-content-open.ui-panel-page-content-position-left{margin-right:17em}.ui-responsive-panel .ui-panel-page-content-open.ui-panel-page-content-position-right{margin-left:17em}.ui-responsive-panel .ui-panel-page-content-open{width:auto}.ui-responsive-panel .ui-panel-dismiss-display-push,.ui-responsive-panel.ui-page-active~.ui-panel-dismiss-display-push{display:none}}.ui-body-a.ui-panel{background-color:#fff}.ui-body-b.ui-panel{background-color:#222} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.js b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.js index 0a7cb9b3b6..a391844311 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.js +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.panel.js @@ -1,531 +1 @@ -define(['jqmwidget'], function () { - - (function ($, undefined) { - var props = { - "animation": {}, - "transition": {} - }, - testElement = document.createElement("a"), - vendorPrefixes = ["", "webkit-", "moz-", "o-"]; - - $.each(["animation", "transition"], function (i, test) { - - // Get correct name for test - var testName = (i === 0) ? test + "-" + "name" : test; - - $.each(vendorPrefixes, function (j, prefix) { - if (testElement.style[$.camelCase(prefix + testName)] !== undefined) { - props[test]["prefix"] = prefix; - return false; - } - }); - - // Set event and duration names for later use - props[test]["duration"] = - $.camelCase(props[test]["prefix"] + test + "-" + "duration"); - props[test]["event"] = - $.camelCase(props[test]["prefix"] + test + "-" + "end"); - - // All lower case if not a vendor prop - if (props[test]["prefix"] === "") { - props[test]["event"] = props[test]["event"].toLowerCase(); - } - }); - - // Remove the testElement - $(testElement).remove(); - - // Animation complete callback - $.fn.animationComplete = function (callback, type, fallbackTime) { - var timer, duration, - that = this, - eventBinding = function () { - - // Clear the timer so we don't call callback twice - clearTimeout(timer); - callback.apply(this, arguments); - }, - animationType = (!type || type === "animation") ? "animation" : "transition"; - - // If a fallback time was not passed set one - if (fallbackTime === undefined) { - - // Make sure the was not bound to document before checking .css - if ($(this).context !== document) { - - // Parse the durration since its in second multiple by 1000 for milliseconds - // Multiply by 3 to make sure we give the animation plenty of time. - duration = parseFloat( - $(this).css(props[animationType].duration) - ) * 3000; - } - - // If we could not read a duration use the default - if (duration === 0 || duration === undefined || isNaN(duration)) { - duration = $.fn.animationComplete.defaultDuration; - } - } - - // Sets up the fallback if event never comes - timer = setTimeout(function () { - $(that).off(props[animationType].event, eventBinding); - callback.apply(that); - }, duration); - - // Bind the event - return $(this).one(props[animationType].event, eventBinding); - }; - - // Allow default callback to be configured on mobileInit - $.fn.animationComplete.defaultDuration = 1000; - })(jQuery); - - (function ($, undefined) { - - $.widget("mobile.panel", { - options: { - animate: true, - theme: null, - position: "left", - dismissible: true, - display: "overlay", //accepts reveal, push, overlay - swipeClose: true, - positionFixed: true - }, - - _parentPage: null, - _page: null, - _modal: null, - _panelInner: null, - _wrapper: null, - - _create: function () { - var el = this.element, - parentPage = el.closest(".ui-page, [data-role='page']"); - - // expose some private props to other methods - $.extend(this, { - _parentPage: (parentPage.length > 0) ? parentPage : false, - _openedPage: null, - _page: this._getPage, - _panelInner: this._getPanelInner() - }); - if (this.options.display !== "overlay") { - this._getWrapper(); - } - this._addPanelClasses(); - - // if animating, add the class to do so - if (!!this.options.animate) { - this.element.addClass("ui-panel-animate"); - } - - this._bindUpdateLayout(); - this._bindCloseEvents(); - this._bindLinkListeners(); - this._bindPageEvents(); - - if (!!this.options.dismissible) { - this._createModal(); - } - - this._bindSwipeEvents(); - }, - - _getPanelInner: function () { - var panelInner = this.element[0].querySelector("." + "ui-panel-inner"); - if (!panelInner) { - panelInner = this.element.children().wrapAll("
").parent(); - } else { - panelInner = $(panelInner); - } - - return panelInner; - }, - - _createModal: function () { - var self = this, - target = self._parentPage ? self._parentPage.parent() : self.element.parent(); - - self._modal = $("
") - .on("mousedown", function () { - self.close(); - }) - .appendTo(target); - }, - - _getPage: function () { - var page = this._openedPage || this._parentPage || $(".ui-page-active"); - - return page; - }, - - _getWrapper: function () { - var wrapper = this._page().find("." + "ui-panel-wrapper"); - if (wrapper.length === 0) { - wrapper = this._page().children(".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)") - .wrapAll("
") - .parent(); - } - - this._wrapper = wrapper; - }, - - _getPosDisplayClasses: function (prefix) { - return prefix + "-position-right " + prefix + "-display-" + this.options.display; - }, - - _getPanelClasses: function () { - var panelClasses = "ui-panel" + - " " + this._getPosDisplayClasses("ui-panel") + - " " + "ui-panel-closed" + - " " + "ui-body-" + (this.options.theme ? this.options.theme : "inherit"); - - if (!!this.options.positionFixed) { - panelClasses += " " + "ui-panel-fixed"; - } - - return panelClasses; - }, - - _addPanelClasses: function () { - this.element.addClass(this._getPanelClasses()); - }, - - _handleCloseClick: function (event) { - if (!event.isDefaultPrevented()) { - this.close(); - } - }, - - _bindCloseEvents: function () { - }, - - _positionPanel: function (scrollToTop) { - var self = this, - panelInnerHeight = self._panelInner.outerHeight(), - expand = panelInnerHeight > (window.innerHeight || $(window).height()); - - if (expand || !self.options.positionFixed) { - if (expand) { - self._unfixPanel(); - } - if (scrollToTop) { - this.window[0].scrollTo(0, $.mobile.defaultHomeScroll); - } - } else { - self._fixPanel(); - } - }, - - _bindFixListener: function () { - this._on($(window), { "resize": "_positionPanel" }); - }, - - _unbindFixListener: function () { - this._off($(window), "resize"); - }, - - _unfixPanel: function () { - if (!!this.options.positionFixed) { - this.element.removeClass("ui-panel-fixed"); - } - }, - - _fixPanel: function () { - if (!!this.options.positionFixed) { - this.element.addClass("ui-panel-fixed"); - } - }, - - _bindUpdateLayout: function () { - var self = this; - - self.element.on("updatelayout", function (/* e */) { - if (self._open) { - self._positionPanel(); - } - }); - }, - - _bindLinkListeners: function () { - this._on("body", { - "click a": "_handleClick" - }); - - }, - - _handleClick: function (e) { - var link, - panelId = this.element.attr("id"); - - if (e.currentTarget.href.split("#")[1] === panelId && panelId !== undefined) { - - e.preventDefault(); - link = $(e.target); - if (link.hasClass("ui-btn")) { - link.addClass($.mobile.activeBtnClass); - this.element.one("panelopen panelclose", function () { - link.removeClass($.mobile.activeBtnClass); - }); - } - this.toggle(); - } - }, - - _bindSwipeEvents: function () { - var self = this, - area = self._modal ? self.element.add(self._modal) : self.element; - - // on swipe, close the panel - if (!!self.options.swipeClose) { - if (self.options.position === "left") { - area.on("swipeleft.panel", function (/* e */) { - self.close(); - }); - } else { - area.on("swiperight.panel", function (/* e */) { - self.close(); - }); - } - } - }, - - _bindPageEvents: function () { - var self = this; - - this.document - // Close the panel if another panel on the page opens - .on("panelbeforeopen", function (e) { - if (self._open && e.target !== self.element[0]) { - self.close(); - } - }) - // On escape, close? might need to have a target check too... - .on("keyup.panel", function (e) { - if (e.keyCode === 27 && self._open) { - self.close(); - } - }); - if (!this._parentPage && this.options.display !== "overlay") { - this._on(this.document, { - "pageshow": function () { - this._openedPage = null; - this._getWrapper(); - } - }); - } - // Clean up open panels after page hide - if (self._parentPage) { - this.document.on("pagehide", "[data-role='page']", function () { - if (self._open) { - self.close(true); - } - }); - } else { - this.document.on("pagebeforehide", function () { - if (self._open) { - self.close(true); - } - }); - } - }, - - // state storage of open or closed - _open: false, - _pageContentOpenClasses: null, - _modalOpenClasses: null, - - open: function (immediate) { - if (!this._open) { - var self = this, - o = self.options, - - _openPanel = function () { - self._off(self.document, "panelclose"); - self._page().data("panel", "open"); - - if (!!o.animate && o.display !== "overlay") { - self._wrapper.addClass("ui-panel-animate"); - } - - if (!immediate && !!o.animate) { - (self._wrapper || self.element) - .animationComplete(complete, "transition"); - } else { - setTimeout(complete, 0); - } - - if (o.theme && o.display !== "overlay") { - self._page().parent() - .addClass("ui-panel-page-container" + "-themed " + "ui-panel-page-container" + "-" + o.theme); - } - - self.element - .removeClass("ui-panel-closed") - .addClass("ui-panel-open"); - - self._positionPanel(true); - - self._pageContentOpenClasses = self._getPosDisplayClasses("ui-panel-page-content"); - - if (o.display !== "overlay") { - self._page().parent().addClass("ui-panel-page-container"); - self._wrapper.addClass(self._pageContentOpenClasses); - } - - self._modalOpenClasses = self._getPosDisplayClasses("ui-panel-dismiss") + " " + "ui-panel-dismiss-open"; - if (self._modal) { - self._modal - .addClass(self._modalOpenClasses) - .height(Math.max(self._modal.height(), self.document.height())); - } - }, - complete = function () { - - // Bail if the panel was closed before the opening animation has completed - if (!self._open) { - return; - } - - if (o.display !== "overlay") { - self._wrapper.addClass("ui-panel-page-content" + "-open"); - } - - self._bindFixListener(); - - self._trigger("open"); - - self._openedPage = self._page(); - }; - - self._trigger("beforeopen"); - - if (self._page().data("panel") === "open") { - self._on(self.document, { - "panelclose": _openPanel - }); - } else { - _openPanel(); - } - - self._open = true; - } - }, - - close: function (immediate) { - if (this._open) { - var self = this, - o = this.options, - - _closePanel = function () { - - self.element.removeClass("ui-panel-open"); - - if (o.display !== "overlay") { - self._wrapper.removeClass(self._pageContentOpenClasses); - } - - if (!immediate && !!o.animate) { - (self._wrapper || self.element) - .animationComplete(complete, "transition"); - } else { - setTimeout(complete, 0); - } - - if (self._modal) { - self._modal - .removeClass(self._modalOpenClasses) - .height(""); - } - }, - complete = function () { - if (o.theme && o.display !== "overlay") { - self._page().parent().removeClass("ui-panel-page-container" + "-themed " + "ui-panel-page-container" + "-" + o.theme); - } - - self.element.addClass("ui-panel-closed"); - - if (o.display !== "overlay") { - self._page().parent().removeClass("ui-panel-page-container"); - self._wrapper.removeClass("ui-panel-page-content" + "-open"); - } - - if (!!o.animate && o.display !== "overlay") { - self._wrapper.removeClass("ui-panel-animate"); - } - - self._fixPanel(); - self._unbindFixListener(); - - self._page().removeData("panel"); - - self._trigger("close"); - - self._openedPage = null; - }; - - self._trigger("beforeclose"); - - _closePanel(); - - self._open = false; - } - }, - - toggle: function () { - this[this._open ? "close" : "open"](); - }, - - _destroy: function () { - var otherPanels, - o = this.options, - multiplePanels = ($("body > :mobile-panel").length + $.mobile.activePage.find(":mobile-panel").length) > 1; - - if (o.display !== "overlay") { - - // remove the wrapper if not in use by another panel - otherPanels = $("body > :mobile-panel").add($.mobile.activePage.find(":mobile-panel")); - if (otherPanels.not(".ui-panel-display-overlay").not(this.element).length === 0) { - this._wrapper.children().unwrap(); - } - - if (this._open) { - - this._page().parent().removeClass("ui-panel-page-container"); - - if (o.theme) { - this._page().parent().removeClass("ui-panel-page-container" + "-themed " + "ui-panel-page-container" + "-" + o.theme); - } - } - } - - if (!multiplePanels) { - - this.document.off("panelopen panelclose"); - - } - - if (this._open) { - this._page().removeData("panel"); - } - - this._panelInner.children().unwrap(); - - this.element - .removeClass([this._getPanelClasses(), "ui-panel-open", "ui-panel-animate"].join(" ")) - .off("swipeleft.panel swiperight.panel") - .off("panelbeforeopen") - .off("panelhide") - .off("keyup.panel") - .off("updatelayout"); - - if (this._modal) { - this._modal.remove(); - } - } - }); - - })(jQuery); - -}); \ No newline at end of file +define(["jqmwidget"],function(){!function($,undefined){var props={animation:{},transition:{}},testElement=document.createElement("a"),vendorPrefixes=["","webkit-","moz-","o-"];$.each(["animation","transition"],function(i,test){var testName=0===i?test+"-name":test;$.each(vendorPrefixes,function(j,prefix){if(testElement.style[$.camelCase(prefix+testName)]!==undefined)return props[test].prefix=prefix,!1}),props[test].duration=$.camelCase(props[test].prefix+test+"-duration"),props[test].event=$.camelCase(props[test].prefix+test+"-end"),""===props[test].prefix&&(props[test].event=props[test].event.toLowerCase())}),$(testElement).remove(),$.fn.animationComplete=function(callback,type,fallbackTime){var timer,duration,that=this,eventBinding=function(){clearTimeout(timer),callback.apply(this,arguments)},animationType=type&&"animation"!==type?"transition":"animation";return fallbackTime===undefined&&($(this).context!==document&&(duration=3e3*parseFloat($(this).css(props[animationType].duration))),(0===duration||duration===undefined||isNaN(duration))&&(duration=$.fn.animationComplete.defaultDuration)),timer=setTimeout(function(){$(that).off(props[animationType].event,eventBinding),callback.apply(that)},duration),$(this).one(props[animationType].event,eventBinding)},$.fn.animationComplete.defaultDuration=1e3}(jQuery),function($,undefined){$.widget("mobile.panel",{options:{animate:!0,theme:null,position:"left",dismissible:!0,display:"overlay",swipeClose:!0,positionFixed:!0},_parentPage:null,_page:null,_modal:null,_panelInner:null,_wrapper:null,_create:function(){var el=this.element,parentPage=el.closest(".ui-page, [data-role='page']");$.extend(this,{_parentPage:parentPage.length>0&&parentPage,_openedPage:null,_page:this._getPage,_panelInner:this._getPanelInner()}),"overlay"!==this.options.display&&this._getWrapper(),this._addPanelClasses(),this.options.animate&&this.element.addClass("ui-panel-animate"),this._bindUpdateLayout(),this._bindCloseEvents(),this._bindLinkListeners(),this._bindPageEvents(),this.options.dismissible&&this._createModal(),this._bindSwipeEvents()},_getPanelInner:function(){var panelInner=this.element[0].querySelector(".ui-panel-inner");return panelInner=panelInner?$(panelInner):this.element.children().wrapAll("
").parent()},_createModal:function(){var self=this,target=self._parentPage?self._parentPage.parent():self.element.parent();self._modal=$("
").on("mousedown",function(){self.close()}).appendTo(target)},_getPage:function(){var page=this._openedPage||this._parentPage||$(".ui-page-active");return page},_getWrapper:function(){var wrapper=this._page().find(".ui-panel-wrapper");0===wrapper.length&&(wrapper=this._page().children(".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)").wrapAll("
").parent()),this._wrapper=wrapper},_getPosDisplayClasses:function(prefix){return prefix+"-position-right "+prefix+"-display-"+this.options.display},_getPanelClasses:function(){var panelClasses="ui-panel "+this._getPosDisplayClasses("ui-panel")+" ui-panel-closed ui-body-"+(this.options.theme?this.options.theme:"inherit");return this.options.positionFixed&&(panelClasses+=" ui-panel-fixed"),panelClasses},_addPanelClasses:function(){this.element.addClass(this._getPanelClasses())},_handleCloseClick:function(event){event.isDefaultPrevented()||this.close()},_bindCloseEvents:function(){},_positionPanel:function(scrollToTop){var self=this,panelInnerHeight=self._panelInner.outerHeight(),expand=panelInnerHeight>(window.innerHeight||$(window).height());expand||!self.options.positionFixed?(expand&&self._unfixPanel(),scrollToTop&&this.window[0].scrollTo(0,$.mobile.defaultHomeScroll)):self._fixPanel()},_bindFixListener:function(){this._on($(window),{resize:"_positionPanel"})},_unbindFixListener:function(){this._off($(window),"resize")},_unfixPanel:function(){this.options.positionFixed&&this.element.removeClass("ui-panel-fixed")},_fixPanel:function(){this.options.positionFixed&&this.element.addClass("ui-panel-fixed")},_bindUpdateLayout:function(){var self=this;self.element.on("updatelayout",function(){self._open&&self._positionPanel()})},_bindLinkListeners:function(){this._on("body",{"click a":"_handleClick"})},_handleClick:function(e){var link,panelId=this.element.attr("id");e.currentTarget.href.split("#")[1]===panelId&&panelId!==undefined&&(e.preventDefault(),link=$(e.target),link.hasClass("ui-btn")&&(link.addClass($.mobile.activeBtnClass),this.element.one("panelopen panelclose",function(){link.removeClass($.mobile.activeBtnClass)})),this.toggle())},_bindSwipeEvents:function(){var self=this,area=self._modal?self.element.add(self._modal):self.element;self.options.swipeClose&&("left"===self.options.position?area.on("swipeleft.panel",function(){self.close()}):area.on("swiperight.panel",function(){self.close()}))},_bindPageEvents:function(){var self=this;this.document.on("panelbeforeopen",function(e){self._open&&e.target!==self.element[0]&&self.close()}).on("keyup.panel",function(e){27===e.keyCode&&self._open&&self.close()}),this._parentPage||"overlay"===this.options.display||this._on(this.document,{pageshow:function(){this._openedPage=null,this._getWrapper()}}),self._parentPage?this.document.on("pagehide","[data-role='page']",function(){self._open&&self.close(!0)}):this.document.on("pagebeforehide",function(){self._open&&self.close(!0)})},_open:!1,_pageContentOpenClasses:null,_modalOpenClasses:null,open:function(immediate){if(!this._open){var self=this,o=self.options,_openPanel=function(){self._off(self.document,"panelclose"),self._page().data("panel","open"),o.animate&&"overlay"!==o.display&&self._wrapper.addClass("ui-panel-animate"),!immediate&&o.animate?(self._wrapper||self.element).animationComplete(complete,"transition"):setTimeout(complete,0),o.theme&&"overlay"!==o.display&&self._page().parent().addClass("ui-panel-page-container-themed ui-panel-page-container-"+o.theme),self.element.removeClass("ui-panel-closed").addClass("ui-panel-open"),self._positionPanel(!0),self._pageContentOpenClasses=self._getPosDisplayClasses("ui-panel-page-content"),"overlay"!==o.display&&(self._page().parent().addClass("ui-panel-page-container"),self._wrapper.addClass(self._pageContentOpenClasses)),self._modalOpenClasses=self._getPosDisplayClasses("ui-panel-dismiss")+" ui-panel-dismiss-open",self._modal&&self._modal.addClass(self._modalOpenClasses).height(Math.max(self._modal.height(),self.document.height()))},complete=function(){self._open&&("overlay"!==o.display&&self._wrapper.addClass("ui-panel-page-content-open"),self._bindFixListener(),self._trigger("open"),self._openedPage=self._page())};self._trigger("beforeopen"),"open"===self._page().data("panel")?self._on(self.document,{panelclose:_openPanel}):_openPanel(),self._open=!0}},close:function(immediate){if(this._open){var self=this,o=this.options,_closePanel=function(){self.element.removeClass("ui-panel-open"),"overlay"!==o.display&&self._wrapper.removeClass(self._pageContentOpenClasses),!immediate&&o.animate?(self._wrapper||self.element).animationComplete(complete,"transition"):setTimeout(complete,0),self._modal&&self._modal.removeClass(self._modalOpenClasses).height("")},complete=function(){o.theme&&"overlay"!==o.display&&self._page().parent().removeClass("ui-panel-page-container-themed ui-panel-page-container-"+o.theme),self.element.addClass("ui-panel-closed"),"overlay"!==o.display&&(self._page().parent().removeClass("ui-panel-page-container"),self._wrapper.removeClass("ui-panel-page-content-open")),o.animate&&"overlay"!==o.display&&self._wrapper.removeClass("ui-panel-animate"),self._fixPanel(),self._unbindFixListener(),self._page().removeData("panel"),self._trigger("close"),self._openedPage=null};self._trigger("beforeclose"),_closePanel(),self._open=!1}},toggle:function(){this[this._open?"close":"open"]()},_destroy:function(){var otherPanels,o=this.options,multiplePanels=$("body > :mobile-panel").length+$.mobile.activePage.find(":mobile-panel").length>1;"overlay"!==o.display&&(otherPanels=$("body > :mobile-panel").add($.mobile.activePage.find(":mobile-panel")),0===otherPanels.not(".ui-panel-display-overlay").not(this.element).length&&this._wrapper.children().unwrap(),this._open&&(this._page().parent().removeClass("ui-panel-page-container"),o.theme&&this._page().parent().removeClass("ui-panel-page-container-themed ui-panel-page-container-"+o.theme))),multiplePanels||this.document.off("panelopen panelclose"),this._open&&this._page().removeData("panel"),this._panelInner.children().unwrap(),this.element.removeClass([this._getPanelClasses(),"ui-panel-open","ui-panel-animate"].join(" ")).off("swipeleft.panel swiperight.panel").off("panelbeforeopen").off("panelhide").off("keyup.panel").off("updatelayout"),this._modal&&this._modal.remove()}})}(jQuery)}); \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.css b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.css index c034aaa5ec..b1e050177f 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.css +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.css @@ -1,453 +1 @@ -.ui-popup-container { - z-index: 99999; -} - -/* "page" containers - full-screen views, one should always be in view post-pageload */ -.ui-mobile [data-role=dialog] { - top: 0; - left: 0; - width: 100%; - min-height: 100%; - position: absolute; - border: 0; - background: #fff; -} - -.ui-popup { - background: #fff; -} -.ui-popup-open .ui-header-fixed, -.ui-popup-open .ui-footer-fixed { - position: absolute !important; /* See issues #4816, #4844 and #4874 and popup.js */ -} - -.ui-popup-screen { - background-image: url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="); /* Necessary to set some form of background to ensure element is clickable in IE6/7. While legacy IE won't understand the data-URI'd image, it ensures no additional requests occur in all other browsers with little overhead. */ - top: 0; - left: 0; - right: 0; - bottom: 1px; - position: absolute; - filter: Alpha(Opacity=0); - opacity: 0; - z-index: 1099; -} - - .ui-popup-screen.in { - opacity: 0.5; - filter: Alpha(Opacity=50); - } - - .ui-popup-screen.out { - opacity: 0; - filter: Alpha(Opacity=0); - } - -.ui-popup-container { - z-index: 1100; - display: inline-block; - position: absolute; - padding: 0; - outline: 0; -} - -.ui-popup { - position: relative; -} - - .ui-popup.ui-body-inherit { - border-width: 1px; - border-style: solid; - } - -.ui-popup-hidden { - left: 0; - top: 0; - position: absolute !important; - visibility: hidden; -} - -.ui-popup-truncate { - height: 1px; - width: 1px; - margin: -1px; - overflow: hidden; - clip: rect(1px,1px,1px,1px); -} - -.ui-popup.ui-content, -.ui-popup .ui-content { - overflow: visible; -} - -.ui-popup > .ui-header { - border-top-width: 0; -} - -.ui-popup > .ui-footer { - border-bottom-width: 0; -} - -.ui-popup > p, -.ui-popup > h1, -.ui-popup > h2, -.ui-popup > h3, -.ui-popup > h4, -.ui-popup > h5, -.ui-popup > h6 { - margin: .5em .4375em; -} - -.ui-popup > span { - display: block; - margin: .5em .4375em; -} - -.ui-popup-container .ui-content > p, -.ui-popup-container .ui-content > h1, -.ui-popup-container .ui-content > h2, -.ui-popup-container .ui-content > h3, -.ui-popup-container .ui-content > h4, -.ui-popup-container .ui-content > h5, -.ui-popup-container .ui-content > h6 { - margin: .5em 0; -} - -.ui-popup-container .ui-content > span { - margin: 0; -} - -.ui-popup-container .ui-content > p:first-child, -.ui-popup-container .ui-content > h1:first-child, -.ui-popup-container .ui-content > h2:first-child, -.ui-popup-container .ui-content > h3:first-child, -.ui-popup-container .ui-content > h4:first-child, -.ui-popup-container .ui-content > h5:first-child, -.ui-popup-container .ui-content > h6:first-child { - margin-top: 0; -} - -.ui-popup-container .ui-content > p:last-child, -.ui-popup-container .ui-content > h1:last-child, -.ui-popup-container .ui-content > h2:last-child, -.ui-popup-container .ui-content > h3:last-child, -.ui-popup-container .ui-content > h4:last-child, -.ui-popup-container .ui-content > h5:last-child, -.ui-popup-container .ui-content > h6:last-child { - margin-bottom: 0; -} - -.ui-popup > img { - max-width: 100%; - max-height: 100%; - vertical-align: middle; -} - -.ui-popup:not(.ui-content) > img:only-child, -.ui-popup:not(.ui-content) > .ui-btn-left:first-child + img:last-child, -.ui-popup:not(.ui-content) > .ui-btn-right:first-child + img:last-child { - -webkit-border-radius: inherit; - border-radius: inherit; -} - -.ui-popup iframe { - vertical-align: middle; -} - -.ui-popup > .ui-btn-left, -.ui-popup > .ui-btn-right { - position: absolute; - top: -11px; - margin: 0; - z-index: 1101; -} - -.ui-popup > .ui-btn-left { - left: -11px; -} - -.ui-popup > .ui-btn-right { - right: -11px; -} - - -@-webkit-keyframes fadein { - from { - opacity: 0; - } - - to { - opacity: 1; - } -} - -@-moz-keyframes fadein { - from { - opacity: 0; - } - - to { - opacity: 1; - } -} - -@keyframes fadein { - from { - opacity: 0; - } - - to { - opacity: 1; - } -} - -@-webkit-keyframes fadeout { - from { - opacity: 1; - } - - to { - opacity: 0; - } -} - -@-moz-keyframes fadeout { - from { - opacity: 1; - } - - to { - opacity: 0; - } -} - -@keyframes fadeout { - from { - opacity: 1; - } - - to { - opacity: 0; - } -} - -.fade.out { - opacity: 0; - -webkit-animation-duration: 125ms; - -webkit-animation-name: fadeout; - -moz-animation-duration: 125ms; - -moz-animation-name: fadeout; - animation-duration: 125ms; - animation-name: fadeout; -} - -.fade.in { - opacity: 1; - -webkit-animation-duration: 225ms; - -webkit-animation-name: fadein; - -moz-animation-duration: 225ms; - -moz-animation-name: fadein; - animation-duration: 225ms; - animation-name: fadein; -} - - -/* Dimensions related to the popup arrow ------------------------------------------------------------------------------------------------------------*/ -/* desired triangle height: 10px */ - -/** - * guide for the arrow - its width, height, and offset are theme-dependent and - * should be expessed as left, right, top, bottom, so that the element bearing - * such a class becomes stretched inside its parent position: relative element. - * The left/top/right/bottom specified below should reflect the corresponding - * border radii and so it leaves room for the shadow: - * ..--------------------.. - * ." ^ top ". - * / v \ - * | +------------------+ | - * | | | | - * | left| |right| - * |<--->| |<--->| - * | +------------------+ | - * \ ^ / - * `. v bottom .' - * ""--------------------"" - * The idea is that the top/left of the arrow container box does not move to a - * coordinate smaller than the top/left of the guide and the right/bottom of - * the arrow container box does not move to a coordinate larger than the - * bottom/right of the guide. This will help us avoid the following situation: - * ..--------------------.. - * ." ^ top ". - * /|/ v \ - * / | +------------------+ | - * \ | | | | - * \| left| |right| - * |<--->| |<--->| - * | +------------------+ | - * \ ^ / - * `. v bottom .' - * ""--------------------"" - * The arrow should not receive a top/left coordinate such that it is too close - * to one of the corners, because then at first the shadow of the arrow and, - * given a coordinate even closer to the corner, even the body of the arrow will - * "stick out" of the corner of the popup. The guide provides a hint to the - * arrow positioning code as to which range of values is acceptable for the - * arrow container's top/left coordinate. - **/ - -.ui-popup-arrow-container { - width: 20px; - height: 20px; -} - - /* aside from the "infinities" (-1000,2000), triangle height is used */ - .ui-popup-arrow-container.ui-popup-arrow-l { - left: -10px; - clip: rect(-1000px,10px,2000px,-1000px); - } - - .ui-popup-arrow-container.ui-popup-arrow-t { - top: -10px; - clip: rect(-1000px,2000px,10px,-1000px); - } - - .ui-popup-arrow-container.ui-popup-arrow-r { - right: -10px; - clip: rect(-1000px,2000px,2000px,10px); - } - - .ui-popup-arrow-container.ui-popup-arrow-b { - bottom: -10px; - clip: rect(10px,2000px,1000px,-1000px); - } - - /** - * For each side, the arrow is twice the desired size and its corner is aligned - * with the edge of the container: - * - * /\ /\ +----+ /\ - * / \ / \ | /\ |top / \ - * +----+ \ / +----+ +-->|/ \| / \ - * left| / | \ / | \ |right | | | / \ - * |/ | \ / | \| | /| |\ / \ - * |\ | / \ | /| | / +----+ \ \ +----+ / - * | \ | / \ | / | | \ / \| |/ - * +----+ / \ +----+ | \ / | | - * ^ \ / \ / ^ | \ / +->|\ /| - * | \/ \/ | | \ / | | \/ |bottom - * | | | \/ | +----+ - * +-------------------+--------+-----------+ - * | - * arrow container - * (clips arrow) - **/ - - .ui-popup-arrow-container .ui-popup-arrow { - /* (4*desired triangle height)/sqrt(2) - does not account for border - centred within the outer rectangle */ - width: 28.284271247px; - height: 28.284271247px; - border-width: 1px; - border-style: solid; - } - - .ui-popup-arrow-container.ui-popup-arrow-t .ui-popup-arrow { - left: -4.142135623px; - top: 5.857864376px; - } - - .ui-popup-arrow-container.ui-popup-arrow-b .ui-popup-arrow { - left: -4.142135623px; - top: -14.142135623px; - } - - .ui-popup-arrow-container.ui-popup-arrow-l .ui-popup-arrow { - left: 5.857864376px; - top: -4.142135623px; - } - - .ui-popup-arrow-container.ui-popup-arrow-r .ui-popup-arrow { - left: -14.142135623px; - top: -4.142135623px; - } - - /* Fix rotation center for oldIE - see http://www.useragentman.com/IETransformsTranslator/ */ - .ui-popup-arrow-container.ui-popup-arrow-t.ie .ui-popup-arrow { - margin-left: -5.857864376269049px; - margin-top: -7.0710678118654755px; - } - - .ui-popup-arrow-container.ui-popup-arrow-b.ie .ui-popup-arrow { - margin-left: -5.857864376269049px; - margin-top: -4.142135623730951px; - } - - .ui-popup-arrow-container.ui-popup-arrow-l.ie .ui-popup-arrow { - margin-left: -7.0710678118654755px; - margin-top: -5.857864376269049px; - } - - .ui-popup-arrow-container.ui-popup-arrow-r.ie .ui-popup-arrow { - margin-left: -4.142135623730951px; - margin-top: -5.857864376269049px; - } - -/* structure */ -.ui-popup > .ui-popup-arrow-guide { - position: absolute; - left: 0; - right: 0; - top: 0; - bottom: 0; - visibility: hidden; -} - -.ui-popup-arrow-container { - position: absolute; -} - -.ui-popup-arrow { - -webkit-transform: rotate(45deg); - -moz-transform: rotate(45deg); - -ms-transform: rotate(45deg); - transform: rotate(45deg); - position: absolute; - overflow: hidden; - box-sizing: border-box; -} - -.ui-popup-arrow-container.ie .ui-popup-arrow { - -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.7071067811865474, M12=-0.7071067811865477, M21=0.7071067811865477, M22=0.7071067811865474, SizingMethod='auto expand')"; - filter: progid:DXImageTransform.Microsoft.Matrix( M11=0.7071067811865474, M12=-0.7071067811865477, M21=0.7071067811865477, M22=0.7071067811865474, SizingMethod='auto expand'); -} - - - -/* Corner styling for dialogs and popups */ -.ui-corner-all > .ui-content:first-child { - -webkit-border-top-left-radius: inherit; - border-top-left-radius: inherit; - -webkit-border-top-right-radius: inherit; - border-top-right-radius: inherit; -} -.ui-corner-all > .ui-content:last-child { - -webkit-border-bottom-left-radius: inherit; - border-bottom-left-radius: inherit; - -webkit-border-bottom-right-radius: inherit; - border-bottom-right-radius: inherit; -} - - -/* Popup arrow */ -.ui-popup.ui-corner-all > .ui-popup-arrow-guide { - left: .6em /*{global-radii-blocks}*/; - right: .6em /*{global-radii-blocks}*/; - top: .6em /*{global-radii-blocks}*/; - bottom: .6em /*{global-radii-blocks}*/; -} - - -/* Used for hiding elements by the filterable widget. You can also use this class to hide list items or buttons in controlgroups; this ensures correct corner styling. */ -.ui-screen-hidden { - display: none !important; -} \ No newline at end of file +.ui-mobile [data-role=dialog]{top:0;left:0;width:100%;min-height:100%;position:absolute;border:0;background:#fff}.ui-popup{background:#fff}.ui-popup-open .ui-footer-fixed,.ui-popup-open .ui-header-fixed{position:absolute!important}.ui-popup-screen{background-image:url(data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==);top:0;left:0;right:0;bottom:1px;position:absolute;filter:Alpha(Opacity=0);opacity:0;z-index:1099}.ui-popup-screen.in{opacity:.5;filter:Alpha(Opacity=50)}.ui-popup-screen.out{opacity:0;filter:Alpha(Opacity=0)}.ui-popup-container{z-index:1100;display:inline-block;position:absolute;padding:0;outline:0}.ui-popup{position:relative}.ui-popup.ui-body-inherit{border-width:1px;border-style:solid}.ui-popup-hidden{left:0;top:0;position:absolute!important;visibility:hidden}.ui-popup-truncate{height:1px;width:1px;margin:-1px;overflow:hidden;clip:rect(1px,1px,1px,1px)}.ui-popup>h1,.ui-popup>h2,.ui-popup>h3,.ui-popup>h4,.ui-popup>h5,.ui-popup>h6,.ui-popup>p,.ui-popup>span{margin:.5em .4375em}.ui-popup .ui-content,.ui-popup.ui-content{overflow:visible}.ui-popup>.ui-header{border-top-width:0}.ui-popup>.ui-footer{border-bottom-width:0}.ui-popup>span{display:block}.ui-popup-container .ui-content>h1,.ui-popup-container .ui-content>h2,.ui-popup-container .ui-content>h3,.ui-popup-container .ui-content>h4,.ui-popup-container .ui-content>h5,.ui-popup-container .ui-content>h6,.ui-popup-container .ui-content>p{margin:.5em 0}.ui-popup-container .ui-content>span{margin:0}.ui-popup-container .ui-content>h1:first-child,.ui-popup-container .ui-content>h2:first-child,.ui-popup-container .ui-content>h3:first-child,.ui-popup-container .ui-content>h4:first-child,.ui-popup-container .ui-content>h5:first-child,.ui-popup-container .ui-content>h6:first-child,.ui-popup-container .ui-content>p:first-child{margin-top:0}.ui-popup-container .ui-content>h1:last-child,.ui-popup-container .ui-content>h2:last-child,.ui-popup-container .ui-content>h3:last-child,.ui-popup-container .ui-content>h4:last-child,.ui-popup-container .ui-content>h5:last-child,.ui-popup-container .ui-content>h6:last-child,.ui-popup-container .ui-content>p:last-child{margin-bottom:0}.ui-popup>img{max-width:100%;max-height:100%;vertical-align:middle}.ui-popup:not(.ui-content)>.ui-btn-left:first-child+img:last-child,.ui-popup:not(.ui-content)>.ui-btn-right:first-child+img:last-child,.ui-popup:not(.ui-content)>img:only-child{-webkit-border-radius:inherit;border-radius:inherit}.ui-popup iframe{vertical-align:middle}.ui-popup>.ui-btn-left,.ui-popup>.ui-btn-right{position:absolute;top:-11px;margin:0;z-index:1101}.ui-popup>.ui-btn-left{left:-11px}.ui-popup>.ui-btn-right{right:-11px}@-webkit-keyframes fadein{from{opacity:0}to{opacity:1}}@keyframes fadein{from{opacity:0}to{opacity:1}}@-webkit-keyframes fadeout{from{opacity:1}to{opacity:0}}@keyframes fadeout{from{opacity:1}to{opacity:0}}.fade.out{opacity:0;-moz-animation-duration:125ms;-moz-animation-name:fadeout;-webkit-animation-duration:125ms;animation-duration:125ms;-webkit-animation-name:fadeout;animation-name:fadeout}.fade.in{opacity:1;-moz-animation-duration:225ms;-moz-animation-name:fadein;-webkit-animation-duration:225ms;animation-duration:225ms;-webkit-animation-name:fadein;animation-name:fadein}.ui-popup-arrow-container{width:20px;height:20px;position:absolute}.ui-popup-arrow-container.ui-popup-arrow-l{left:-10px;clip:rect(-1000px,10px,2000px,-1000px)}.ui-popup-arrow-container.ui-popup-arrow-t{top:-10px;clip:rect(-1000px,2000px,10px,-1000px)}.ui-popup-arrow-container.ui-popup-arrow-r{right:-10px;clip:rect(-1000px,2000px,2000px,10px)}.ui-popup-arrow-container.ui-popup-arrow-b{bottom:-10px;clip:rect(10px,2000px,1000px,-1000px)}.ui-popup-arrow-container .ui-popup-arrow{width:28.28px;height:28.28px;border-width:1px;border-style:solid}.ui-popup-arrow-container.ui-popup-arrow-t .ui-popup-arrow{left:-4.14px;top:5.86px}.ui-popup-arrow-container.ui-popup-arrow-b .ui-popup-arrow{left:-4.14px;top:-14.14px}.ui-popup-arrow-container.ui-popup-arrow-l .ui-popup-arrow{left:5.86px;top:-4.14px}.ui-popup-arrow-container.ui-popup-arrow-r .ui-popup-arrow{left:-14.14px;top:-4.14px}.ui-popup-arrow-container.ui-popup-arrow-t.ie .ui-popup-arrow{margin-left:-5.86px;margin-top:-7.07px}.ui-popup-arrow-container.ui-popup-arrow-b.ie .ui-popup-arrow{margin-left:-5.86px;margin-top:-4.14px}.ui-popup-arrow-container.ui-popup-arrow-l.ie .ui-popup-arrow{margin-left:-7.07px;margin-top:-5.86px}.ui-popup-arrow-container.ui-popup-arrow-r.ie .ui-popup-arrow{margin-left:-4.14px;margin-top:-5.86px}.ui-popup>.ui-popup-arrow-guide{position:absolute;left:0;right:0;top:0;bottom:0;visibility:hidden}.ui-popup-arrow{-webkit-transform:rotate(45deg);transform:rotate(45deg);position:absolute;overflow:hidden;-webkit-box-sizing:border-box;box-sizing:border-box}.ui-popup-arrow-container.ie .ui-popup-arrow{-ms-filter:"progid:DXImageTransform.Microsoft.Matrix(M11=0.7071067811865474, M12=-0.7071067811865477, M21=0.7071067811865477, M22=0.7071067811865474, SizingMethod='auto expand')";filter:progid:DXImageTransform.Microsoft.Matrix( M11=.7071067811865474, M12=-.7071067811865477, M21=.7071067811865477, M22=.7071067811865474, SizingMethod='auto expand')}.ui-corner-all>.ui-content:first-child{-webkit-border-top-left-radius:inherit;border-top-left-radius:inherit;-webkit-border-top-right-radius:inherit;border-top-right-radius:inherit}.ui-corner-all>.ui-content:last-child{-webkit-border-bottom-left-radius:inherit;border-bottom-left-radius:inherit;-webkit-border-bottom-right-radius:inherit;border-bottom-right-radius:inherit}.ui-popup.ui-corner-all>.ui-popup-arrow-guide{left:.6em;right:.6em;top:.6em;bottom:.6em}.ui-screen-hidden{display:none!important} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.js b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.js index f325931b89..41770b4fe6 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.js +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.popup.js @@ -1,1284 +1 @@ -define(['jqmwidget'], function () { - - (function ($, undefined) { - var props = { - "animation": {}, - "transition": {} - }, - testElement = document.createElement("a"), - vendorPrefixes = ["", "webkit-", "moz-", "o-"]; - - $.each(["animation", "transition"], function (i, test) { - - // Get correct name for test - var testName = (i === 0) ? test + "-" + "name" : test; - - $.each(vendorPrefixes, function (j, prefix) { - if (testElement.style[$.camelCase(prefix + testName)] !== undefined) { - props[test]["prefix"] = prefix; - return false; - } - }); - - // Set event and duration names for later use - props[test]["duration"] = - $.camelCase(props[test]["prefix"] + test + "-" + "duration"); - props[test]["event"] = - $.camelCase(props[test]["prefix"] + test + "-" + "end"); - - // All lower case if not a vendor prop - if (props[test]["prefix"] === "") { - props[test]["event"] = props[test]["event"].toLowerCase(); - } - }); - - // Remove the testElement - $(testElement).remove(); - - // Animation complete callback - $.fn.animationComplete = function (callback, type, fallbackTime) { - var timer, duration, - that = this, - eventBinding = function () { - - // Clear the timer so we don't call callback twice - clearTimeout(timer); - callback.apply(this, arguments); - }, - animationType = (!type || type === "animation") ? "animation" : "transition"; - - // If a fallback time was not passed set one - if (fallbackTime === undefined) { - - // Make sure the was not bound to document before checking .css - if ($(this).context !== document) { - - // Parse the durration since its in second multiple by 1000 for milliseconds - // Multiply by 3 to make sure we give the animation plenty of time. - duration = parseFloat( - $(this).css(props[animationType].duration) - ) * 3000; - } - - // If we could not read a duration use the default - if (duration === 0 || duration === undefined || isNaN(duration)) { - duration = $.fn.animationComplete.defaultDuration; - } - } - - // Sets up the fallback if event never comes - timer = setTimeout(function () { - $(that).off(props[animationType].event, eventBinding); - callback.apply(that); - }, duration); - - // Bind the event - return $(this).one(props[animationType].event, eventBinding); - }; - - // Allow default callback to be configured on mobileInit - $.fn.animationComplete.defaultDuration = 1000; - })(jQuery); - - (function ($, undefined) { - - function fitSegmentInsideSegment(windowSize, segmentSize, offset, desired) { - var returnValue = desired; - - if (windowSize < segmentSize) { - // Center segment if it's bigger than the window - returnValue = offset + (windowSize - segmentSize) / 2; - } else { - // Otherwise center it at the desired coordinate while keeping it completely inside the window - returnValue = Math.min(Math.max(offset, desired - segmentSize / 2), offset + windowSize - segmentSize); - } - - return returnValue; - } - - function getWindowCoordinates(theWindow) { - return { - x: theWindow.scrollLeft(), - y: theWindow.scrollTop(), - cx: (theWindow[0].innerWidth || theWindow.width()), - cy: (theWindow[0].innerHeight || theWindow.height()) - }; - } - - // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 - // allows for inclusion of IE 6+, including Windows Mobile 7 - $.extend($.mobile, { browser: {} }); - $.mobile.browser.oldIE = (function () { - var v = 3, - div = document.createElement("div"), - a = div.all || []; - - do { - div.innerHTML = ""; - } while (a[0]); - - return v > 4 ? v : !v; - })(); - - $.widget("mobile.popup", { - options: { - wrapperClass: null, - theme: null, - overlayTheme: null, - shadow: true, - corners: true, - transition: "none", - positionTo: "origin", - tolerance: null, - closeLinkSelector: "a[data-rel='back']", - closeLinkEvents: "click.popup", - navigateEvents: "navigate.popup", - closeEvents: "navigate.popup pagebeforechange.popup", - dismissible: true, - enhanced: false, - - // NOTE Windows Phone 7 has a scroll position caching issue that - // requires us to disable popup history management by default - // https://github.com/jquery/jquery-mobile/issues/4784 - // - // NOTE this option is modified in _create! - history: !$.mobile.browser.oldIE - }, - - // When the user depresses the mouse/finger on an element inside the popup while the popup is - // open, we ignore resize events for a short while. This prevents #6961. - _handleDocumentVmousedown: function (theEvent) { - if (this._isOpen && $.contains(this._ui.container[0], theEvent.target)) { - this._ignoreResizeEvents(); - } - }, - - _create: function () { - var theElement = this.element, - myId = theElement.attr("id"), - currentOptions = this.options; - - // We need to adjust the history option to be false if there's no AJAX nav. - // We can't do it in the option declarations because those are run before - // it is determined whether there shall be AJAX nav. - currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; - - this._on(this.document, { - "mousedown": "_handleDocumentVmousedown" - }); - - // Define instance variables - $.extend(this, { - _scrollTop: 0, - _page: theElement.parents("div[data-role='page']"), - _ui: null, - _fallbackTransition: "", - _currentTransition: false, - _prerequisites: null, - _isOpen: false, - _tolerance: null, - _resizeData: null, - _ignoreResizeTo: 0, - _orientationchangeInProgress: false - }); - - if (this._page.length === 0) { - this._page = $("body"); - } - - if (currentOptions.enhanced) { - this._ui = { - container: theElement.parent(), - screen: theElement.parent().prev(), - placeholder: $(this.document[0].getElementById(myId + "-placeholder")) - }; - } else { - this._ui = this._enhance(theElement, myId); - this._applyTransition(currentOptions.transition); - } - this - ._setTolerance(currentOptions.tolerance) - ._ui.focusElement = this._ui.container; - - // Event handlers - this._on(this._ui.screen, { "click": "_eatEventAndClose" }); - this._on(this.window, { - orientationchange: $.proxy(this, "_handleWindowOrientationchange"), - resize: $.proxy(this, "_handleWindowResize") - }); - this._on(this.document, { "focusin": "_handleDocumentFocusIn" }); - }, - - _delay: function (handler, delay) { - function handlerProxy() { - return (typeof handler === "string" ? instance[handler] : handler) - .apply(instance, arguments); - } - var instance = this; - return setTimeout(handlerProxy, delay || 0); - }, - - _enhance: function (theElement, myId) { - var currentOptions = this.options, - wrapperClass = currentOptions.wrapperClass, - ui = { - screen: $("
"), - placeholder: $("
"), - container: $("
") - }, - fragment = this.document[0].createDocumentFragment(); - - fragment.appendChild(ui.screen[0]); - fragment.appendChild(ui.container[0]); - - if (myId) { - ui.screen.attr("id", myId + "-screen"); - ui.container.attr("id", myId + "-popup"); - ui.placeholder - .attr("id", myId + "-placeholder") - .html(""); - } - - // Apply the proto - this._page[0].appendChild(fragment); - // Leave a placeholder where the element used to be - ui.placeholder.insertAfter(theElement); - theElement - .detach() - .addClass("ui-popup " + - this._themeClassFromOption("ui-body-", currentOptions.theme) + " " + - (currentOptions.shadow ? "ui-overlay-shadow " : "") + - (currentOptions.corners ? "ui-corner-all " : "")) - .appendTo(ui.container); - - return ui; - }, - - _eatEventAndClose: function (theEvent) { - theEvent.preventDefault(); - theEvent.stopImmediatePropagation(); - if (this.options.dismissible) { - this.close(); - } - return false; - }, - - // Make sure the screen covers the entire document - CSS is sometimes not - // enough to accomplish this. - _resizeScreen: function () { - var screen = this._ui.screen, - popupHeight = this._ui.container.outerHeight(true), - screenHeight = screen.removeAttr("style").height(), - - // Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where - // the browser hangs if the screen covers the entire document :/ - documentHeight = this.document.height() - 1; - - if (screenHeight < documentHeight) { - screen.height(documentHeight); - } else if (popupHeight > screenHeight) { - screen.height(popupHeight); - } - }, - - _expectResizeEvent: function () { - var windowCoordinates = getWindowCoordinates(this.window); - - if (this._resizeData) { - if (windowCoordinates.x === this._resizeData.windowCoordinates.x && - windowCoordinates.y === this._resizeData.windowCoordinates.y && - windowCoordinates.cx === this._resizeData.windowCoordinates.cx && - windowCoordinates.cy === this._resizeData.windowCoordinates.cy) { - // timeout not refreshed - return false; - } else { - // clear existing timeout - it will be refreshed below - clearTimeout(this._resizeData.timeoutId); - } - } - - this._resizeData = { - timeoutId: this._delay("_resizeTimeout", 200), - windowCoordinates: windowCoordinates - }; - - return true; - }, - - _resizeTimeout: function () { - if (this._isOpen) { - if (!this._expectResizeEvent()) { - if (this._ui.container.hasClass("ui-popup-hidden")) { - // effectively rapid-open the popup while leaving the screen intact - this._ui.container.removeClass("ui-popup-hidden ui-popup-truncate"); - this.reposition({ positionTo: "window" }); - this._ignoreResizeEvents(); - } - - this._resizeScreen(); - this._resizeData = null; - this._orientationchangeInProgress = false; - } - } else { - this._resizeData = null; - this._orientationchangeInProgress = false; - } - }, - - _stopIgnoringResizeEvents: function () { - this._ignoreResizeTo = 0; - }, - - _ignoreResizeEvents: function () { - if (this._ignoreResizeTo) { - clearTimeout(this._ignoreResizeTo); - } - this._ignoreResizeTo = this._delay("_stopIgnoringResizeEvents", 1000); - }, - - _handleWindowResize: function (/* theEvent */) { - if (this._isOpen && this._ignoreResizeTo === 0) { - if ((this._expectResizeEvent() || this._orientationchangeInProgress) && - !this._ui.container.hasClass("ui-popup-hidden")) { - // effectively rapid-close the popup while leaving the screen intact - this._ui.container - .addClass("ui-popup-hidden ui-popup-truncate") - .removeAttr("style"); - } - } - }, - - _handleWindowOrientationchange: function (/* theEvent */) { - if (!this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0) { - this._expectResizeEvent(); - this._orientationchangeInProgress = true; - } - }, - - // When the popup is open, attempting to focus on an element that is not a - // child of the popup will redirect focus to the popup - _handleDocumentFocusIn: function (theEvent) { - var target, - targetElement = theEvent.target, - ui = this._ui; - - if (!this._isOpen) { - return; - } - - if (targetElement !== ui.container[0]) { - target = $(targetElement); - if (!$.contains(ui.container[0], targetElement)) { - $(this.document[0].activeElement).one("focus", $.proxy(function () { - this._safelyBlur(targetElement); - }, this)); - ui.focusElement.focus(); - theEvent.preventDefault(); - theEvent.stopImmediatePropagation(); - return false; - } else if (ui.focusElement[0] === ui.container[0]) { - ui.focusElement = target; - } - } - - this._ignoreResizeEvents(); - }, - - _themeClassFromOption: function (prefix, value) { - return (value ? (value === "none" ? "" : (prefix + value)) : (prefix + "inherit")); - }, - - _applyTransition: function (value) { - if (value) { - this._ui.container.removeClass(this._fallbackTransition); - if (value !== "none") { - this._fallbackTransition = $.mobile._maybeDegradeTransition(value); - if (this._fallbackTransition === "none") { - this._fallbackTransition = ""; - } - this._ui.container.addClass(this._fallbackTransition); - } - } - - return this; - }, - - _setOptions: function (newOptions) { - var currentOptions = this.options, - theElement = this.element, - screen = this._ui.screen; - - if (newOptions.wrapperClass !== undefined) { - this._ui.container - .removeClass(currentOptions.wrapperClass) - .addClass(newOptions.wrapperClass); - } - - if (newOptions.theme !== undefined) { - theElement - .removeClass(this._themeClassFromOption("ui-body-", currentOptions.theme)) - .addClass(this._themeClassFromOption("ui-body-", newOptions.theme)); - } - - if (newOptions.overlayTheme !== undefined) { - screen - .removeClass(this._themeClassFromOption("ui-overlay-", currentOptions.overlayTheme)) - .addClass(this._themeClassFromOption("ui-overlay-", newOptions.overlayTheme)); - - if (this._isOpen) { - screen.addClass("in"); - } - } - - if (newOptions.shadow !== undefined) { - theElement.toggleClass("ui-overlay-shadow", newOptions.shadow); - } - - if (newOptions.corners !== undefined) { - theElement.toggleClass("ui-corner-all", newOptions.corners); - } - - if (newOptions.transition !== undefined) { - if (!this._currentTransition) { - this._applyTransition(newOptions.transition); - } - } - - if (newOptions.tolerance !== undefined) { - this._setTolerance(newOptions.tolerance); - } - - if (newOptions.disabled !== undefined) { - if (newOptions.disabled) { - this.close(); - } - } - - return this._super(newOptions); - }, - - _setTolerance: function (value) { - var tol = { t: 30, r: 15, b: 30, l: 15 }, - ar; - - if (value !== undefined) { - ar = String(value).split(","); - - $.each(ar, function (idx, val) { ar[idx] = parseInt(val, 10); }); - - switch (ar.length) { - // All values are to be the same - case 1: - if (!isNaN(ar[0])) { - tol.t = tol.r = tol.b = tol.l = ar[0]; - } - break; - - // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance - case 2: - if (!isNaN(ar[0])) { - tol.t = tol.b = ar[0]; - } - if (!isNaN(ar[1])) { - tol.l = tol.r = ar[1]; - } - break; - - // The array contains values in the order top, right, bottom, left - case 4: - if (!isNaN(ar[0])) { - tol.t = ar[0]; - } - if (!isNaN(ar[1])) { - tol.r = ar[1]; - } - if (!isNaN(ar[2])) { - tol.b = ar[2]; - } - if (!isNaN(ar[3])) { - tol.l = ar[3]; - } - break; - - default: - break; - } - } - - this._tolerance = tol; - return this; - }, - - _clampPopupWidth: function (infoOnly) { - var menuSize, - windowCoordinates = getWindowCoordinates(this.window), - // rectangle within which the popup must fit - rectangle = { - x: this._tolerance.l, - y: windowCoordinates.y + this._tolerance.t, - cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, - cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b - }; - - if (!infoOnly) { - // Clamp the width of the menu before grabbing its size - this._ui.container.css("max-width", rectangle.cx); - } - - menuSize = { - cx: this._ui.container.outerWidth(true), - cy: this._ui.container.outerHeight(true) - }; - - return { rc: rectangle, menuSize: menuSize }; - }, - - _calculateFinalLocation: function (desired, clampInfo) { - var returnValue, - rectangle = clampInfo.rc, - menuSize = clampInfo.menuSize; - - // Center the menu over the desired coordinates, while not going outside - // the window tolerances. This will center wrt. the window if the popup is - // too large. - returnValue = { - left: fitSegmentInsideSegment(rectangle.cx, menuSize.cx, rectangle.x, desired.x), - top: fitSegmentInsideSegment(rectangle.cy, menuSize.cy, rectangle.y, desired.y) - }; - - // Make sure the top of the menu is visible - returnValue.top = Math.max(0, returnValue.top); - - // If the height of the menu is smaller than the height of the document - // align the bottom with the bottom of the document - - returnValue.top -= Math.min(returnValue.top, - Math.max(0, returnValue.top + menuSize.cy - this.document.height())); - - return returnValue; - }, - - // Try and center the overlay over the given coordinates - _placementCoords: function (desired) { - return this._calculateFinalLocation(desired, this._clampPopupWidth()); - }, - - _createPrerequisites: function (screenPrerequisite, containerPrerequisite, whenDone) { - var prerequisites, - self = this; - - // It is important to maintain both the local variable prerequisites and - // self._prerequisites. The local variable remains in the closure of the - // functions which call the callbacks passed in. The comparison between the - // local variable and self._prerequisites is necessary, because once a - // function has been passed to .animationComplete() it will be called next - // time an animation completes, even if that's not the animation whose end - // the function was supposed to catch (for example, if an abort happens - // during the opening animation, the .animationComplete handler is not - // called for that animation anymore, but the handler remains attached, so - // it is called the next time the popup is opened - making it stale. - // Comparing the local variable prerequisites to the widget-level variable - // self._prerequisites ensures that callbacks triggered by a stale - // .animationComplete will be ignored. - - prerequisites = { - screen: $.Deferred(), - container: $.Deferred() - }; - - prerequisites.screen.then(function () { - if (prerequisites === self._prerequisites) { - screenPrerequisite(); - } - }); - - prerequisites.container.then(function () { - if (prerequisites === self._prerequisites) { - containerPrerequisite(); - } - }); - - Promise.all([prerequisites.screen, prerequisites.container]).then(function () { - if (prerequisites === self._prerequisites) { - self._prerequisites = null; - whenDone(); - } - }); - - self._prerequisites = prerequisites; - }, - - _animate: function (args) { - // NOTE before removing the default animation of the screen - // this had an animate callback that would resolve the deferred - // now the deferred is resolved immediately - // TODO remove the dependency on the screen deferred - this._ui.screen - .removeClass(args.classToRemove) - .addClass(args.screenClassToAdd); - - args.prerequisites.screen.resolve(); - - if (args.transition && args.transition !== "none") { - if (args.applyTransition) { - this._applyTransition(args.transition); - } - if (this._fallbackTransition) { - this._ui.container - .addClass(args.containerClassToAdd) - .removeClass(args.classToRemove) - .animationComplete($.proxy(args.prerequisites.container, "resolve")); - return; - } - } - this._ui.container.removeClass(args.classToRemove); - args.prerequisites.container.resolve(); - }, - - // The desired coordinates passed in will be returned untouched if no reference element can be identified via - // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid - // x and y coordinates by specifying the center middle of the window if the coordinates are absent. - // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector - _desiredCoords: function (openOptions) { - var offset, - dst = null, - windowCoordinates = getWindowCoordinates(this.window), - x = openOptions.x, - y = openOptions.y, - pTo = openOptions.positionTo; - - // Establish which element will serve as the reference - if (pTo && pTo !== "origin") { - if (pTo === "window") { - x = windowCoordinates.cx / 2 + windowCoordinates.x; - y = windowCoordinates.cy / 2 + windowCoordinates.y; - } else { - try { - dst = $(pTo); - } catch (err) { - dst = null; - } - if (dst) { - dst.filter(":visible"); - if (dst.length === 0) { - dst = null; - } - } - } - } - - // If an element was found, center over it - if (dst) { - offset = dst.offset(); - x = offset.left + dst.outerWidth() / 2; - y = offset.top + dst.outerHeight() / 2; - } - - // Make sure x and y are valid numbers - center over the window - if ($.type(x) !== "number" || isNaN(x)) { - x = windowCoordinates.cx / 2 + windowCoordinates.x; - } - if ($.type(y) !== "number" || isNaN(y)) { - y = windowCoordinates.cy / 2 + windowCoordinates.y; - } - - return { x: x, y: y }; - }, - - _reposition: function (openOptions) { - // We only care about position-related parameters for repositioning - openOptions = { - x: openOptions.x, - y: openOptions.y, - positionTo: openOptions.positionTo - }; - this._trigger("beforeposition", undefined, openOptions); - this._ui.container.offset(this._placementCoords(this._desiredCoords(openOptions))); - }, - - reposition: function (openOptions) { - if (this._isOpen) { - this._reposition(openOptions); - } - }, - - _safelyBlur: function (currentElement) { - if (currentElement !== this.window[0] && - currentElement.nodeName.toLowerCase() !== "body") { - $(currentElement).blur(); - } - }, - - _openPrerequisitesComplete: function () { - var id = this.element.attr("id"); - - this._ui.container.addClass("ui-popup-active"); - this._isOpen = true; - this._resizeScreen(); - - // Check to see if currElement is not a child of the container. If it's not, blur - if (!$.contains(this._ui.container[0], this.document[0].activeElement)) { - this._safelyBlur(this.document[0].activeElement); - } - this._ignoreResizeEvents(); - if (id) { - this.document.find("[aria-haspopup='true'][aria-owns='" + id + "']").attr("aria-expanded", true); - } - this._trigger("afteropen"); - }, - - _open: function (options) { - var openOptions = $.extend({}, this.options, options), - // TODO move blacklist to private method - androidBlacklist = (function () { - var ua = navigator.userAgent, - // Rendering engine is Webkit, and capture major version - wkmatch = ua.match(/AppleWebKit\/([0-9\.]+)/), - wkversion = !!wkmatch && wkmatch[1], - androidmatch = ua.match(/Android (\d+(?:\.\d+))/), - andversion = !!androidmatch && androidmatch[1], - chromematch = ua.indexOf("Chrome") > -1; - - // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. - if (androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch) { - return true; - } - return false; - }()); - - // Count down to triggering "popupafteropen" - we have two prerequisites: - // 1. The popup window animation completes (container()) - // 2. The screen opacity animation completes (screen()) - this._createPrerequisites( - $.noop, - $.noop, - $.proxy(this, "_openPrerequisitesComplete")); - - this._currentTransition = openOptions.transition; - this._applyTransition(openOptions.transition); - - this._ui.screen.removeClass("ui-screen-hidden"); - this._ui.container.removeClass("ui-popup-truncate"); - - // Give applications a chance to modify the contents of the container before it appears - this._reposition(openOptions); - - this._ui.container.removeClass("ui-popup-hidden"); - - if (this.options.overlayTheme && androidBlacklist) { - /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 - This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): - https://github.com/jquery/jquery-mobile/issues/4816 - https://github.com/jquery/jquery-mobile/issues/4844 - https://github.com/jquery/jquery-mobile/issues/4874 - */ - - // TODO sort out why this._page isn't working - this.element.closest(".ui-page").addClass("ui-popup-open"); - } - this._animate({ - additionalCondition: true, - transition: openOptions.transition, - classToRemove: "", - screenClassToAdd: "in", - containerClassToAdd: "in", - applyTransition: false, - prerequisites: this._prerequisites - }); - }, - - _closePrerequisiteScreen: function () { - this._ui.screen - .removeClass("out") - .addClass("ui-screen-hidden"); - }, - - _closePrerequisiteContainer: function () { - this._ui.container - .removeClass("reverse out") - .addClass("ui-popup-hidden ui-popup-truncate") - .removeAttr("style"); - }, - - _closePrerequisitesDone: function () { - var container = this._ui.container, - id = this.element.attr("id"); - - // remove the global mutex for popups - $.mobile.popup.active = undefined; - - // Blur elements inside the container, including the container - $(":focus", container[0]).add(container[0]).blur(); - - if (id) { - this.document.find("[aria-haspopup='true'][aria-owns='" + id + "']").attr("aria-expanded", false); - } - - // alert users that the popup is closed - this._trigger("afterclose"); - }, - - _close: function (immediate) { - this._ui.container.removeClass("ui-popup-active"); - this._page.removeClass("ui-popup-open"); - - this._isOpen = false; - - // Count down to triggering "popupafterclose" - we have two prerequisites: - // 1. The popup window reverse animation completes (container()) - // 2. The screen opacity animation completes (screen()) - this._createPrerequisites( - $.proxy(this, "_closePrerequisiteScreen"), - $.proxy(this, "_closePrerequisiteContainer"), - $.proxy(this, "_closePrerequisitesDone")); - - this._animate({ - additionalCondition: this._ui.screen.hasClass("in"), - transition: (immediate ? "none" : (this._currentTransition)), - classToRemove: "in", - screenClassToAdd: "out", - containerClassToAdd: "reverse out", - applyTransition: true, - prerequisites: this._prerequisites - }); - }, - - _unenhance: function () { - if (this.options.enhanced) { - return; - } - - // Put the element back to where the placeholder was and remove the "ui-popup" class - this._setOptions({ theme: $.mobile.popup.prototype.options.theme }); - this.element - // Cannot directly insertAfter() - we need to detach() first, because - // insertAfter() will do nothing if the payload div was not attached - // to the DOM at the time the widget was created, and so the payload - // will remain inside the container even after we call insertAfter(). - // If that happens and we remove the container a few lines below, we - // will cause an infinite recursion - #5244 - .detach() - .insertAfter(this._ui.placeholder) - .removeClass("ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit"); - this._ui.screen.remove(); - this._ui.container.remove(); - this._ui.placeholder.remove(); - }, - - _destroy: function () { - if ($.mobile.popup.active === this) { - this.element.one("popupafterclose", $.proxy(this, "_unenhance")); - this.close(); - } else { - this._unenhance(); - } - - return this; - }, - - _closePopup: function (theEvent, data) { - var parsedDst, toUrl, - currentOptions = this.options, - immediate = false; - - if ((theEvent && theEvent.isDefaultPrevented()) || $.mobile.popup.active !== this) { - return; - } - - // restore location on screen - window.scrollTo(0, this._scrollTop); - - if (theEvent && theEvent.type === "pagebeforechange" && data) { - // Determine whether we need to rapid-close the popup, or whether we can - // take the time to run the closing transition - if (typeof data.toPage === "string") { - parsedDst = data.toPage; - } else { - parsedDst = data.toPage.data("url"); - } - parsedDst = $.mobile.path.parseUrl(parsedDst); - toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; - - if (this._myUrl !== $.mobile.path.makeUrlAbsolute(toUrl)) { - // Going to a different page - close immediately - immediate = true; - } else { - theEvent.preventDefault(); - } - } - - // remove nav bindings - this.window.off(currentOptions.closeEvents); - // unbind click handlers added when history is disabled - this.element.off(currentOptions.closeLinkEvents, currentOptions.closeLinkSelector); - - this._close(immediate); - }, - - // any navigation event after a popup is opened should close the popup - // NOTE the pagebeforechange is bound to catch navigation events that don't - // alter the url (eg, dialogs from popups) - _bindContainerClose: function () { - this.window - .on(this.options.closeEvents, $.proxy(this, "_closePopup")); - }, - - widget: function () { - return this._ui.container; - }, - - // TODO no clear deliniation of what should be here and - // what should be in _open. Seems to be "visual" vs "history" for now - open: function (options) { - var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory, - self = this, - currentOptions = this.options; - - // make sure open is idempotent - if ($.mobile.popup.active || currentOptions.disabled) { - return this; - } - - // set the global popup mutex - $.mobile.popup.active = this; - this._scrollTop = this.window.scrollTop(); - - // if history alteration is disabled close on navigate events - // and leave the url as is - if (!(currentOptions.history)) { - self._open(options); - self._bindContainerClose(); - - // When histoy is disabled we have to grab the data-rel - // back link clicks so we can close the popup instead of - // relying on history to do it for us - self.element - .on(currentOptions.closeLinkEvents, currentOptions.closeLinkSelector, function (theEvent) { - self.close(); - theEvent.preventDefault(); - }); - - return this; - } - - // cache some values for min/readability - urlHistory = $.mobile.navigate.history; - hashkey = $.mobile.dialogHashKey; - activePage = $.mobile.activePage; - currentIsDialog = (activePage ? activePage.hasClass("ui-dialog") : false); - this._myUrl = url = urlHistory.getActive().url; - hasHash = (url.indexOf(hashkey) > -1) && !currentIsDialog && (urlHistory.activeIndex > 0); - - if (hasHash) { - self._open(options); - self._bindContainerClose(); - return this; - } - - // if the current url has no dialog hash key proceed as normal - // otherwise, if the page is a dialog simply tack on the hash key - if (url.indexOf(hashkey) === -1 && !currentIsDialog) { - url = url + (url.indexOf("#") > -1 ? hashkey : "#" + hashkey); - } else { - url = $.mobile.path.parseLocation().hash + hashkey; - } - - // swallow the the initial navigation event, and bind for the next - this.window.one("beforenavigate", function (theEvent) { - theEvent.preventDefault(); - self._open(options); - self._bindContainerClose(); - }); - - this.urlAltered = true; - $.mobile.navigate(url, { role: "dialog" }); - - return this; - }, - - close: function () { - // make sure close is idempotent - if ($.mobile.popup.active !== this) { - return this; - } - - this._scrollTop = this.window.scrollTop(); - - if (this.options.history && this.urlAltered) { - $.mobile.pageContainer.pagecontainer("back"); - this.urlAltered = false; - } else { - // simulate the nav bindings having fired - this._closePopup(); - } - - return this; - } - }); - - // TODO this can be moved inside the widget - $.mobile.popup.handleLink = function ($link) { - var offset, - path = $.mobile.path, - - // NOTE make sure to get only the hash from the href because ie7 (wp7) - // returns the absolute href in this case ruining the element selection - popup = $(path.hashToSelector(path.parseUrl($link.attr("href")).hash)).first(); - - if (popup.length > 0 && popup.data("mobile-popup")) { - offset = $link.offset(); - popup.popup("open", { - x: offset.left + $link.outerWidth() / 2, - y: offset.top + $link.outerHeight() / 2, - transition: $link.data("transition"), - positionTo: $link.data("position-to") - }); - } - - //remove after delay - setTimeout(function () { - $link.removeClass($.mobile.activeBtnClass); - }, 300); - }; - - // TODO move inside _create - $(document).on("pagebeforechange", function (theEvent, data) { - if (data.options.role === "popup") { - $.mobile.popup.handleLink(data.options.link); - theEvent.preventDefault(); - } - }); - - })(jQuery); - - - (function ($, undefined) { - - var ieHack = ($.mobile.browser.oldIE && $.mobile.browser.oldIE <= 8), - uiTemplate = $( - "
" + - "
" + - "
" + - "
" - ); - - function getArrow() { - var clone = uiTemplate.clone(), - gd = clone.eq(0), - ct = clone.eq(1), - ar = ct.children(); - - return { arEls: ct.add(gd), gd: gd, ct: ct, ar: ar }; - } - - $.widget("mobile.popup", $.mobile.popup, { - options: { - - arrow: "" - }, - - _create: function () { - var ar, - ret = this._super(); - - if (this.options.arrow) { - this._ui.arrow = ar = this._addArrow(); - } - - return ret; - }, - - _addArrow: function () { - var theme, - opts = this.options, - ar = getArrow(); - - theme = this._themeClassFromOption("ui-body-", opts.theme); - ar.ar.addClass(theme + (opts.shadow ? " ui-overlay-shadow" : "")); - ar.arEls.hide().appendTo(this.element); - - return ar; - }, - - _unenhance: function () { - var ar = this._ui.arrow; - - if (ar) { - ar.arEls.remove(); - } - - return this._super(); - }, - - // Pretend to show an arrow described by @p and @dir and calculate the - // distance from the desired point. If a best-distance is passed in, return - // the minimum of the one passed in and the one calculated. - _tryAnArrow: function (p, dir, desired, s, best) { - var result, r, diff, desiredForArrow = {}, tip = {}; - - // If the arrow has no wiggle room along the edge of the popup, it cannot - // be displayed along the requested edge without it sticking out. - if (s.arFull[p.dimKey] > s.guideDims[p.dimKey]) { - return best; - } - - desiredForArrow[p.fst] = desired[p.fst] + - (s.arHalf[p.oDimKey] + s.menuHalf[p.oDimKey]) * p.offsetFactor - - s.contentBox[p.fst] + (s.clampInfo.menuSize[p.oDimKey] - s.contentBox[p.oDimKey]) * p.arrowOffsetFactor; - desiredForArrow[p.snd] = desired[p.snd]; - - result = s.result || this._calculateFinalLocation(desiredForArrow, s.clampInfo); - r = { x: result.left, y: result.top }; - - tip[p.fst] = r[p.fst] + s.contentBox[p.fst] + p.tipOffset; - tip[p.snd] = Math.max(result[p.prop] + s.guideOffset[p.prop] + s.arHalf[p.dimKey], - Math.min(result[p.prop] + s.guideOffset[p.prop] + s.guideDims[p.dimKey] - s.arHalf[p.dimKey], - desired[p.snd])); - - diff = Math.abs(desired.x - tip.x) + Math.abs(desired.y - tip.y); - if (!best || diff < best.diff) { - // Convert tip offset to coordinates inside the popup - tip[p.snd] -= s.arHalf[p.dimKey] + result[p.prop] + s.contentBox[p.snd]; - best = { dir: dir, diff: diff, result: result, posProp: p.prop, posVal: tip[p.snd] }; - } - - return best; - }, - - _getPlacementState: function (clamp) { - var offset, gdOffset, - ar = this._ui.arrow, - state = { - clampInfo: this._clampPopupWidth(!clamp), - arFull: { cx: ar.ct.width(), cy: ar.ct.height() }, - guideDims: { cx: ar.gd.width(), cy: ar.gd.height() }, - guideOffset: ar.gd.offset() - }; - - offset = this.element.offset(); - - ar.gd.css({ left: 0, top: 0, right: 0, bottom: 0 }); - gdOffset = ar.gd.offset(); - state.contentBox = { - x: gdOffset.left - offset.left, - y: gdOffset.top - offset.top, - cx: ar.gd.width(), - cy: ar.gd.height() - }; - ar.gd.removeAttr("style"); - - // The arrow box moves between guideOffset and guideOffset + guideDims - arFull - state.guideOffset = { left: state.guideOffset.left - offset.left, top: state.guideOffset.top - offset.top }; - state.arHalf = { cx: state.arFull.cx / 2, cy: state.arFull.cy / 2 }; - state.menuHalf = { cx: state.clampInfo.menuSize.cx / 2, cy: state.clampInfo.menuSize.cy / 2 }; - - return state; - }, - - _placementCoords: function (desired) { - var state, best, params, elOffset, bgRef, - optionValue = this.options.arrow, - ar = this._ui.arrow; - - if (!ar) { - return this._super(desired); - } - - ar.arEls.show(); - - bgRef = {}; - state = this._getPlacementState(true); - params = { - "l": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: 1, tipOffset: -state.arHalf.cx, arrowOffsetFactor: 0 }, - "r": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: -1, tipOffset: state.arHalf.cx + state.contentBox.cx, arrowOffsetFactor: 1 }, - "b": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: -1, tipOffset: state.arHalf.cy + state.contentBox.cy, arrowOffsetFactor: 1 }, - "t": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: 1, tipOffset: -state.arHalf.cy, arrowOffsetFactor: 0 } - }; - - // Try each side specified in the options to see on which one the arrow - // should be placed such that the distance between the tip of the arrow and - // the desired coordinates is the shortest. - $.each((optionValue === true ? "l,t,r,b" : optionValue).split(","), - $.proxy(function (key, value) { - best = this._tryAnArrow(params[value], value, desired, state, best); - }, this)); - - // Could not place the arrow along any of the edges - behave as if showing - // the arrow was turned off. - if (!best) { - ar.arEls.hide(); - return this._super(desired); - } - - // Move the arrow into place - ar.ct - .removeClass("ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b") - .addClass("ui-popup-arrow-" + best.dir) - .removeAttr("style").css(best.posProp, best.posVal) - .show(); - - // Do not move/size the background div on IE, because we use the arrow div for background as well. - if (!ieHack) { - elOffset = this.element.offset(); - bgRef[params[best.dir].fst] = ar.ct.offset(); - bgRef[params[best.dir].snd] = { - left: elOffset.left + state.contentBox.x, - top: elOffset.top + state.contentBox.y - }; - } - - return best.result; - }, - - _setOptions: function (opts) { - var newTheme, - oldTheme = this.options.theme, - ar = this._ui.arrow, - ret = this._super(opts); - - if (opts.arrow !== undefined) { - if (!ar && opts.arrow) { - this._ui.arrow = this._addArrow(); - - // Important to return here so we don't set the same options all over - // again below. - return; - } else if (ar && !opts.arrow) { - ar.arEls.remove(); - this._ui.arrow = null; - } - } - - // Reassign with potentially new arrow - ar = this._ui.arrow; - - if (ar) { - if (opts.theme !== undefined) { - oldTheme = this._themeClassFromOption("ui-body-", oldTheme); - newTheme = this._themeClassFromOption("ui-body-", opts.theme); - ar.ar.removeClass(oldTheme).addClass(newTheme); - } - - if (opts.shadow !== undefined) { - ar.ar.toggleClass("ui-overlay-shadow", opts.shadow); - } - } - - return ret; - }, - - _destroy: function () { - var ar = this._ui.arrow; - - if (ar) { - ar.arEls.remove(); - } - - return this._super(); - } - }); - - })(jQuery); -}); \ No newline at end of file +define(["jqmwidget"],function(){!function($,undefined){var props={animation:{},transition:{}},testElement=document.createElement("a"),vendorPrefixes=["","webkit-","moz-","o-"];$.each(["animation","transition"],function(i,test){var testName=0===i?test+"-name":test;$.each(vendorPrefixes,function(j,prefix){if(testElement.style[$.camelCase(prefix+testName)]!==undefined)return props[test].prefix=prefix,!1}),props[test].duration=$.camelCase(props[test].prefix+test+"-duration"),props[test].event=$.camelCase(props[test].prefix+test+"-end"),""===props[test].prefix&&(props[test].event=props[test].event.toLowerCase())}),$(testElement).remove(),$.fn.animationComplete=function(callback,type,fallbackTime){var timer,duration,that=this,eventBinding=function(){clearTimeout(timer),callback.apply(this,arguments)},animationType=type&&"animation"!==type?"transition":"animation";return fallbackTime===undefined&&($(this).context!==document&&(duration=3e3*parseFloat($(this).css(props[animationType].duration))),(0===duration||duration===undefined||isNaN(duration))&&(duration=$.fn.animationComplete.defaultDuration)),timer=setTimeout(function(){$(that).off(props[animationType].event,eventBinding),callback.apply(that)},duration),$(this).one(props[animationType].event,eventBinding)},$.fn.animationComplete.defaultDuration=1e3}(jQuery),function($,undefined){function fitSegmentInsideSegment(windowSize,segmentSize,offset,desired){var returnValue=desired;return returnValue=windowSize
";while(a[0]);return v>4?v:!v}(),$.widget("mobile.popup",{options:{wrapperClass:null,theme:null,overlayTheme:null,shadow:!0,corners:!0,transition:"none",positionTo:"origin",tolerance:null,closeLinkSelector:"a[data-rel='back']",closeLinkEvents:"click.popup",navigateEvents:"navigate.popup",closeEvents:"navigate.popup pagebeforechange.popup",dismissible:!0,enhanced:!1,history:!$.mobile.browser.oldIE},_handleDocumentVmousedown:function(theEvent){this._isOpen&&$.contains(this._ui.container[0],theEvent.target)&&this._ignoreResizeEvents()},_create:function(){var theElement=this.element,myId=theElement.attr("id"),currentOptions=this.options;currentOptions.history=currentOptions.history&&$.mobile.ajaxEnabled&&$.mobile.hashListeningEnabled,this._on(this.document,{mousedown:"_handleDocumentVmousedown"}),$.extend(this,{_scrollTop:0,_page:theElement.parents("div[data-role='page']"),_ui:null,_fallbackTransition:"",_currentTransition:!1,_prerequisites:null,_isOpen:!1,_tolerance:null,_resizeData:null,_ignoreResizeTo:0,_orientationchangeInProgress:!1}),0===this._page.length&&(this._page=$("body")),currentOptions.enhanced?this._ui={container:theElement.parent(),screen:theElement.parent().prev(),placeholder:$(this.document[0].getElementById(myId+"-placeholder"))}:(this._ui=this._enhance(theElement,myId),this._applyTransition(currentOptions.transition)),this._setTolerance(currentOptions.tolerance)._ui.focusElement=this._ui.container,this._on(this._ui.screen,{click:"_eatEventAndClose"}),this._on(this.window,{orientationchange:$.proxy(this,"_handleWindowOrientationchange"),resize:$.proxy(this,"_handleWindowResize")}),this._on(this.document,{focusin:"_handleDocumentFocusIn"})},_delay:function(handler,delay){function handlerProxy(){return("string"==typeof handler?instance[handler]:handler).apply(instance,arguments)}var instance=this;return setTimeout(handlerProxy,delay||0)},_enhance:function(theElement,myId){var currentOptions=this.options,wrapperClass=currentOptions.wrapperClass,ui={screen:$("
"),placeholder:$("
"),container:$("
")},fragment=this.document[0].createDocumentFragment();return fragment.appendChild(ui.screen[0]),fragment.appendChild(ui.container[0]),myId&&(ui.screen.attr("id",myId+"-screen"),ui.container.attr("id",myId+"-popup"),ui.placeholder.attr("id",myId+"-placeholder").html("")),this._page[0].appendChild(fragment),ui.placeholder.insertAfter(theElement),theElement.detach().addClass("ui-popup "+this._themeClassFromOption("ui-body-",currentOptions.theme)+" "+(currentOptions.shadow?"ui-overlay-shadow ":"")+(currentOptions.corners?"ui-corner-all ":"")).appendTo(ui.container),ui},_eatEventAndClose:function(theEvent){return theEvent.preventDefault(),theEvent.stopImmediatePropagation(),this.options.dismissible&&this.close(),!1},_resizeScreen:function(){var screen=this._ui.screen,popupHeight=this._ui.container.outerHeight(!0),screenHeight=screen.removeAttr("style").height(),documentHeight=this.document.height()-1;screenHeightscreenHeight&&screen.height(popupHeight)},_expectResizeEvent:function(){var windowCoordinates=getWindowCoordinates(this.window);if(this._resizeData){if(windowCoordinates.x===this._resizeData.windowCoordinates.x&&windowCoordinates.y===this._resizeData.windowCoordinates.y&&windowCoordinates.cx===this._resizeData.windowCoordinates.cx&&windowCoordinates.cy===this._resizeData.windowCoordinates.cy)return!1;clearTimeout(this._resizeData.timeoutId)}return this._resizeData={timeoutId:this._delay("_resizeTimeout",200),windowCoordinates:windowCoordinates},!0},_resizeTimeout:function(){this._isOpen?this._expectResizeEvent()||(this._ui.container.hasClass("ui-popup-hidden")&&(this._ui.container.removeClass("ui-popup-hidden ui-popup-truncate"),this.reposition({positionTo:"window"}),this._ignoreResizeEvents()),this._resizeScreen(),this._resizeData=null,this._orientationchangeInProgress=!1):(this._resizeData=null,this._orientationchangeInProgress=!1)},_stopIgnoringResizeEvents:function(){this._ignoreResizeTo=0},_ignoreResizeEvents:function(){this._ignoreResizeTo&&clearTimeout(this._ignoreResizeTo),this._ignoreResizeTo=this._delay("_stopIgnoringResizeEvents",1e3)},_handleWindowResize:function(){this._isOpen&&0===this._ignoreResizeTo&&(!this._expectResizeEvent()&&!this._orientationchangeInProgress||this._ui.container.hasClass("ui-popup-hidden")||this._ui.container.addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style"))},_handleWindowOrientationchange:function(){!this._orientationchangeInProgress&&this._isOpen&&0===this._ignoreResizeTo&&(this._expectResizeEvent(),this._orientationchangeInProgress=!0)},_handleDocumentFocusIn:function(theEvent){var target,targetElement=theEvent.target,ui=this._ui;if(this._isOpen){if(targetElement!==ui.container[0]){if(target=$(targetElement),!$.contains(ui.container[0],targetElement))return $(this.document[0].activeElement).one("focus",$.proxy(function(){this._safelyBlur(targetElement)},this)),ui.focusElement.focus(),theEvent.preventDefault(),theEvent.stopImmediatePropagation(),!1;ui.focusElement[0]===ui.container[0]&&(ui.focusElement=target)}this._ignoreResizeEvents()}},_themeClassFromOption:function(prefix,value){return value?"none"===value?"":prefix+value:prefix+"inherit"},_applyTransition:function(value){return value&&(this._ui.container.removeClass(this._fallbackTransition),"none"!==value&&(this._fallbackTransition=$.mobile._maybeDegradeTransition(value),"none"===this._fallbackTransition&&(this._fallbackTransition=""),this._ui.container.addClass(this._fallbackTransition))),this},_setOptions:function(newOptions){var currentOptions=this.options,theElement=this.element,screen=this._ui.screen;return newOptions.wrapperClass!==undefined&&this._ui.container.removeClass(currentOptions.wrapperClass).addClass(newOptions.wrapperClass),newOptions.theme!==undefined&&theElement.removeClass(this._themeClassFromOption("ui-body-",currentOptions.theme)).addClass(this._themeClassFromOption("ui-body-",newOptions.theme)),newOptions.overlayTheme!==undefined&&(screen.removeClass(this._themeClassFromOption("ui-overlay-",currentOptions.overlayTheme)).addClass(this._themeClassFromOption("ui-overlay-",newOptions.overlayTheme)),this._isOpen&&screen.addClass("in")),newOptions.shadow!==undefined&&theElement.toggleClass("ui-overlay-shadow",newOptions.shadow),newOptions.corners!==undefined&&theElement.toggleClass("ui-corner-all",newOptions.corners),newOptions.transition!==undefined&&(this._currentTransition||this._applyTransition(newOptions.transition)),newOptions.tolerance!==undefined&&this._setTolerance(newOptions.tolerance),newOptions.disabled!==undefined&&newOptions.disabled&&this.close(),this._super(newOptions)},_setTolerance:function(value){var ar,tol={t:30,r:15,b:30,l:15};if(value!==undefined)switch(ar=String(value).split(","),$.each(ar,function(idx,val){ar[idx]=parseInt(val,10)}),ar.length){case 1:isNaN(ar[0])||(tol.t=tol.r=tol.b=tol.l=ar[0]);break;case 2:isNaN(ar[0])||(tol.t=tol.b=ar[0]),isNaN(ar[1])||(tol.l=tol.r=ar[1]);break;case 4:isNaN(ar[0])||(tol.t=ar[0]),isNaN(ar[1])||(tol.r=ar[1]),isNaN(ar[2])||(tol.b=ar[2]),isNaN(ar[3])||(tol.l=ar[3])}return this._tolerance=tol,this},_clampPopupWidth:function(infoOnly){var menuSize,windowCoordinates=getWindowCoordinates(this.window),rectangle={x:this._tolerance.l,y:windowCoordinates.y+this._tolerance.t,cx:windowCoordinates.cx-this._tolerance.l-this._tolerance.r,cy:windowCoordinates.cy-this._tolerance.t-this._tolerance.b};return infoOnly||this._ui.container.css("max-width",rectangle.cx),menuSize={cx:this._ui.container.outerWidth(!0),cy:this._ui.container.outerHeight(!0)},{rc:rectangle,menuSize:menuSize}},_calculateFinalLocation:function(desired,clampInfo){var returnValue,rectangle=clampInfo.rc,menuSize=clampInfo.menuSize;return returnValue={left:fitSegmentInsideSegment(rectangle.cx,menuSize.cx,rectangle.x,desired.x),top:fitSegmentInsideSegment(rectangle.cy,menuSize.cy,rectangle.y,desired.y)},returnValue.top=Math.max(0,returnValue.top),returnValue.top-=Math.min(returnValue.top,Math.max(0,returnValue.top+menuSize.cy-this.document.height())),returnValue},_placementCoords:function(desired){return this._calculateFinalLocation(desired,this._clampPopupWidth())},_createPrerequisites:function(screenPrerequisite,containerPrerequisite,whenDone){var prerequisites,self=this;prerequisites={screen:$.Deferred(),container:$.Deferred()},prerequisites.screen.then(function(){prerequisites===self._prerequisites&&screenPrerequisite()}),prerequisites.container.then(function(){prerequisites===self._prerequisites&&containerPrerequisite()}),Promise.all([prerequisites.screen,prerequisites.container]).then(function(){prerequisites===self._prerequisites&&(self._prerequisites=null,whenDone())}),self._prerequisites=prerequisites},_animate:function(args){return this._ui.screen.removeClass(args.classToRemove).addClass(args.screenClassToAdd),args.prerequisites.screen.resolve(),args.transition&&"none"!==args.transition&&(args.applyTransition&&this._applyTransition(args.transition),this._fallbackTransition)?void this._ui.container.addClass(args.containerClassToAdd).removeClass(args.classToRemove).animationComplete($.proxy(args.prerequisites.container,"resolve")):(this._ui.container.removeClass(args.classToRemove),void args.prerequisites.container.resolve())},_desiredCoords:function(openOptions){var offset,dst=null,windowCoordinates=getWindowCoordinates(this.window),x=openOptions.x,y=openOptions.y,pTo=openOptions.positionTo;if(pTo&&"origin"!==pTo)if("window"===pTo)x=windowCoordinates.cx/2+windowCoordinates.x,y=windowCoordinates.cy/2+windowCoordinates.y;else{try{dst=$(pTo)}catch(err){dst=null}dst&&(dst.filter(":visible"),0===dst.length&&(dst=null))}return dst&&(offset=dst.offset(),x=offset.left+dst.outerWidth()/2,y=offset.top+dst.outerHeight()/2),("number"!==$.type(x)||isNaN(x))&&(x=windowCoordinates.cx/2+windowCoordinates.x),("number"!==$.type(y)||isNaN(y))&&(y=windowCoordinates.cy/2+windowCoordinates.y),{x:x,y:y}},_reposition:function(openOptions){openOptions={x:openOptions.x,y:openOptions.y,positionTo:openOptions.positionTo},this._trigger("beforeposition",undefined,openOptions),this._ui.container.offset(this._placementCoords(this._desiredCoords(openOptions)))},reposition:function(openOptions){this._isOpen&&this._reposition(openOptions)},_safelyBlur:function(currentElement){currentElement!==this.window[0]&&"body"!==currentElement.nodeName.toLowerCase()&&$(currentElement).blur()},_openPrerequisitesComplete:function(){var id=this.element.attr("id");this._ui.container.addClass("ui-popup-active"),this._isOpen=!0,this._resizeScreen(),$.contains(this._ui.container[0],this.document[0].activeElement)||this._safelyBlur(this.document[0].activeElement),this._ignoreResizeEvents(),id&&this.document.find("[aria-haspopup='true'][aria-owns='"+id+"']").attr("aria-expanded",!0),this._trigger("afteropen")},_open:function(options){var openOptions=$.extend({},this.options,options),androidBlacklist=function(){var ua=navigator.userAgent,wkmatch=ua.match(/AppleWebKit\/([0-9\.]+)/),wkversion=!!wkmatch&&wkmatch[1],androidmatch=ua.match(/Android (\d+(?:\.\d+))/),andversion=!!androidmatch&&androidmatch[1],chromematch=ua.indexOf("Chrome")>-1;return!(!(null!==androidmatch&&"4.0"===andversion&&wkversion&&wkversion>534.13)||chromematch)}();this._createPrerequisites($.noop,$.noop,$.proxy(this,"_openPrerequisitesComplete")),this._currentTransition=openOptions.transition,this._applyTransition(openOptions.transition),this._ui.screen.removeClass("ui-screen-hidden"),this._ui.container.removeClass("ui-popup-truncate"),this._reposition(openOptions),this._ui.container.removeClass("ui-popup-hidden"),this.options.overlayTheme&&androidBlacklist&&this.element.closest(".ui-page").addClass("ui-popup-open"),this._animate({additionalCondition:!0,transition:openOptions.transition,classToRemove:"",screenClassToAdd:"in",containerClassToAdd:"in",applyTransition:!1,prerequisites:this._prerequisites})},_closePrerequisiteScreen:function(){this._ui.screen.removeClass("out").addClass("ui-screen-hidden")},_closePrerequisiteContainer:function(){this._ui.container.removeClass("reverse out").addClass("ui-popup-hidden ui-popup-truncate").removeAttr("style")},_closePrerequisitesDone:function(){var container=this._ui.container,id=this.element.attr("id");$.mobile.popup.active=undefined,$(":focus",container[0]).add(container[0]).blur(),id&&this.document.find("[aria-haspopup='true'][aria-owns='"+id+"']").attr("aria-expanded",!1),this._trigger("afterclose")},_close:function(immediate){this._ui.container.removeClass("ui-popup-active"),this._page.removeClass("ui-popup-open"),this._isOpen=!1,this._createPrerequisites($.proxy(this,"_closePrerequisiteScreen"),$.proxy(this,"_closePrerequisiteContainer"),$.proxy(this,"_closePrerequisitesDone")),this._animate({additionalCondition:this._ui.screen.hasClass("in"),transition:immediate?"none":this._currentTransition,classToRemove:"in",screenClassToAdd:"out",containerClassToAdd:"reverse out",applyTransition:!0,prerequisites:this._prerequisites})},_unenhance:function(){this.options.enhanced||(this._setOptions({theme:$.mobile.popup.prototype.options.theme}),this.element.detach().insertAfter(this._ui.placeholder).removeClass("ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit"),this._ui.screen.remove(),this._ui.container.remove(),this._ui.placeholder.remove())},_destroy:function(){return $.mobile.popup.active===this?(this.element.one("popupafterclose",$.proxy(this,"_unenhance")),this.close()):this._unenhance(),this},_closePopup:function(theEvent,data){var parsedDst,toUrl,currentOptions=this.options,immediate=!1;theEvent&&theEvent.isDefaultPrevented()||$.mobile.popup.active!==this||(window.scrollTo(0,this._scrollTop),theEvent&&"pagebeforechange"===theEvent.type&&data&&(parsedDst="string"==typeof data.toPage?data.toPage:data.toPage.data("url"),parsedDst=$.mobile.path.parseUrl(parsedDst),toUrl=parsedDst.pathname+parsedDst.search+parsedDst.hash,this._myUrl!==$.mobile.path.makeUrlAbsolute(toUrl)?immediate=!0:theEvent.preventDefault()),this.window.off(currentOptions.closeEvents),this.element.off(currentOptions.closeLinkEvents,currentOptions.closeLinkSelector),this._close(immediate))},_bindContainerClose:function(){this.window.on(this.options.closeEvents,$.proxy(this,"_closePopup"))},widget:function(){return this._ui.container},open:function(options){var url,hashkey,activePage,currentIsDialog,hasHash,urlHistory,self=this,currentOptions=this.options;return $.mobile.popup.active||currentOptions.disabled?this:($.mobile.popup.active=this,this._scrollTop=this.window.scrollTop(),currentOptions.history?(urlHistory=$.mobile.navigate.history,hashkey=$.mobile.dialogHashKey,activePage=$.mobile.activePage,currentIsDialog=!!activePage&&activePage.hasClass("ui-dialog"),this._myUrl=url=urlHistory.getActive().url,(hasHash=url.indexOf(hashkey)>-1&&!currentIsDialog&&urlHistory.activeIndex>0)?(self._open(options),self._bindContainerClose(),this):(url.indexOf(hashkey)!==-1||currentIsDialog?url=$.mobile.path.parseLocation().hash+hashkey:url+=url.indexOf("#")>-1?hashkey:"#"+hashkey,this.window.one("beforenavigate",function(theEvent){theEvent.preventDefault(),self._open(options),self._bindContainerClose()}),this.urlAltered=!0,$.mobile.navigate(url,{role:"dialog"}),this)):(self._open(options),self._bindContainerClose(),self.element.on(currentOptions.closeLinkEvents,currentOptions.closeLinkSelector,function(theEvent){self.close(),theEvent.preventDefault()}),this))},close:function(){return $.mobile.popup.active!==this?this:(this._scrollTop=this.window.scrollTop(),this.options.history&&this.urlAltered?($.mobile.pageContainer.pagecontainer("back"),this.urlAltered=!1):this._closePopup(),this)}}),$.mobile.popup.handleLink=function($link){var offset,path=$.mobile.path,popup=$(path.hashToSelector(path.parseUrl($link.attr("href")).hash)).first();popup.length>0&&popup.data("mobile-popup")&&(offset=$link.offset(),popup.popup("open",{x:offset.left+$link.outerWidth()/2,y:offset.top+$link.outerHeight()/2,transition:$link.data("transition"),positionTo:$link.data("position-to")})),setTimeout(function(){$link.removeClass($.mobile.activeBtnClass)},300)},$(document).on("pagebeforechange",function(theEvent,data){"popup"===data.options.role&&($.mobile.popup.handleLink(data.options.link),theEvent.preventDefault())})}(jQuery),function($,undefined){function getArrow(){var clone=uiTemplate.clone(),gd=clone.eq(0),ct=clone.eq(1),ar=ct.children();return{arEls:ct.add(gd),gd:gd,ct:ct,ar:ar}}var ieHack=$.mobile.browser.oldIE&&$.mobile.browser.oldIE<=8,uiTemplate=$("
");$.widget("mobile.popup",$.mobile.popup,{options:{arrow:""},_create:function(){var ar,ret=this._super();return this.options.arrow&&(this._ui.arrow=ar=this._addArrow()),ret},_addArrow:function(){var theme,opts=this.options,ar=getArrow();return theme=this._themeClassFromOption("ui-body-",opts.theme),ar.ar.addClass(theme+(opts.shadow?" ui-overlay-shadow":"")),ar.arEls.hide().appendTo(this.element),ar},_unenhance:function(){var ar=this._ui.arrow;return ar&&ar.arEls.remove(),this._super()},_tryAnArrow:function(p,dir,desired,s,best){var result,r,diff,desiredForArrow={},tip={};return s.arFull[p.dimKey]>s.guideDims[p.dimKey]?best:(desiredForArrow[p.fst]=desired[p.fst]+(s.arHalf[p.oDimKey]+s.menuHalf[p.oDimKey])*p.offsetFactor-s.contentBox[p.fst]+(s.clampInfo.menuSize[p.oDimKey]-s.contentBox[p.oDimKey])*p.arrowOffsetFactor,desiredForArrow[p.snd]=desired[p.snd],result=s.result||this._calculateFinalLocation(desiredForArrow,s.clampInfo),r={x:result.left,y:result.top},tip[p.fst]=r[p.fst]+s.contentBox[p.fst]+p.tipOffset,tip[p.snd]=Math.max(result[p.prop]+s.guideOffset[p.prop]+s.arHalf[p.dimKey],Math.min(result[p.prop]+s.guideOffset[p.prop]+s.guideDims[p.dimKey]-s.arHalf[p.dimKey],desired[p.snd])),diff=Math.abs(desired.x-tip.x)+Math.abs(desired.y-tip.y),(!best||diff/**/body .ui-rangeslider .ui-rangeslider-sliders .ui-slider-track:first-child { - height: 15px; - border-width: 1px; -} -html >/**/body .ui-rangeslider.ui-mini .ui-rangeslider-sliders .ui-slider-track:first-child { - height: 12px; -} - -/* Hide the second label (the first is moved outside the div) */ -div.ui-rangeslider label { - position: absolute !important; - height: 1px; - width: 1px; - overflow: hidden; - clip: rect(1px,1px,1px,1px); -} -.ui-field-contain .ui-rangeslider input.ui-slider-input, -.ui-field-contain .ui-rangeslider.ui-mini input.ui-slider-input, -.ui-field-contain .ui-rangeslider .ui-rangeslider-sliders, -.ui-field-contain .ui-rangeslider.ui-mini .ui-rangeslider-sliders { - margin-top: 0; - margin-bottom: 0; -} - - - - - -div.ui-slider { - height: 30px; - margin: .5em 0; - padding: 0; - -ms-touch-action: pan-y pinch-zoom double-tap-zoom; -} -div.ui-slider:before, -div.ui-slider:after { - content: ""; - display: table; -} -div.ui-slider:after { - clear: both; -} -input.ui-slider-input { - display: none; - float: left; - font-size: 14px; - font-weight: bold; - margin: 0; - padding: 4px; - width: 40px; - height: 20px; - line-height: 20px; - border-width: 1px; - border-style: solid; - outline: 0; - text-align: center; - vertical-align: text-bottom; - -webkit-appearance: none; - -moz-appearance: none; - appearance: none; - -webkit-box-sizing: content-box; - -moz-box-sizing: content-box; - box-sizing: content-box; -} -.ui-slider-input::-webkit-outer-spin-button, -.ui-slider-input::-webkit-inner-spin-button { - -webkit-appearance: none; - margin: 0; -} -.ui-slider-track { - position: relative; - overflow: visible; - border-width: 1px; - border-style: solid; - height: 15px; - margin: 0 15px 0 0; - top: 6px; -} -.ui-slider-track.ui-mini { - height: 12px; - top: 8px; -} -.ui-slider-track .ui-slider-bg { - height: 100%; -} -/* High level of specificity to override button margins in grids */ -.ui-slider-track .ui-btn.ui-slider-handle { - position: absolute; - z-index: 1; - top: 50%; - width: 28px; - height: 28px; - margin: -15px 0 0 -15px; - outline: 0; - padding: 0; -} -.ui-slider-track.ui-mini .ui-slider-handle { - height: 14px; - width: 14px; - margin: -8px 0 0 -8px; -} -select.ui-slider-switch { - position: absolute !important; - height: 1px; - width: 1px; - overflow: hidden; - clip: rect(1px,1px,1px,1px); -} -div.ui-slider-switch { - display: inline-block; - height: 32px; - width: 5.8em; - top: 0; -} -/* reset the clearfix */ -div.ui-slider-switch:before, -div.ui-slider-switch:after { - display: none; - clear: none; -} -div.ui-slider-switch.ui-mini { - height: 29px; - top: 0; -} -.ui-slider-inneroffset { - margin: 0 16px; - position: relative; - z-index: 1; -} -.ui-slider-switch.ui-mini .ui-slider-inneroffset { - margin: 0 15px 0 14px; -} -.ui-slider-switch .ui-btn.ui-slider-handle { - margin: 1px 0 0 -15px; -} -.ui-slider-switch.ui-mini .ui-slider-handle { - width: 25px; - height: 25px; - margin: 1px 0 0 -13px; - padding: 0; -} -.ui-slider-handle-snapping { - -webkit-transition: left 70ms linear; - -moz-transition: left 70ms linear; - transition: left 70ms linear; -} -.ui-slider-switch .ui-slider-label { - position: absolute; - text-align: center; - width: 100%; - overflow: hidden; - font-size: 16px; - top: 0; - line-height: 2; - min-height: 100%; - white-space: nowrap; - cursor: pointer; -} -.ui-slider-switch.ui-mini .ui-slider-label { - font-size: 14px; -} -.ui-slider-switch .ui-slider-label-a { - z-index: 1; - left: 0; - text-indent: -1.5em; -} -.ui-slider-switch .ui-slider-label-b { - z-index: 0; - right: 0; - text-indent: 1.5em; -} -/* The corner radii for ui-slider-switch/track can be specified in theme CSS. The bg and handle inherits. */ -.ui-slider-track .ui-slider-bg, -.ui-slider-switch .ui-slider-label, -.ui-slider-switch .ui-slider-inneroffset, -.ui-slider-handle { - -webkit-border-radius: inherit; - border-radius: inherit; -} -.ui-field-contain div.ui-slider-switch { - margin: 0; -} -/* ui-hide-label deprecated in 1.4. TODO: Remove in 1.5 */ -.ui-field-contain div.ui-slider-switch, -.ui-field-contain.ui-hide-label div.ui-slider-switch, -html .ui-popup .ui-field-contain div.ui-slider-switch { - display: inline-block; - width: 5.8em; -} - - -/* slider tooltip ------------------------------------------------------------------------------------------------------------*/ - -.ui-slider-popup { - width: 64px; - height: 64px; - font-size: 36px; - padding-top: 14px; - opacity: 0.8; -} - -.ui-slider-popup { - position: absolute !important; - text-align: center; - z-index: 100; -} - -.ui-slider-track .ui-btn.ui-slider-handle { - font-size: .9em; - line-height: 30px; -} - - - -/* Active slider track */ -.ui-page-theme-a .ui-slider-track .ui-btn-active, -html .ui-bar-a .ui-slider-track .ui-btn-active, -html .ui-body-a .ui-slider-track .ui-btn-active, -html body .ui-group-theme-a .ui-slider-track .ui-btn-active, -html body div.ui-slider-track.ui-body-a .ui-btn-active { - background-color: #3388cc /*{a-active-background-color}*/; - border-color: #3388cc /*{a-active-border}*/; - color: #fff /*{a-active-color}*/; - text-shadow: 0 /*{a-active-shadow-x}*/ 1px /*{a-active-shadow-y}*/ 0 /*{a-active-shadow-radius}*/ #005599 /*{a-active-shadow-color}*/; -} - -/* Active slider track */ -.ui-page-theme-b .ui-slider-track .ui-btn-active, -html .ui-bar-b .ui-slider-track .ui-btn-active, -html .ui-body-b .ui-slider-track .ui-btn-active, -html body .ui-group-theme-b .ui-slider-track .ui-btn-active, -html body div.ui-slider-track.ui-body-b .ui-btn-active { - background-color: #22aadd /*{b-active-background-color}*/; - border-color: #22aadd /*{b-active-border}*/; - color: #fff /*{b-active-color}*/; - text-shadow: 0 /*{b-active-shadow-x}*/ 1px /*{b-active-shadow-y}*/ 0 /*{b-active-shadow-radius}*/ #0088bb /*{b-active-shadow-color}*/; -} +.ui-rangeslider:after,div.ui-slider:after{clear:both}.ui-rangeslider{margin:.5em 0}.ui-rangeslider:after,.ui-rangeslider:before{content:"";display:table}.ui-rangeslider .ui-slider-input.ui-rangeslider-last{float:right}.ui-rangeslider .ui-rangeslider-sliders{position:relative;overflow:visible;height:30px;margin:0 68px}.ui-rangeslider .ui-rangeslider-sliders .ui-slider-track{position:absolute;top:6px;right:0;left:0;margin:0}.ui-rangeslider.ui-mini .ui-rangeslider-sliders .ui-slider-track{top:8px}.ui-rangeslider .ui-slider-track:first-child .ui-slider-bg{display:none}.ui-rangeslider .ui-rangeslider-sliders .ui-slider-track:first-child{background:0 0;border-width:0;height:0}html>body .ui-rangeslider .ui-rangeslider-sliders .ui-slider-track:first-child{height:15px;border-width:1px}html>body .ui-rangeslider.ui-mini .ui-rangeslider-sliders .ui-slider-track:first-child{height:12px}div.ui-rangeslider label{position:absolute!important;height:1px;width:1px;overflow:hidden;clip:rect(1px,1px,1px,1px)}.ui-field-contain .ui-rangeslider .ui-rangeslider-sliders,.ui-field-contain .ui-rangeslider input.ui-slider-input,.ui-field-contain .ui-rangeslider.ui-mini .ui-rangeslider-sliders,.ui-field-contain .ui-rangeslider.ui-mini input.ui-slider-input{margin-top:0;margin-bottom:0}div.ui-slider{height:30px;margin:.5em 0;padding:0;-ms-touch-action:pan-y pinch-zoom double-tap-zoom}div.ui-slider:after,div.ui-slider:before{content:"";display:table}input.ui-slider-input{display:none;float:left;font-size:14px;font-weight:700;margin:0;padding:4px;width:40px;height:20px;line-height:20px;border-width:1px;border-style:solid;outline:0;text-align:center;vertical-align:text-bottom;-webkit-appearance:none;-moz-appearance:none;appearance:none;-webkit-box-sizing:content-box;box-sizing:content-box}.ui-slider-input::-webkit-inner-spin-button,.ui-slider-input::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.ui-slider-track{position:relative;overflow:visible;border-width:1px;border-style:solid;height:15px;margin:0 15px 0 0;top:6px}.ui-slider-track.ui-mini{height:12px;top:8px}.ui-slider-track .ui-slider-bg{height:100%}.ui-slider-track .ui-btn.ui-slider-handle{position:absolute;z-index:1;top:50%;width:28px;height:28px;margin:-15px 0 0 -15px;outline:0;padding:0}.ui-slider-track.ui-mini .ui-slider-handle{height:14px;width:14px;margin:-8px 0 0 -8px}select.ui-slider-switch{position:absolute!important;height:1px;width:1px;overflow:hidden;clip:rect(1px,1px,1px,1px)}div.ui-slider-switch{display:inline-block;height:32px;width:5.8em;top:0}div.ui-slider-switch:after,div.ui-slider-switch:before{display:none;clear:none}div.ui-slider-switch.ui-mini{height:29px;top:0}.ui-slider-inneroffset{margin:0 16px;position:relative;z-index:1}.ui-slider-switch.ui-mini .ui-slider-inneroffset{margin:0 15px 0 14px}.ui-slider-switch .ui-btn.ui-slider-handle{margin:1px 0 0 -15px}.ui-slider-switch.ui-mini .ui-slider-handle{width:25px;height:25px;margin:1px 0 0 -13px;padding:0}.ui-slider-handle-snapping{-webkit-transition:left 70ms linear;-o-transition:left 70ms linear;transition:left 70ms linear}.ui-slider-switch .ui-slider-label{position:absolute;text-align:center;width:100%;overflow:hidden;font-size:16px;top:0;line-height:2;min-height:100%;white-space:nowrap;cursor:pointer}.ui-slider-switch.ui-mini .ui-slider-label{font-size:14px}.ui-slider-switch .ui-slider-label-a{z-index:1;left:0;text-indent:-1.5em}.ui-slider-switch .ui-slider-label-b{z-index:0;right:0;text-indent:1.5em}.ui-slider-handle,.ui-slider-switch .ui-slider-inneroffset,.ui-slider-switch .ui-slider-label,.ui-slider-track .ui-slider-bg{-webkit-border-radius:inherit;border-radius:inherit}.ui-field-contain div.ui-slider-switch{margin:0}.ui-field-contain div.ui-slider-switch,.ui-field-contain.ui-hide-label div.ui-slider-switch,html .ui-popup .ui-field-contain div.ui-slider-switch{display:inline-block;width:5.8em}.ui-slider-popup{width:64px;height:64px;font-size:36px;padding-top:14px;opacity:.8;position:absolute!important;text-align:center;z-index:100}.ui-slider-track .ui-btn.ui-slider-handle{font-size:.9em;line-height:30px}.ui-page-theme-a .ui-slider-track .ui-btn-active,html .ui-bar-a .ui-slider-track .ui-btn-active,html .ui-body-a .ui-slider-track .ui-btn-active,html body .ui-group-theme-a .ui-slider-track .ui-btn-active,html body div.ui-slider-track.ui-body-a .ui-btn-active{background-color:#38c;border-color:#38c;color:#fff;text-shadow:0 1px 0 #059}.ui-page-theme-b .ui-slider-track .ui-btn-active,html .ui-bar-b .ui-slider-track .ui-btn-active,html .ui-body-b .ui-slider-track .ui-btn-active,html body .ui-group-theme-b .ui-slider-track .ui-btn-active,html body div.ui-slider-track.ui-body-b .ui-btn-active{background-color:#2ad;border-color:#2ad;color:#fff;text-shadow:0 1px 0 #08b} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.slider.js b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.slider.js index 6b9cee55c6..98f7073bbc 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.slider.js +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.slider.js @@ -1,1027 +1 @@ -define(['jqmwidget'], function () { - - var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/; - - $.extend($.mobile, { - - // Namespace used framework-wide for data-attrs. Default is no namespace - - // Retrieve an attribute from an element and perform some massaging of the value - - getAttribute: function (element, key) { - var data; - - element = element.jquery ? element[0] : element; - - if (element && element.getAttribute) { - data = element.getAttribute("data-" + key); - } - - // Copied from core's src/data.js:dataAttr() - // Convert from a string to a proper data type - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test(data) ? JSON.parse(data) : - data; - } catch (err) { } - - return data; - } - - }); - - /*! - * jQuery UI Core c0ab71056b936627e8a7821f03c044aec6280a40 - * http://jqueryui.com - * - * Copyright 2013 jQuery Foundation and other contributors - * Released under the MIT license. - * http://jquery.org/license - * - * http://api.jqueryui.com/category/ui-core/ - */ - (function ($, undefined) { - - // $.ui might exist from components with no dependencies, e.g., $.ui.position - $.ui = $.ui || {}; - - $.extend($.ui, { - version: "c0ab71056b936627e8a7821f03c044aec6280a40", - - keyCode: { - BACKSPACE: 8, - COMMA: 188, - DELETE: 46, - DOWN: 40, - END: 35, - ENTER: 13, - ESCAPE: 27, - HOME: 36, - LEFT: 37, - PAGE_DOWN: 34, - PAGE_UP: 33, - PERIOD: 190, - RIGHT: 39, - SPACE: 32, - TAB: 9, - UP: 38 - } - }); - - // deprecated - $.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()); - - })(jQuery); - - $.widget("mobile.slider", $.extend({ - initSelector: "input[type='range']:not([data-role='none'])", - - widgetEventPrefix: "slide", - - options: { - theme: null, - trackTheme: null, - corners: true, - mini: false, - highlight: false - }, - - _create: function () { - - // TODO: Each of these should have comments explain what they're for - var self = this, - control = this.element, - trackTheme = this.options.trackTheme || $.mobile.getAttribute(control[0], "theme"), - trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", - cornerClass = (this.options.corners || control.data("corners")) ? " ui-corner-all" : "", - miniClass = (this.options.mini || control.data("mini")) ? " ui-mini" : "", - cType = control[0].nodeName.toLowerCase(), - isToggleSwitch = (cType === "select"), - isRangeslider = control.parent().is("[data-role='rangeslider']"), - selectClass = (isToggleSwitch) ? "ui-slider-switch" : "", - controlID = control.attr("id"), - $label = $("[for='" + controlID + "']"), - labelID = $label.attr("id") || controlID + "-label", - min = !isToggleSwitch ? parseFloat(control.attr("min")) : 0, - max = !isToggleSwitch ? parseFloat(control.attr("max")) : control.find("option").length - 1, - step = window.parseFloat(control.attr("step") || 1), - domHandle = document.createElement("a"), - handle = $(domHandle), - domSlider = document.createElement("div"), - slider = $(domSlider), - valuebg = this.options.highlight && !isToggleSwitch ? (function () { - var bg = document.createElement("div"); - bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; - return $(bg).prependTo(slider); - })() : false, - options, - wrapper, - j, length, - i, optionsCount, origTabIndex, - side, activeClass, sliderImg; - - $label.attr("id", labelID); - this.isToggleSwitch = isToggleSwitch; - - domHandle.setAttribute("href", "#"); - domSlider.setAttribute("role", "application"); - domSlider.className = [this.isToggleSwitch ? "ui-slider ui-slider-track ui-shadow-inset " : "ui-slider-track ui-shadow-inset ", selectClass, trackThemeClass, cornerClass, miniClass].join(""); - domHandle.className = "ui-slider-handle"; - domSlider.appendChild(domHandle); - - handle.attr({ - "role": "slider", - "aria-valuemin": min, - "aria-valuemax": max, - "aria-valuenow": this._value(), - "aria-valuetext": this._value(), - "title": this._value(), - "aria-labelledby": labelID - }); - - $.extend(this, { - slider: slider, - handle: handle, - control: control, - type: cType, - step: step, - max: max, - min: min, - valuebg: valuebg, - isRangeslider: isRangeslider, - dragging: false, - beforeStart: null, - userModified: false, - mouseMoved: false - }); - - if (isToggleSwitch) { - // TODO: restore original tabindex (if any) in a destroy method - origTabIndex = control.attr("tabindex"); - if (origTabIndex) { - handle.attr("tabindex", origTabIndex); - } - control.attr("tabindex", "-1").focus(function () { - $(this).blur(); - handle.focus(); - }); - - wrapper = document.createElement("div"); - wrapper.className = "ui-slider-inneroffset"; - - for (j = 0, length = domSlider.childNodes.length; j < length; j++) { - wrapper.appendChild(domSlider.childNodes[j]); - } - - domSlider.appendChild(wrapper); - - // slider.wrapInner( "
" ); - - // make the handle move with a smooth transition - handle.addClass("ui-slider-handle-snapping"); - - options = control.find("option"); - - for (i = 0, optionsCount = options.length; i < optionsCount; i++) { - side = !i ? "b" : "a"; - activeClass = !i ? "" : " " + $.mobile.activeBtnClass; - sliderImg = document.createElement("span"); - - sliderImg.className = ["ui-slider-label ui-slider-label-", side, activeClass].join(""); - sliderImg.setAttribute("role", "img"); - sliderImg.appendChild(document.createTextNode(options[i].innerHTML)); - $(sliderImg).prependTo(slider); - } - - self._labels = $(".ui-slider-label", slider); - - } - - // monitor the input for updated values - control.addClass(isToggleSwitch ? "ui-slider-switch" : "ui-slider-input"); - - this._on(control, { - "change": "_controlChange", - "keyup": "_controlKeyup", - "blur": "_controlBlur", - "mouseup": "_controlVMouseUp" - }); - - slider.on("mousedown", $.proxy(this._sliderVMouseDown, this)) - .on("click", false); - - // We have to instantiate a new function object for the unbind to work properly - // since the method itself is defined in the prototype (causing it to unbind everything) - this._on(document, { "mousemove": "_preventDocumentDrag" }); - this._on(slider.add(document), { "mouseup": "_sliderVMouseUp" }); - - slider.insertAfter(control); - - // wrap in a div for styling purposes - if (!isToggleSwitch && !isRangeslider) { - wrapper = this.options.mini ? "
" : "
"; - - control.add(slider).wrapAll(wrapper); - } - - // bind the handle event callbacks and set the context to the widget instance - this._on(this.handle, { - "mousedown": "_handleVMouseDown", - "keydown": "_handleKeydown", - "keyup": "_handleKeyup" - }); - - this.handle.on("click", false); - - //this._handleFormReset(); - - this.refresh(undefined, undefined, true); - }, - - _setOptions: function (options) { - if (options.theme !== undefined) { - this._setTheme(options.theme); - } - - if (options.trackTheme !== undefined) { - this._setTrackTheme(options.trackTheme); - } - - if (options.corners !== undefined) { - this._setCorners(options.corners); - } - - if (options.mini !== undefined) { - this._setMini(options.mini); - } - - if (options.highlight !== undefined) { - this._setHighlight(options.highlight); - } - - if (options.disabled !== undefined) { - this._setDisabled(options.disabled); - } - this._super(options); - }, - - _controlChange: function (event) { - // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again - if (this._trigger("controlchange", event) === false) { - return false; - } - if (!this.mouseMoved) { - this.refresh(this._value(), true); - } - }, - - _controlKeyup: function (/* event */) { // necessary? - this.refresh(this._value(), true, true); - }, - - _controlBlur: function (/* event */) { - this.refresh(this._value(), true); - }, - - // it appears the clicking the up and down buttons in chrome on - // range/number inputs doesn't trigger a change until the field is - // blurred. Here we check thif the value has changed and refresh - _controlVMouseUp: function (/* event */) { - this._checkedRefresh(); - }, - - // NOTE force focus on handle - _handleVMouseDown: function (/* event */) { - this.handle.focus(); - }, - - _handleKeydown: function (event) { - var index = this._value(); - if (this.options.disabled) { - return; - } - - // In all cases prevent the default and mark the handle as active - switch (event.keyCode) { - case $.ui.keyCode.HOME: - case $.ui.keyCode.END: - case $.ui.keyCode.PAGE_UP: - case $.ui.keyCode.PAGE_DOWN: - case $.ui.keyCode.UP: - case $.ui.keyCode.RIGHT: - case $.ui.keyCode.DOWN: - case $.ui.keyCode.LEFT: - event.preventDefault(); - - if (!this._keySliding) { - this._keySliding = true; - this.handle.addClass("ui-state-active"); /* TODO: We don't use this class for styling. Do we need to add it? */ - } - - break; - } - - // move the slider according to the keypress - switch (event.keyCode) { - case $.ui.keyCode.HOME: - this.refresh(this.min); - break; - case $.ui.keyCode.END: - this.refresh(this.max); - break; - case $.ui.keyCode.PAGE_UP: - case $.ui.keyCode.UP: - case $.ui.keyCode.RIGHT: - this.refresh(index + this.step); - break; - case $.ui.keyCode.PAGE_DOWN: - case $.ui.keyCode.DOWN: - case $.ui.keyCode.LEFT: - this.refresh(index - this.step); - break; - } - }, // remove active mark - - _handleKeyup: function (/* event */) { - if (this._keySliding) { - this._keySliding = false; - this.handle.removeClass("ui-state-active"); /* See comment above. */ - } - }, - - _sliderVMouseDown: function (event) { - // NOTE: we don't do this in refresh because we still want to - // support programmatic alteration of disabled inputs - if (this.options.disabled || !(event.which === 1 || event.which === 0 || event.which === undefined)) { - return false; - } - if (this._trigger("beforestart", event) === false) { - return false; - } - this.dragging = true; - this.userModified = false; - this.mouseMoved = false; - - if (this.isToggleSwitch) { - this.beforeStart = this.element[0].selectedIndex; - } - - this.refresh(event); - this._trigger("start"); - return false; - }, - - _sliderVMouseUp: function () { - if (this.dragging) { - this.dragging = false; - - if (this.isToggleSwitch) { - // make the handle move with a smooth transition - this.handle.addClass("ui-slider-handle-snapping"); - - if (this.mouseMoved) { - // this is a drag, change the value only if user dragged enough - if (this.userModified) { - this.refresh(this.beforeStart === 0 ? 1 : 0); - } else { - this.refresh(this.beforeStart); - } - } else { - // this is just a click, change the value - this.refresh(this.beforeStart === 0 ? 1 : 0); - } - } - - this.mouseMoved = false; - this._trigger("stop"); - return false; - } - }, - - _preventDocumentDrag: function (event) { - // NOTE: we don't do this in refresh because we still want to - // support programmatic alteration of disabled inputs - if (this._trigger("drag", event) === false) { - return false; - } - if (this.dragging && !this.options.disabled) { - - // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event - this.mouseMoved = true; - - if (this.isToggleSwitch) { - // make the handle move in sync with the mouse - this.handle.removeClass("ui-slider-handle-snapping"); - } - - this.refresh(event); - - // only after refresh() you can calculate this.userModified - this.userModified = this.beforeStart !== this.element[0].selectedIndex; - return false; - } - }, - - _checkedRefresh: function () { - if (this.value !== this._value()) { - this.refresh(this._value()); - } - }, - - _value: function () { - return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat(this.element.val()); - }, - - _reset: function () { - this.refresh(undefined, false, true); - }, - - refresh: function (val, isfromControl, preventInputUpdate) { - // NOTE: we don't return here because we want to support programmatic - // alteration of the input value, which should still update the slider - - var self = this, - parentTheme = $.mobile.getAttribute(this.element[0], "theme"), - theme = this.options.theme || parentTheme, - themeClass = theme ? " ui-btn-" + theme : "", - trackTheme = this.options.trackTheme || parentTheme, - trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", - cornerClass = this.options.corners ? " ui-corner-all" : "", - miniClass = this.options.mini ? " ui-mini" : "", - left, width, data, tol, - pxStep, percent, - control, isInput, optionElements, min, max, step, - newval, valModStep, alignValue, percentPerStep, - handlePercent, aPercent, bPercent, - valueChanged; - - self.slider[0].className = [this.isToggleSwitch ? "ui-slider ui-slider-switch ui-slider-track ui-shadow-inset" : "ui-slider-track ui-shadow-inset", trackThemeClass, cornerClass, miniClass].join(""); - if (this.options.disabled || this.element.prop("disabled")) { - this.disable(); - } - - // set the stored value for comparison later - this.value = this._value(); - if (this.options.highlight && !this.isToggleSwitch && this.slider.find(".ui-slider-bg").length === 0) { - this.valuebg = (function () { - var bg = document.createElement("div"); - bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; - return $(bg).prependTo(self.slider); - })(); - } - this.handle.addClass("ui-btn" + themeClass + " ui-shadow"); - - control = this.element; - isInput = !this.isToggleSwitch; - optionElements = isInput ? [] : control.find("option"); - min = isInput ? parseFloat(control.attr("min")) : 0; - max = isInput ? parseFloat(control.attr("max")) : optionElements.length - 1; - step = (isInput && parseFloat(control.attr("step")) > 0) ? parseFloat(control.attr("step")) : 1; - - if (typeof val === "object") { - data = val; - // a slight tolerance helped get to the ends of the slider - tol = 8; - - left = this.slider.offset().left; - width = this.slider.width(); - pxStep = width / ((max - min) / step); - if (!this.dragging || - data.pageX < left - tol || - data.pageX > left + width + tol) { - return; - } - if (pxStep > 1) { - percent = ((data.pageX - left) / width) * 100; - } else { - percent = Math.round(((data.pageX - left) / width) * 100); - } - } else { - if (val == null) { - val = isInput ? parseFloat(control.val() || 0) : control[0].selectedIndex; - } - percent = (parseFloat(val) - min) / (max - min) * 100; - } - - if (isNaN(percent)) { - return; - } - - newval = (percent / 100) * (max - min) + min; - - //from jQuery UI slider, the following source will round to the nearest step - valModStep = (newval - min) % step; - alignValue = newval - valModStep; - - if (Math.abs(valModStep) * 2 >= step) { - alignValue += (valModStep > 0) ? step : (-step); - } - - percentPerStep = 100 / ((max - min) / step); - // Since JavaScript has problems with large floats, round - // the final value to 5 digits after the decimal point (see jQueryUI: #4124) - newval = parseFloat(alignValue.toFixed(5)); - - if (typeof pxStep === "undefined") { - pxStep = width / ((max - min) / step); - } - if (pxStep > 1 && isInput) { - percent = (newval - min) * percentPerStep * (1 / step); - } - if (percent < 0) { - percent = 0; - } - - if (percent > 100) { - percent = 100; - } - - if (newval < min) { - newval = min; - } - - if (newval > max) { - newval = max; - } - - this.handle.css("left", percent + "%"); - - this.handle[0].setAttribute("aria-valuenow", isInput ? newval : optionElements.eq(newval).attr("value")); - - this.handle[0].setAttribute("aria-valuetext", isInput ? newval : optionElements.eq(newval).text()); - - this.handle[0].setAttribute("title", isInput ? newval : optionElements.eq(newval).text()); - - if (this.valuebg) { - this.valuebg.css("width", percent + "%"); - } - - // drag the label widths - if (this._labels) { - handlePercent = this.handle.width() / this.slider.width() * 100; - aPercent = percent && handlePercent + (100 - handlePercent) * percent / 100; - bPercent = percent === 100 ? 0 : Math.min(handlePercent + 100 - aPercent, 100); - - this._labels.each(function () { - var ab = $(this).hasClass("ui-slider-label-a"); - $(this).width((ab ? aPercent : bPercent) + "%"); - }); - } - - if (!preventInputUpdate) { - valueChanged = false; - - // update control"s value - if (isInput) { - valueChanged = parseFloat(control.val()) !== newval; - control.val(newval); - } else { - valueChanged = control[0].selectedIndex !== newval; - control[0].selectedIndex = newval; - } - if (this._trigger("beforechange", val) === false) { - return false; - } - if (!isfromControl && valueChanged) { - control.trigger("change"); - } - } - }, - - _setHighlight: function (value) { - value = !!value; - if (value) { - this.options.highlight = !!value; - this.refresh(); - } else if (this.valuebg) { - this.valuebg.remove(); - this.valuebg = false; - } - }, - - _setTheme: function (value) { - this.handle - .removeClass("ui-btn-" + this.options.theme) - .addClass("ui-btn-" + value); - - var currentTheme = this.options.theme ? this.options.theme : "inherit", - newTheme = value ? value : "inherit"; - - this.control - .removeClass("ui-body-" + currentTheme) - .addClass("ui-body-" + newTheme); - }, - - _setTrackTheme: function (value) { - var currentTrackTheme = this.options.trackTheme ? this.options.trackTheme : "inherit", - newTrackTheme = value ? value : "inherit"; - - this.slider - .removeClass("ui-body-" + currentTrackTheme) - .addClass("ui-body-" + newTrackTheme); - }, - - _setMini: function (value) { - value = !!value; - if (!this.isToggleSwitch && !this.isRangeslider) { - this.slider.parent().toggleClass("ui-mini", value); - this.element.toggleClass("ui-mini", value); - } - this.slider.toggleClass("ui-mini", value); - }, - - _setCorners: function (value) { - this.slider.toggleClass("ui-corner-all", value); - - if (!this.isToggleSwitch) { - this.control.toggleClass("ui-corner-all", value); - } - }, - - _setDisabled: function (value) { - value = !!value; - this.element.prop("disabled", value); - this.slider - .toggleClass("ui-state-disabled", value) - .attr("aria-disabled", value); - - this.element.toggleClass("ui-state-disabled", value); - } - - }, $.mobile.behaviors.formReset)); - - $.widget("mobile.rangeslider", $.extend({ - - options: { - theme: null, - trackTheme: null, - corners: true, - mini: false, - highlight: true - }, - - _create: function () { - var $el = this.element, - elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider", - _inputFirst = $el.find("input").first(), - _inputLast = $el.find("input").last(), - _label = $el.find("label").first(), - _sliderWidgetFirst = $.data(_inputFirst.get(0), "mobile-slider") || - $.data(_inputFirst.slider().get(0), "mobile-slider"), - _sliderWidgetLast = $.data(_inputLast.get(0), "mobile-slider") || - $.data(_inputLast.slider().get(0), "mobile-slider"), - _sliderFirst = _sliderWidgetFirst.slider, - _sliderLast = _sliderWidgetLast.slider, - firstHandle = _sliderWidgetFirst.handle, - _sliders = $("
").appendTo($el); - - _inputFirst.addClass("ui-rangeslider-first"); - _inputLast.addClass("ui-rangeslider-last"); - $el.addClass(elClass); - - _sliderFirst.appendTo(_sliders); - _sliderLast.appendTo(_sliders); - _label.insertBefore($el); - firstHandle.prependTo(_sliderLast); - - $.extend(this, { - _inputFirst: _inputFirst, - _inputLast: _inputLast, - _sliderFirst: _sliderFirst, - _sliderLast: _sliderLast, - _label: _label, - _targetVal: null, - _sliderTarget: false, - _sliders: _sliders, - _proxy: false - }); - - this.refresh(); - this._on(this.element.find("input.ui-slider-input"), { - "slidebeforestart": "_slidebeforestart", - "slidestop": "_slidestop", - "slidedrag": "_slidedrag", - "slidebeforechange": "_change", - "blur": "_change", - "keyup": "_change" - }); - this._on({ - "mousedown": "_change" - }); - this._on(this.element.closest("form"), { - "reset": "_handleReset" - }); - this._on(firstHandle, { - "mousedown": "_dragFirstHandle" - }); - }, - _handleReset: function () { - var self = this; - //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet - setTimeout(function () { - self._updateHighlight(); - }, 0); - }, - - _dragFirstHandle: function (event) { - //if the first handle is dragged send the event to the first slider - $.data(this._inputFirst.get(0), "mobile-slider").dragging = true; - $.data(this._inputFirst.get(0), "mobile-slider").refresh(event); - $.data(this._inputFirst.get(0), "mobile-slider")._trigger("start"); - return false; - }, - - _slidedrag: function (event) { - var first = $(event.target).is(this._inputFirst), - otherSlider = (first) ? this._inputLast : this._inputFirst; - - this._sliderTarget = false; - //if the drag was initiated on an extreme and the other handle is focused send the events to - //the closest handle - if ((this._proxy === "first" && first) || (this._proxy === "last" && !first)) { - $.data(otherSlider.get(0), "mobile-slider").dragging = true; - $.data(otherSlider.get(0), "mobile-slider").refresh(event); - return false; - } - }, - - _slidestop: function (event) { - var first = $(event.target).is(this._inputFirst); - - this._proxy = false; - //this stops dragging of the handle and brings the active track to the front - //this makes clicks on the track go the the last handle used - this.element.find("input").trigger("mouseup"); - this._sliderFirst.css("z-index", first ? 1 : ""); - }, - - _slidebeforestart: function (event) { - this._sliderTarget = false; - //if the track is the target remember this and the original value - if ($(event.originalEvent.target).hasClass("ui-slider-track")) { - this._sliderTarget = true; - this._targetVal = $(event.target).val(); - } - }, - - _setOptions: function (options) { - if (options.theme !== undefined) { - this._setTheme(options.theme); - } - - if (options.trackTheme !== undefined) { - this._setTrackTheme(options.trackTheme); - } - - if (options.mini !== undefined) { - this._setMini(options.mini); - } - - if (options.highlight !== undefined) { - this._setHighlight(options.highlight); - } - - if (options.disabled !== undefined) { - this._setDisabled(options.disabled); - } - - this._super(options); - this.refresh(); - }, - - refresh: function () { - var $el = this.element, - o = this.options; - - if (this._inputFirst.is(":disabled") || this._inputLast.is(":disabled")) { - this.options.disabled = true; - } - - $el.find("input").slider({ - theme: o.theme, - trackTheme: o.trackTheme, - disabled: o.disabled, - corners: o.corners, - mini: o.mini, - highlight: o.highlight - }).slider("refresh"); - this._updateHighlight(); - }, - - _change: function (event) { - if (event.type === "keyup") { - this._updateHighlight(); - return false; - } - - var self = this, - min = parseFloat(this._inputFirst.val(), 10), - max = parseFloat(this._inputLast.val(), 10), - first = $(event.target).hasClass("ui-rangeslider-first"), - thisSlider = first ? this._inputFirst : this._inputLast, - otherSlider = first ? this._inputLast : this._inputFirst; - - if ((this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle"))) { - thisSlider.blur(); - } else if (event.type === "mousedown") { - return; - } - if (min > max && !this._sliderTarget) { - //this prevents min from being greater then max - thisSlider.val(first ? max : min).slider("refresh"); - this._trigger("normalize"); - } else if (min > max) { - //this makes it so clicks on the target on either extreme go to the closest handle - thisSlider.val(this._targetVal).slider("refresh"); - - //You must wait for the stack to unwind so first slider is updated before updating second - setTimeout(function () { - otherSlider.val(first ? min : max).slider("refresh"); - $.data(otherSlider.get(0), "mobile-slider").handle.focus(); - self._sliderFirst.css("z-index", first ? "" : 1); - self._trigger("normalize"); - }, 0); - this._proxy = (first) ? "first" : "last"; - } - //fixes issue where when both _sliders are at min they cannot be adjusted - if (min === max) { - $.data(thisSlider.get(0), "mobile-slider").handle.css("z-index", 1); - $.data(otherSlider.get(0), "mobile-slider").handle.css("z-index", 0); - } else { - $.data(otherSlider.get(0), "mobile-slider").handle.css("z-index", ""); - $.data(thisSlider.get(0), "mobile-slider").handle.css("z-index", ""); - } - - this._updateHighlight(); - - if (min >= max) { - return false; - } - }, - - _updateHighlight: function () { - var min = parseInt($.data(this._inputFirst.get(0), "mobile-slider").handle.get(0).style.left, 10), - max = parseInt($.data(this._inputLast.get(0), "mobile-slider").handle.get(0).style.left, 10), - width = (max - min); - - this.element.find(".ui-slider-bg").css({ - "margin-left": min + "%", - "width": width + "%" - }); - }, - - _setTheme: function (value) { - this._inputFirst.slider("option", "theme", value); - this._inputLast.slider("option", "theme", value); - }, - - _setTrackTheme: function (value) { - this._inputFirst.slider("option", "trackTheme", value); - this._inputLast.slider("option", "trackTheme", value); - }, - - _setMini: function (value) { - this._inputFirst.slider("option", "mini", value); - this._inputLast.slider("option", "mini", value); - this.element.toggleClass("ui-mini", !!value); - }, - - _setHighlight: function (value) { - this._inputFirst.slider("option", "highlight", value); - this._inputLast.slider("option", "highlight", value); - }, - - _setDisabled: function (value) { - this._inputFirst.prop("disabled", value); - this._inputLast.prop("disabled", value); - }, - - _destroy: function () { - this._label.prependTo(this.element); - this.element.removeClass("ui-rangeslider ui-mini"); - this._inputFirst.after(this._sliderFirst); - this._inputLast.after(this._sliderLast); - this._sliders.remove(); - this.element.find("input").removeClass("ui-rangeslider-first ui-rangeslider-last").slider("destroy"); - } - - }, $.mobile.behaviors.formReset)); - - var popup; - - function getPopup() { - if (!popup) { - popup = $("
", { - "class": "ui-slider-popup ui-shadow ui-corner-all" - }); - } - return popup.clone(); - } - - $.widget("mobile.slider", $.mobile.slider, { - options: { - popupEnabled: false, - showValue: false - }, - - _create: function () { - this._super(); - - $.extend(this, { - _currentValue: null, - _popup: null, - _popupVisible: false - }); - - this._setOption("popupEnabled", this.options.popupEnabled); - - this._on(this.handle, { "mousedown": "_showPopup" }); - this._on(this.slider.add(this.document), { "mouseup": "_hidePopup" }); - this._refresh(); - }, - - // position the popup centered 5px above the handle - _positionPopup: function () { - var dstOffset = this.handle.offset(); - - this._popup.offset({ - left: dstOffset.left + (this.handle.width() - this._popup.width()) / 2, - top: dstOffset.top - this._popup.outerHeight() - 5 - }); - }, - - _setOption: function (key, value) { - this._super(key, value); - - if (key === "showValue") { - this.handle.html(value && !this.options.mini ? this._value() : ""); - } else if (key === "popupEnabled") { - if (value && !this._popup) { - this._popup = getPopup() - .addClass("ui-body-" + (this.options.theme || "a")) - .hide() - .insertBefore(this.element); - } - } - }, - - // show value on the handle and in popup - refresh: function () { - this._super.apply(this, arguments); - this._refresh(); - }, - - _refresh: function () { - var o = this.options, newValue; - - if (o.popupEnabled) { - // remove the title attribute from the handle (which is - // responsible for the annoying tooltip); NB we have - // to do it here as the jqm slider sets it every time - // the slider's value changes :( - this.handle.removeAttr("title"); - } - - newValue = this._value(); - if (newValue === this._currentValue) { - return; - } - this._currentValue = newValue; - - if (o.popupEnabled && this._popup) { - this._positionPopup(); - this._popup.html(newValue); - } - - if (o.showValue && !this.options.mini) { - this.handle.html(newValue); - } - }, - - _showPopup: function () { - if (this.options.popupEnabled && !this._popupVisible) { - this.handle.html(""); - this._popup.show(); - this._positionPopup(); - this._popupVisible = true; - } - }, - - _hidePopup: function () { - var o = this.options; - - if (o.popupEnabled && this._popupVisible) { - if (o.showValue && !o.mini) { - this.handle.html(this._value()); - } - this._popup.hide(); - this._popupVisible = false; - } - } - }); - -}); \ No newline at end of file +define(["jqmwidget"],function(){function getPopup(){return popup||(popup=$("
",{class:"ui-slider-popup ui-shadow ui-corner-all"})),popup.clone()}var rbrace=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/;$.extend($.mobile,{getAttribute:function(element,key){var data;element=element.jquery?element[0]:element,element&&element.getAttribute&&(data=element.getAttribute("data-"+key));try{data="true"===data||"false"!==data&&("null"===data?null:+data+""===data?+data:rbrace.test(data)?JSON.parse(data):data)}catch(err){}return data}}),function($,undefined){$.ui=$.ui||{},$.extend($.ui,{version:"c0ab71056b936627e8a7821f03c044aec6280a40",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),$.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase())}(jQuery),$.widget("mobile.slider",$.extend({initSelector:"input[type='range']:not([data-role='none'])",widgetEventPrefix:"slide",options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!1},_create:function(){var options,wrapper,j,length,i,optionsCount,origTabIndex,side,activeClass,sliderImg,self=this,control=this.element,trackTheme=this.options.trackTheme||$.mobile.getAttribute(control[0],"theme"),trackThemeClass=trackTheme?" ui-bar-"+trackTheme:" ui-bar-inherit",cornerClass=this.options.corners||control.data("corners")?" ui-corner-all":"",miniClass=this.options.mini||control.data("mini")?" ui-mini":"",cType=control[0].nodeName.toLowerCase(),isToggleSwitch="select"===cType,isRangeslider=control.parent().is("[data-role='rangeslider']"),selectClass=isToggleSwitch?"ui-slider-switch":"",controlID=control.attr("id"),$label=$("[for='"+controlID+"']"),labelID=$label.attr("id")||controlID+"-label",min=isToggleSwitch?0:parseFloat(control.attr("min")),max=isToggleSwitch?control.find("option").length-1:parseFloat(control.attr("max")),step=window.parseFloat(control.attr("step")||1),domHandle=document.createElement("a"),handle=$(domHandle),domSlider=document.createElement("div"),slider=$(domSlider),valuebg=!(!this.options.highlight||isToggleSwitch)&&function(){var bg=document.createElement("div");return bg.className="ui-slider-bg "+$.mobile.activeBtnClass,$(bg).prependTo(slider)}();if($label.attr("id",labelID),this.isToggleSwitch=isToggleSwitch,domHandle.setAttribute("href","#"),domSlider.setAttribute("role","application"),domSlider.className=[this.isToggleSwitch?"ui-slider ui-slider-track ui-shadow-inset ":"ui-slider-track ui-shadow-inset ",selectClass,trackThemeClass,cornerClass,miniClass].join(""),domHandle.className="ui-slider-handle",domSlider.appendChild(domHandle),handle.attr({role:"slider","aria-valuemin":min,"aria-valuemax":max,"aria-valuenow":this._value(),"aria-valuetext":this._value(),title:this._value(),"aria-labelledby":labelID}),$.extend(this,{slider:slider,handle:handle,control:control,type:cType,step:step,max:max,min:min,valuebg:valuebg,isRangeslider:isRangeslider,dragging:!1,beforeStart:null,userModified:!1,mouseMoved:!1}),isToggleSwitch){for(origTabIndex=control.attr("tabindex"),origTabIndex&&handle.attr("tabindex",origTabIndex),control.attr("tabindex","-1").focus(function(){$(this).blur(),handle.focus()}),wrapper=document.createElement("div"),wrapper.className="ui-slider-inneroffset",j=0,length=domSlider.childNodes.length;j":"
",control.add(slider).wrapAll(wrapper)),this._on(this.handle,{mousedown:"_handleVMouseDown",keydown:"_handleKeydown",keyup:"_handleKeyup"}),this.handle.on("click",!1),this.refresh(void 0,void 0,!0)},_setOptions:function(options){void 0!==options.theme&&this._setTheme(options.theme),void 0!==options.trackTheme&&this._setTrackTheme(options.trackTheme),void 0!==options.corners&&this._setCorners(options.corners),void 0!==options.mini&&this._setMini(options.mini),void 0!==options.highlight&&this._setHighlight(options.highlight),void 0!==options.disabled&&this._setDisabled(options.disabled),this._super(options)},_controlChange:function(event){return this._trigger("controlchange",event)!==!1&&void(this.mouseMoved||this.refresh(this._value(),!0))},_controlKeyup:function(){this.refresh(this._value(),!0,!0)},_controlBlur:function(){this.refresh(this._value(),!0)},_controlVMouseUp:function(){this._checkedRefresh()},_handleVMouseDown:function(){this.handle.focus()},_handleKeydown:function(event){var index=this._value();if(!this.options.disabled){switch(event.keyCode){case $.ui.keyCode.HOME:case $.ui.keyCode.END:case $.ui.keyCode.PAGE_UP:case $.ui.keyCode.PAGE_DOWN:case $.ui.keyCode.UP:case $.ui.keyCode.RIGHT:case $.ui.keyCode.DOWN:case $.ui.keyCode.LEFT:event.preventDefault(),this._keySliding||(this._keySliding=!0,this.handle.addClass("ui-state-active"))}switch(event.keyCode){case $.ui.keyCode.HOME:this.refresh(this.min);break;case $.ui.keyCode.END:this.refresh(this.max);break;case $.ui.keyCode.PAGE_UP:case $.ui.keyCode.UP:case $.ui.keyCode.RIGHT:this.refresh(index+this.step);break;case $.ui.keyCode.PAGE_DOWN:case $.ui.keyCode.DOWN:case $.ui.keyCode.LEFT:this.refresh(index-this.step)}}},_handleKeyup:function(){this._keySliding&&(this._keySliding=!1,this.handle.removeClass("ui-state-active"))},_sliderVMouseDown:function(event){return!(this.options.disabled||1!==event.which&&0!==event.which&&void 0!==event.which)&&(this._trigger("beforestart",event)!==!1&&(this.dragging=!0,this.userModified=!1,this.mouseMoved=!1,this.isToggleSwitch&&(this.beforeStart=this.element[0].selectedIndex),this.refresh(event),this._trigger("start"),!1))},_sliderVMouseUp:function(){if(this.dragging)return this.dragging=!1,this.isToggleSwitch&&(this.handle.addClass("ui-slider-handle-snapping"),this.mouseMoved?this.userModified?this.refresh(0===this.beforeStart?1:0):this.refresh(this.beforeStart):this.refresh(0===this.beforeStart?1:0)),this.mouseMoved=!1,this._trigger("stop"),!1},_preventDocumentDrag:function(event){return this._trigger("drag",event)!==!1&&(this.dragging&&!this.options.disabled?(this.mouseMoved=!0,this.isToggleSwitch&&this.handle.removeClass("ui-slider-handle-snapping"),this.refresh(event),this.userModified=this.beforeStart!==this.element[0].selectedIndex,!1):void 0)},_checkedRefresh:function(){this.value!==this._value()&&this.refresh(this._value())},_value:function(){return this.isToggleSwitch?this.element[0].selectedIndex:parseFloat(this.element.val())},_reset:function(){this.refresh(void 0,!1,!0)},refresh:function(val,isfromControl,preventInputUpdate){var left,width,data,tol,pxStep,percent,control,isInput,optionElements,min,max,step,newval,valModStep,alignValue,percentPerStep,handlePercent,aPercent,bPercent,valueChanged,self=this,parentTheme=$.mobile.getAttribute(this.element[0],"theme"),theme=this.options.theme||parentTheme,themeClass=theme?" ui-btn-"+theme:"",trackTheme=this.options.trackTheme||parentTheme,trackThemeClass=trackTheme?" ui-bar-"+trackTheme:" ui-bar-inherit",cornerClass=this.options.corners?" ui-corner-all":"",miniClass=this.options.mini?" ui-mini":"";if(self.slider[0].className=[this.isToggleSwitch?"ui-slider ui-slider-switch ui-slider-track ui-shadow-inset":"ui-slider-track ui-shadow-inset",trackThemeClass,cornerClass,miniClass].join(""),(this.options.disabled||this.element.prop("disabled"))&&this.disable(),this.value=this._value(),this.options.highlight&&!this.isToggleSwitch&&0===this.slider.find(".ui-slider-bg").length&&(this.valuebg=function(){var bg=document.createElement("div");return bg.className="ui-slider-bg "+$.mobile.activeBtnClass,$(bg).prependTo(self.slider)}()),this.handle.addClass("ui-btn"+themeClass+" ui-shadow"),control=this.element,isInput=!this.isToggleSwitch,optionElements=isInput?[]:control.find("option"),min=isInput?parseFloat(control.attr("min")):0,max=isInput?parseFloat(control.attr("max")):optionElements.length-1,step=isInput&&parseFloat(control.attr("step"))>0?parseFloat(control.attr("step")):1,"object"==typeof val){if(data=val,tol=8,left=this.slider.offset().left,width=this.slider.width(),pxStep=width/((max-min)/step),!this.dragging||data.pageXleft+width+tol)return;percent=pxStep>1?(data.pageX-left)/width*100:Math.round((data.pageX-left)/width*100)}else null==val&&(val=isInput?parseFloat(control.val()||0):control[0].selectedIndex),percent=(parseFloat(val)-min)/(max-min)*100;if(!isNaN(percent)&&(newval=percent/100*(max-min)+min,valModStep=(newval-min)%step,alignValue=newval-valModStep,2*Math.abs(valModStep)>=step&&(alignValue+=valModStep>0?step:-step),percentPerStep=100/((max-min)/step),newval=parseFloat(alignValue.toFixed(5)),"undefined"==typeof pxStep&&(pxStep=width/((max-min)/step)),pxStep>1&&isInput&&(percent=(newval-min)*percentPerStep*(1/step)),percent<0&&(percent=0),percent>100&&(percent=100),newvalmax&&(newval=max),this.handle.css("left",percent+"%"),this.handle[0].setAttribute("aria-valuenow",isInput?newval:optionElements.eq(newval).attr("value")),this.handle[0].setAttribute("aria-valuetext",isInput?newval:optionElements.eq(newval).text()),this.handle[0].setAttribute("title",isInput?newval:optionElements.eq(newval).text()),this.valuebg&&this.valuebg.css("width",percent+"%"),this._labels&&(handlePercent=this.handle.width()/this.slider.width()*100,aPercent=percent&&handlePercent+(100-handlePercent)*percent/100,bPercent=100===percent?0:Math.min(handlePercent+100-aPercent,100),this._labels.each(function(){var ab=$(this).hasClass("ui-slider-label-a");$(this).width((ab?aPercent:bPercent)+"%")})),!preventInputUpdate)){if(valueChanged=!1,isInput?(valueChanged=parseFloat(control.val())!==newval,control.val(newval)):(valueChanged=control[0].selectedIndex!==newval,control[0].selectedIndex=newval),this._trigger("beforechange",val)===!1)return!1;!isfromControl&&valueChanged&&control.trigger("change")}},_setHighlight:function(value){value=!!value,value?(this.options.highlight=!!value,this.refresh()):this.valuebg&&(this.valuebg.remove(),this.valuebg=!1)},_setTheme:function(value){this.handle.removeClass("ui-btn-"+this.options.theme).addClass("ui-btn-"+value);var currentTheme=this.options.theme?this.options.theme:"inherit",newTheme=value?value:"inherit";this.control.removeClass("ui-body-"+currentTheme).addClass("ui-body-"+newTheme)},_setTrackTheme:function(value){var currentTrackTheme=this.options.trackTheme?this.options.trackTheme:"inherit",newTrackTheme=value?value:"inherit";this.slider.removeClass("ui-body-"+currentTrackTheme).addClass("ui-body-"+newTrackTheme)},_setMini:function(value){value=!!value,this.isToggleSwitch||this.isRangeslider||(this.slider.parent().toggleClass("ui-mini",value),this.element.toggleClass("ui-mini",value)),this.slider.toggleClass("ui-mini",value)},_setCorners:function(value){this.slider.toggleClass("ui-corner-all",value),this.isToggleSwitch||this.control.toggleClass("ui-corner-all",value)},_setDisabled:function(value){value=!!value,this.element.prop("disabled",value),this.slider.toggleClass("ui-state-disabled",value).attr("aria-disabled",value),this.element.toggleClass("ui-state-disabled",value)}},$.mobile.behaviors.formReset)),$.widget("mobile.rangeslider",$.extend({options:{theme:null,trackTheme:null,corners:!0,mini:!1,highlight:!0},_create:function(){var $el=this.element,elClass=this.options.mini?"ui-rangeslider ui-mini":"ui-rangeslider",_inputFirst=$el.find("input").first(),_inputLast=$el.find("input").last(),_label=$el.find("label").first(),_sliderWidgetFirst=$.data(_inputFirst.get(0),"mobile-slider")||$.data(_inputFirst.slider().get(0),"mobile-slider"),_sliderWidgetLast=$.data(_inputLast.get(0),"mobile-slider")||$.data(_inputLast.slider().get(0),"mobile-slider"),_sliderFirst=_sliderWidgetFirst.slider,_sliderLast=_sliderWidgetLast.slider,firstHandle=_sliderWidgetFirst.handle,_sliders=$("
").appendTo($el);_inputFirst.addClass("ui-rangeslider-first"),_inputLast.addClass("ui-rangeslider-last"),$el.addClass(elClass),_sliderFirst.appendTo(_sliders),_sliderLast.appendTo(_sliders),_label.insertBefore($el),firstHandle.prependTo(_sliderLast),$.extend(this,{_inputFirst:_inputFirst,_inputLast:_inputLast,_sliderFirst:_sliderFirst,_sliderLast:_sliderLast,_label:_label,_targetVal:null,_sliderTarget:!1,_sliders:_sliders,_proxy:!1}),this.refresh(),this._on(this.element.find("input.ui-slider-input"),{slidebeforestart:"_slidebeforestart",slidestop:"_slidestop",slidedrag:"_slidedrag",slidebeforechange:"_change",blur:"_change",keyup:"_change"}),this._on({mousedown:"_change"}),this._on(this.element.closest("form"),{reset:"_handleReset"}),this._on(firstHandle,{mousedown:"_dragFirstHandle"})},_handleReset:function(){var self=this;setTimeout(function(){self._updateHighlight()},0)},_dragFirstHandle:function(event){return $.data(this._inputFirst.get(0),"mobile-slider").dragging=!0,$.data(this._inputFirst.get(0),"mobile-slider").refresh(event),$.data(this._inputFirst.get(0),"mobile-slider")._trigger("start"),!1},_slidedrag:function(event){var first=$(event.target).is(this._inputFirst),otherSlider=first?this._inputLast:this._inputFirst;if(this._sliderTarget=!1,"first"===this._proxy&&first||"last"===this._proxy&&!first)return $.data(otherSlider.get(0),"mobile-slider").dragging=!0,$.data(otherSlider.get(0),"mobile-slider").refresh(event),!1},_slidestop:function(event){var first=$(event.target).is(this._inputFirst);this._proxy=!1,this.element.find("input").trigger("mouseup"),this._sliderFirst.css("z-index",first?1:"")},_slidebeforestart:function(event){this._sliderTarget=!1,$(event.originalEvent.target).hasClass("ui-slider-track")&&(this._sliderTarget=!0,this._targetVal=$(event.target).val())},_setOptions:function(options){void 0!==options.theme&&this._setTheme(options.theme),void 0!==options.trackTheme&&this._setTrackTheme(options.trackTheme),void 0!==options.mini&&this._setMini(options.mini),void 0!==options.highlight&&this._setHighlight(options.highlight),void 0!==options.disabled&&this._setDisabled(options.disabled),this._super(options),this.refresh()},refresh:function(){var $el=this.element,o=this.options;(this._inputFirst.is(":disabled")||this._inputLast.is(":disabled"))&&(this.options.disabled=!0),$el.find("input").slider({theme:o.theme,trackTheme:o.trackTheme,disabled:o.disabled,corners:o.corners,mini:o.mini,highlight:o.highlight}).slider("refresh"),this._updateHighlight()},_change:function(event){if("keyup"===event.type)return this._updateHighlight(),!1;var self=this,min=parseFloat(this._inputFirst.val(),10),max=parseFloat(this._inputLast.val(),10),first=$(event.target).hasClass("ui-rangeslider-first"),thisSlider=first?this._inputFirst:this._inputLast,otherSlider=first?this._inputLast:this._inputFirst;if(this._inputFirst.val()>this._inputLast.val()&&"mousedown"===event.type&&!$(event.target).hasClass("ui-slider-handle"))thisSlider.blur();else if("mousedown"===event.type)return;return min>max&&!this._sliderTarget?(thisSlider.val(first?max:min).slider("refresh"),this._trigger("normalize")):min>max&&(thisSlider.val(this._targetVal).slider("refresh"),setTimeout(function(){otherSlider.val(first?min:max).slider("refresh"),$.data(otherSlider.get(0),"mobile-slider").handle.focus(),self._sliderFirst.css("z-index",first?"":1),self._trigger("normalize")},0),this._proxy=first?"first":"last"),min===max?($.data(thisSlider.get(0),"mobile-slider").handle.css("z-index",1),$.data(otherSlider.get(0),"mobile-slider").handle.css("z-index",0)):($.data(otherSlider.get(0),"mobile-slider").handle.css("z-index",""),$.data(thisSlider.get(0),"mobile-slider").handle.css("z-index","")),this._updateHighlight(),!(min>=max)&&void 0},_updateHighlight:function(){var min=parseInt($.data(this._inputFirst.get(0),"mobile-slider").handle.get(0).style.left,10),max=parseInt($.data(this._inputLast.get(0),"mobile-slider").handle.get(0).style.left,10),width=max-min;this.element.find(".ui-slider-bg").css({"margin-left":min+"%",width:width+"%"})},_setTheme:function(value){this._inputFirst.slider("option","theme",value),this._inputLast.slider("option","theme",value)},_setTrackTheme:function(value){this._inputFirst.slider("option","trackTheme",value),this._inputLast.slider("option","trackTheme",value)},_setMini:function(value){this._inputFirst.slider("option","mini",value),this._inputLast.slider("option","mini",value),this.element.toggleClass("ui-mini",!!value)},_setHighlight:function(value){this._inputFirst.slider("option","highlight",value),this._inputLast.slider("option","highlight",value)},_setDisabled:function(value){this._inputFirst.prop("disabled",value),this._inputLast.prop("disabled",value)},_destroy:function(){this._label.prependTo(this.element),this.element.removeClass("ui-rangeslider ui-mini"),this._inputFirst.after(this._sliderFirst),this._inputLast.after(this._sliderLast),this._sliders.remove(),this.element.find("input").removeClass("ui-rangeslider-first ui-rangeslider-last").slider("destroy")}},$.mobile.behaviors.formReset));var popup;$.widget("mobile.slider",$.mobile.slider,{options:{popupEnabled:!1,showValue:!1},_create:function(){this._super(),$.extend(this,{_currentValue:null,_popup:null,_popupVisible:!1}),this._setOption("popupEnabled",this.options.popupEnabled),this._on(this.handle,{mousedown:"_showPopup"}),this._on(this.slider.add(this.document),{mouseup:"_hidePopup"}),this._refresh()},_positionPopup:function(){var dstOffset=this.handle.offset();this._popup.offset({left:dstOffset.left+(this.handle.width()-this._popup.width())/2,top:dstOffset.top-this._popup.outerHeight()-5})},_setOption:function(key,value){this._super(key,value),"showValue"===key?this.handle.html(value&&!this.options.mini?this._value():""):"popupEnabled"===key&&value&&!this._popup&&(this._popup=getPopup().addClass("ui-body-"+(this.options.theme||"a")).hide().insertBefore(this.element))},refresh:function(){this._super.apply(this,arguments),this._refresh()},_refresh:function(){var newValue,o=this.options;o.popupEnabled&&this.handle.removeAttr("title"),newValue=this._value(),newValue!==this._currentValue&&(this._currentValue=newValue,o.popupEnabled&&this._popup&&(this._positionPopup(),this._popup.html(newValue)),o.showValue&&!this.options.mini&&this.handle.html(newValue))},_showPopup:function(){this.options.popupEnabled&&!this._popupVisible&&(this.handle.html(""),this._popup.show(),this._positionPopup(),this._popupVisible=!0)},_hidePopup:function(){var o=this.options;o.popupEnabled&&this._popupVisible&&(o.showValue&&!o.mini&&this.handle.html(this._value()),this._popup.hide(),this._popupVisible=!1)}})}); \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.css b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.css index 86ae3c64c2..3a3c912345 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.css +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.css @@ -1,163 +1 @@ -.ui-block-a, -.ui-block-b, -.ui-block-c, -.ui-block-d, -.ui-block-e { - margin: 0; - padding: 0; - border: 0; - float: left; - min-height: 1px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; -} -/* force new row */ -.ui-block-a { - clear: left; -} -li.ui-block-a, -li.ui-block-b, -li.ui-block-c, -li.ui-block-d, -li.ui-block-e { - margin-left: 0; - margin-right: 0; - padding: 0; - list-style: none; -} -/* No margin in grids for 100% width button elements until we can use max-width: fill-available; */ -[class*="ui-block-"] > button.ui-btn { - margin-right: 0; - margin-left: 0; -} -[class*="ui-block-"] > .ui-btn, -[class*="ui-block-"] > .ui-select, -[class*="ui-block-"] > .ui-checkbox, -[class*="ui-block-"] > .ui-radio, -[class*="ui-block-"] > button.ui-btn-inline, -[class*="ui-block-"] > button.ui-btn-icon-notext { - margin-right: .3125em; - margin-left: .3125em; -} - -/* preset breakpoint to switch to stacked grid styles below 35em (560px) */ -@media (max-width: 35em) { - .ui-responsive > .ui-block-a, - .ui-responsive > .ui-block-b, - .ui-responsive > .ui-block-c, - .ui-responsive > .ui-block-d, - .ui-responsive > .ui-block-e { - width: 100%; - float: none; - } -} - -.ui-table { - border: 0; - border-collapse: collapse; - padding: 0; - width: 100%; -} -.ui-table th, -.ui-table td { - line-height: 1.5em; - text-align: left; - padding: .4em .5em; - vertical-align:top; -} -.ui-table th .ui-btn, -.ui-table td .ui-btn { - line-height: normal; -} -.ui-table th { - font-weight: bold; -} -.ui-table caption { - text-align: left; - margin-bottom: 1.4em; - opacity: .5; -} - - -/* - Styles for the table columntoggle mode -*/ -.ui-table-reflow td .ui-table-cell-label, -.ui-table-reflow th .ui-table-cell-label { - display: none; -} - -/* Mobile first styles: Begin with the stacked presentation at narrow widths */ -@media only all { - /* Hide the table headers */ - .ui-table-reflow thead td, - .ui-table-reflow thead th { - display: none; - } - /* Show the table cells as a block level element */ - .ui-table-reflow td, - .ui-table-reflow th { - text-align: left; - display: block; - } - /* Add a fair amount of top margin to visually separate each row when stacked */ - .ui-table-reflow tbody th { - margin-top: 3em; - } - /* Make the label elements a percentage width */ - .ui-table-reflow td .ui-table-cell-label, - .ui-table-reflow th .ui-table-cell-label { - padding: .4em; - min-width: 30%; - display: inline-block; - margin: -.4em 1em -.4em -.4em; - } - /* For grouped headers, have a different style to visually separate the levels by classing the first label in each col group */ - .ui-table-reflow th .ui-table-cell-label-top, - .ui-table-reflow td .ui-table-cell-label-top { - display: block; - padding: .4em 0; - margin: .4em 0; - text-transform: uppercase; - font-size: .9em; - font-weight: normal; - } -} - - -/* Breakpoint to show as a standard table at 560px (35em x 16px) or wider */ -@media ( min-width: 35em ) { - - /* Show the table header rows */ - .ui-table-reflow.ui-responsive td, - .ui-table-reflow.ui-responsive th, - .ui-table-reflow.ui-responsive tbody th, - .ui-table-reflow.ui-responsive tbody td, - .ui-table-reflow.ui-responsive thead td, - .ui-table-reflow.ui-responsive thead th { - display: table-cell; - margin: 0; - } - - /* Hide the labels in each cell */ - .ui-table-reflow.ui-responsive td .ui-table-cell-label, - .ui-table-reflow.ui-responsive th .ui-table-cell-label { - display: none; - } -} - - -/* Hack to make IE9 and WP7.5 treat cells like block level elements, scoped to ui-responsive class */ -/* Applied in a max-width media query up to the table layout breakpoint so we don't need to negate this*/ -@media ( max-width: 35em ) { - .ui-table-reflow.ui-responsive td, - .ui-table-reflow.ui-responsive th { - width: 100%; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - float: left; - clear: left; - } -} \ No newline at end of file +.ui-block-a,.ui-block-b,.ui-block-c,.ui-block-d,.ui-block-e{margin:0;padding:0;border:0;float:left;min-height:1px;-webkit-box-sizing:border-box;box-sizing:border-box}.ui-block-a{clear:left}li.ui-block-a,li.ui-block-b,li.ui-block-c,li.ui-block-d,li.ui-block-e{margin-left:0;margin-right:0;padding:0;list-style:none}[class*=ui-block-]>button.ui-btn{margin-right:0;margin-left:0}[class*=ui-block-]>.ui-btn,[class*=ui-block-]>.ui-checkbox,[class*=ui-block-]>.ui-radio,[class*=ui-block-]>.ui-select,[class*=ui-block-]>button.ui-btn-icon-notext,[class*=ui-block-]>button.ui-btn-inline{margin-right:.3125em;margin-left:.3125em}.ui-table{border:0;border-collapse:collapse;padding:0;width:100%}.ui-table td,.ui-table th{line-height:1.5em;text-align:left;padding:.4em .5em;vertical-align:top}.ui-table td .ui-btn,.ui-table th .ui-btn{line-height:normal}.ui-table th{font-weight:700}.ui-table caption{text-align:left;margin-bottom:1.4em;opacity:.5}.ui-table-reflow td .ui-table-cell-label,.ui-table-reflow th .ui-table-cell-label{display:none}@media only all{.ui-table-reflow thead td,.ui-table-reflow thead th{display:none}.ui-table-reflow td,.ui-table-reflow th{text-align:left;display:block}.ui-table-reflow tbody th{margin-top:3em}.ui-table-reflow td .ui-table-cell-label,.ui-table-reflow th .ui-table-cell-label{padding:.4em;min-width:30%;display:inline-block;margin:-.4em 1em -.4em -.4em}.ui-table-reflow td .ui-table-cell-label-top,.ui-table-reflow th .ui-table-cell-label-top{display:block;padding:.4em 0;margin:.4em 0;text-transform:uppercase;font-size:.9em;font-weight:400}}@media (min-width:35em){.ui-table-reflow.ui-responsive tbody td,.ui-table-reflow.ui-responsive tbody th,.ui-table-reflow.ui-responsive td,.ui-table-reflow.ui-responsive th,.ui-table-reflow.ui-responsive thead td,.ui-table-reflow.ui-responsive thead th{display:table-cell;margin:0}.ui-table-reflow.ui-responsive td .ui-table-cell-label,.ui-table-reflow.ui-responsive th .ui-table-cell-label{display:none}}@media (max-width:35em){.ui-responsive>.ui-block-a,.ui-responsive>.ui-block-b,.ui-responsive>.ui-block-c,.ui-responsive>.ui-block-d,.ui-responsive>.ui-block-e{width:100%;float:none}.ui-table-reflow.ui-responsive td,.ui-table-reflow.ui-responsive th{width:100%;-webkit-box-sizing:border-box;box-sizing:border-box;float:left;clear:left}} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.js b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.js index db3c6f9111..e4eb0e4f8a 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.js +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.table.js @@ -1,191 +1 @@ -define(['jqmwidget'], function () { - - var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/; - - $.extend($.mobile, { - - // Namespace used framework-wide for data-attrs. Default is no namespace - - // Retrieve an attribute from an element and perform some massaging of the value - - getAttribute: function (element, key) { - var data; - - element = element.jquery ? element[0] : element; - - if (element && element.getAttribute) { - data = element.getAttribute("data-" + key); - } - - // Copied from core's src/data.js:dataAttr() - // Convert from a string to a proper data type - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test(data) ? JSON.parse(data) : - data; - } catch (err) { } - - return data; - } - - }); - - - $.widget("mobile.table", { - options: { - enhanced: false - }, - - _create: function () { - if (!this.options.enhanced) { - this.element.addClass("ui-table"); - } - - // extend here, assign on refresh > _setHeaders - $.extend(this, { - - // Expose headers and allHeaders properties on the widget - // headers references the THs within the first TR in the table - headers: undefined, - - // allHeaders references headers, plus all THs in the thead, which may - // include several rows, or not - allHeaders: undefined - }); - - this._refresh(true); - }, - - _setHeaders: function () { - var trs = this.element.find("thead tr"); - - this.headers = this.element.find("tr:eq(0)").children(); - this.allHeaders = this.headers.add(trs.children()); - }, - - refresh: function () { - this._refresh(); - }, - - rebuild: $.noop, - - _refresh: function ( /* create */) { - var table = this.element, - trs = table.find("thead tr"); - - // updating headers on refresh (fixes #5880) - this._setHeaders(); - - // Iterate over the trs - trs.each(function () { - var columnCount = 0; - - // Iterate over the children of the tr - $(this).children().each(function () { - var span = parseInt(this.getAttribute("colspan"), 10), - selector = ":nth-child(" + (columnCount + 1) + ")", - j; - - this.setAttribute("data-colstart", columnCount + 1); - - if (span) { - for (j = 0; j < span - 1; j++) { - columnCount++; - selector += ", :nth-child(" + (columnCount + 1) + ")"; - } - } - - // Store "cells" data on header as a reference to all cells in the - // same column as this TH - $(this).data("cells", table.find("tr").not(trs.eq(0)).not(this).children(selector)); - - columnCount++; - }); - }); - } - }); - - - $.widget("mobile.table", $.mobile.table, { - options: { - mode: "reflow" - }, - - _create: function () { - this._super(); - - // If it's not reflow mode, return here. - if (this.options.mode !== "reflow") { - return; - } - - if (!this.options.enhanced) { - this.element.addClass("ui-table-reflow"); - - this._updateReflow(); - } - }, - - rebuild: function () { - this._super(); - - if (this.options.mode === "reflow") { - this._refresh(false); - } - }, - - _refresh: function (create) { - this._super(create); - if (!create && this.options.mode === "reflow") { - this._updateReflow(); - } - }, - - _updateReflow: function () { - var table = this, - opts = this.options; - - // get headers in reverse order so that top-level headers are appended last - $(table.allHeaders.get().reverse()).each(function () { - var cells = $(this).data("cells"), - colstart = $.mobile.getAttribute(this, "colstart"), - hierarchyClass = cells.not(this).filter("thead th").length && " ui-table-cell-label-top", - contents = $(this).clone().contents(), - iteration, filter; - - if (contents.length > 0) { - - if (hierarchyClass) { - iteration = parseInt(this.getAttribute("colspan"), 10); - filter = ""; - - if (iteration) { - filter = "td:nth-child(" + iteration + "n + " + (colstart) + ")"; - } - - table._addLabels(cells.filter(filter), - "ui-table-cell-label" + hierarchyClass, contents); - } else { - table._addLabels(cells, "ui-table-cell-label", contents); - } - - } - }); - }, - - _addLabels: function (cells, label, contents) { - if (contents.length === 1 && contents[0].nodeName.toLowerCase() === "abbr") { - contents = contents.eq(0).attr("title"); - } - // .not fixes #6006 - cells - .not(":has(b." + label + ")") - .prepend($("").append(contents)); - } - }); - -}); \ No newline at end of file +define(["jqmwidget"],function(){var rbrace=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/;$.extend($.mobile,{getAttribute:function(element,key){var data;element=element.jquery?element[0]:element,element&&element.getAttribute&&(data=element.getAttribute("data-"+key));try{data="true"===data||"false"!==data&&("null"===data?null:+data+""===data?+data:rbrace.test(data)?JSON.parse(data):data)}catch(err){}return data}}),$.widget("mobile.table",{options:{enhanced:!1},_create:function(){this.options.enhanced||this.element.addClass("ui-table"),$.extend(this,{headers:void 0,allHeaders:void 0}),this._refresh(!0)},_setHeaders:function(){var trs=this.element.find("thead tr");this.headers=this.element.find("tr:eq(0)").children(),this.allHeaders=this.headers.add(trs.children())},refresh:function(){this._refresh()},rebuild:$.noop,_refresh:function(){var table=this.element,trs=table.find("thead tr");this._setHeaders(),trs.each(function(){var columnCount=0;$(this).children().each(function(){var j,span=parseInt(this.getAttribute("colspan"),10),selector=":nth-child("+(columnCount+1)+")";if(this.setAttribute("data-colstart",columnCount+1),span)for(j=0;j0&&(hierarchyClass?(iteration=parseInt(this.getAttribute("colspan"),10),filter="",iteration&&(filter="td:nth-child("+iteration+"n + "+colstart+")"),table._addLabels(cells.filter(filter),"ui-table-cell-label"+hierarchyClass,contents)):table._addLabels(cells,"ui-table-cell-label",contents))})},_addLabels:function(cells,label,contents){1===contents.length&&"abbr"===contents[0].nodeName.toLowerCase()&&(contents=contents.eq(0).attr("title")),cells.not(":has(b."+label+")").prepend($("").append(contents))}})}); \ No newline at end of file diff --git a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.widget.js b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.widget.js index 8436382e96..abf355496e 100644 --- a/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.widget.js +++ b/dashboard-ui/thirdparty/jquerymobile-1.4.5/jqm.widget.js @@ -1,614 +1 @@ -define(['jQuery'], function () { - - jQuery.mobile = {}; - - (function ($, window, undefined) { - - function parentWithClass(elem, className) { - - while (!elem.classList || !elem.classList.contains(className)) { - elem = elem.parentNode; - - if (!elem) { - return null; - } - } - - return elem; - } - - $.extend($.mobile, { - - // Place to store various widget extensions - behaviors: {} - }); - - // plugins - $.fn.extend({ - // Enhance child elements - enhanceWithin: function () { - var index, - widgetElements = {}, - that = this; - - // Enhance widgets - $.each($.mobile.widgets, function (name, constructor) { - - // If initSelector not false find elements - if (constructor.initSelector) { - - // Filter elements that should not be enhanced based on parents - var elements = that[0].querySelectorAll(constructor.initSelector); - - // Enhance whatever is left - if (elements.length > 0) { - widgetElements[constructor.prototype.widgetName] = $(elements); - } - } - }); - - for (index in widgetElements) { - widgetElements[index][index](); - } - - return this; - } - }); - - })(jQuery, this); - - jQuery.mobile.widgets = {}; - - // plugins - $.fn.extend({ - // Enhance child elements - enhanceWithin: function () { - var index, - widgetElements = {}, - that = this; - - // Enhance widgets - $.each($.mobile.widgets, function (name, constructor) { - - // If initSelector not false find elements - if (constructor.initSelector) { - - // Filter elements that should not be enhanced based on parents - var elements = that[0].querySelectorAll(constructor.initSelector); - - // Enhance whatever is left - if (elements.length > 0) { - widgetElements[constructor.prototype.widgetName] = $(elements); - } - } - }); - - for (index in widgetElements) { - widgetElements[index][index](); - } - - return this; - } - }); - - // For backcompat remove in 1.5 - jQuery(document).on("create", function (event) { - jQuery(event.target).enhanceWithin(); - }); - - /*! - * jQuery UI Widget c0ab71056b936627e8a7821f03c044aec6280a40 - * http://jqueryui.com - * - * Copyright 2013 jQuery Foundation and other contributors - * Released under the MIT license. - * http://jquery.org/license - * - * http://api.jqueryui.com/jQuery.widget/ - */ - (function ($, undefined) { - - var uuid = 0, - slice = Array.prototype.slice, - _cleanData = $.cleanData; - $.cleanData = function (elems) { - for (var i = 0, elem; (elem = elems[i]) != null; i++) { - try { - $(elem).triggerHandler("remove"); - // http://bugs.jquery.com/ticket/8235 - } catch (e) { } - } - _cleanData(elems); - }; - - $.widget = function (name, base, prototype) { - var fullName, existingConstructor, constructor, basePrototype, - // proxiedPrototype allows the provided prototype to remain unmodified - // so that it can be used as a mixin for multiple widgets (#8876) - proxiedPrototype = {}, - namespace = name.split(".")[0]; - - name = name.split(".")[1]; - fullName = namespace + "-" + name; - - if (!prototype) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[":"][fullName.toLowerCase()] = function (elem) { - return !!$.data(elem, fullName); - }; - - $[namespace] = $[namespace] || {}; - existingConstructor = $[namespace][name]; - constructor = $[namespace][name] = function (options, element) { - // allow instantiation without "new" keyword - if (!this._createWidget) { - return new constructor(options, element); - } - - // allow instantiation without initializing for simple inheritance - // must use "new" keyword (the code above always passes args) - if (arguments.length) { - this._createWidget(options, element); - } - }; - // extend with the existing constructor to carry over any static properties - $.extend(constructor, existingConstructor, { - version: prototype.version, - // copy the object used to create the prototype in case we need to - // redefine the widget later - _proto: $.extend({}, prototype), - // track widgets that inherit from this widget in case this widget is - // redefined after a widget inherits from it - _childConstructors: [] - }); - - basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from - basePrototype.options = $.widget.extend({}, basePrototype.options); - $.each(prototype, function (prop, value) { - if (!$.isFunction(value)) { - proxiedPrototype[prop] = value; - return; - } - proxiedPrototype[prop] = (function () { - var _super = function () { - return base.prototype[prop].apply(this, arguments); - }, - _superApply = function (args) { - return base.prototype[prop].apply(this, args); - }; - return function () { - var __super = this._super, - __superApply = this._superApply, - returnValue; - - this._super = _super; - this._superApply = _superApply; - - returnValue = value.apply(this, arguments); - - this._super = __super; - this._superApply = __superApply; - - return returnValue; - }; - })(); - }); - constructor.prototype = $.widget.extend(basePrototype, { - // TODO: remove support for widgetEventPrefix - // always use the name + a colon as the prefix, e.g., draggable:start - // don't prefix for widgets that aren't DOM-based - widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name - }, proxiedPrototype, { - constructor: constructor, - namespace: namespace, - widgetName: name, - widgetFullName: fullName - }); - - // If this widget is being redefined then we need to find all widgets that - // are inheriting from it and redefine all of them so that they inherit from - // the new version of this widget. We're essentially trying to replace one - // level in the prototype chain. - if (existingConstructor) { - $.each(existingConstructor._childConstructors, function (i, child) { - var childPrototype = child.prototype; - - // redefine the child widget using the same prototype that was - // originally used, but inherit from the new version of the base - $.widget(childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto); - }); - // remove the list of existing child constructors from the old constructor - // so the old child constructors can be garbage collected - delete existingConstructor._childConstructors; - } else { - base._childConstructors.push(constructor); - } - - $.widget.bridge(name, constructor); - - return constructor; - }; - - $.widget.extend = function (target) { - var input = slice.call(arguments, 1), - inputIndex = 0, - inputLength = input.length, - key, - value; - for (; inputIndex < inputLength; inputIndex++) { - for (key in input[inputIndex]) { - value = input[inputIndex][key]; - if (input[inputIndex].hasOwnProperty(key) && value !== undefined) { - // Clone objects - if ($.isPlainObject(value)) { - target[key] = $.isPlainObject(target[key]) ? - $.widget.extend({}, target[key], value) : - // Don't extend strings, arrays, etc. with objects - $.widget.extend({}, value); - // Copy everything else by reference - } else { - target[key] = value; - } - } - } - } - return target; - }; - - $.widget.bridge = function (name, object) { - - var fullName = object.prototype.widgetFullName || name; - $.fn[name] = function (options) { - var isMethodCall = typeof options === "string", - args = slice.call(arguments, 1), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.widget.extend.apply(null, [options].concat(args)) : - options; - - if (isMethodCall) { - this.each(function () { - var methodValue, - instance = $.data(this, fullName); - if (options === "instance") { - returnValue = instance; - return false; - } - if (!instance) { - return $.error("cannot call methods on " + name + " prior to initialization; " + - "attempted to call method '" + options + "'"); - } - if (!$.isFunction(instance[options]) || options.charAt(0) === "_") { - return $.error("no such method '" + options + "' for " + name + " widget instance"); - } - methodValue = instance[options].apply(instance, args); - if (methodValue !== instance && methodValue !== undefined) { - returnValue = methodValue && methodValue.jquery ? - returnValue.pushStack(methodValue.get()) : - methodValue; - return false; - } - }); - } else { - this.each(function () { - var instance = $.data(this, fullName); - if (instance) { - instance.option(options || {})._init(); - } else { - $.data(this, fullName, new object(options, this)); - } - }); - } - - return returnValue; - }; - }; - - $.Widget = function ( /* options, element */) { }; - $.Widget._childConstructors = []; - - $.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - defaultElement: "
", - options: { - disabled: false, - - // callbacks - create: null - }, - _createWidget: function (options, element) { - element = $(element || this.defaultElement || this)[0]; - this.element = $(element); - this.uuid = uuid++; - this.eventNamespace = "." + this.widgetName + this.uuid; - this.options = $.widget.extend({}, - this.options, - this._getCreateOptions(), - options); - - this.bindings = $(); - this.hoverable = $(); - this.focusable = $(); - - if (element !== this) { - $.data(element, this.widgetFullName, this); - this._on(true, this.element, { - remove: function (event) { - if (event.target === element) { - this.destroy(); - } - } - }); - this.document = $(element.style ? - // element within the document - element.ownerDocument : - // element is window or document - element.document || element); - this.window = $(this.document[0].defaultView || this.document[0].parentWindow); - } - - this._create(); - this._trigger("create", null, this._getCreateEventData()); - this._init(); - }, - _getCreateOptions: $.noop, - _getCreateEventData: $.noop, - _create: $.noop, - _init: $.noop, - - destroy: function () { - this._destroy(); - // we can probably remove the unbind calls in 2.0 - // all event bindings should go through this._on() - this.element - .unbind(this.eventNamespace) - .removeData(this.widgetFullName) - // support: jquery <1.6.3 - // http://bugs.jquery.com/ticket/9413 - .removeData($.camelCase(this.widgetFullName)); - this.widget() - .unbind(this.eventNamespace) - .removeAttr("aria-disabled") - .removeClass( - this.widgetFullName + "-disabled " + - "ui-state-disabled"); - - // clean up events and states - this.bindings.unbind(this.eventNamespace); - this.hoverable.removeClass("ui-state-hover"); - this.focusable.removeClass("ui-state-focus"); - }, - _destroy: $.noop, - - widget: function () { - return this.element; - }, - - option: function (key, value) { - var options = key, - parts, - curOption, - i; - - if (arguments.length === 0) { - // don't return a reference to the internal hash - return $.widget.extend({}, this.options); - } - - if (typeof key === "string") { - // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } - options = {}; - parts = key.split("."); - key = parts.shift(); - if (parts.length) { - curOption = options[key] = $.widget.extend({}, this.options[key]); - for (i = 0; i < parts.length - 1; i++) { - curOption[parts[i]] = curOption[parts[i]] || {}; - curOption = curOption[parts[i]]; - } - key = parts.pop(); - if (value === undefined) { - return curOption[key] === undefined ? null : curOption[key]; - } - curOption[key] = value; - } else { - if (value === undefined) { - return this.options[key] === undefined ? null : this.options[key]; - } - options[key] = value; - } - } - - this._setOptions(options); - - return this; - }, - _setOptions: function (options) { - var key; - - for (key in options) { - this._setOption(key, options[key]); - } - - return this; - }, - _setOption: function (key, value) { - this.options[key] = value; - - if (key === "disabled") { - this.widget() - .toggleClass(this.widgetFullName + "-disabled", !!value); - this.hoverable.removeClass("ui-state-hover"); - this.focusable.removeClass("ui-state-focus"); - } - - return this; - }, - - enable: function () { - return this._setOptions({ disabled: false }); - }, - disable: function () { - return this._setOptions({ disabled: true }); - }, - - _on: function (suppressDisabledCheck, element, handlers) { - var delegateElement, - instance = this; - - // no suppressDisabledCheck flag, shuffle arguments - if (typeof suppressDisabledCheck !== "boolean") { - handlers = element; - element = suppressDisabledCheck; - suppressDisabledCheck = false; - } - - // no element argument, shuffle and use this.element - if (!handlers) { - handlers = element; - element = this.element; - delegateElement = this.widget(); - } else { - // accept selectors, DOM elements - element = delegateElement = $(element); - this.bindings = this.bindings.add(element); - } - - $.each(handlers, function (event, handler) { - function handlerProxy() { - // allow widgets to customize the disabled handling - // - disabled as an array instead of boolean - // - disabled class as method for disabling individual parts - if (!suppressDisabledCheck && - (instance.options.disabled === true || - $(this).hasClass("ui-state-disabled"))) { - return; - } - return (typeof handler === "string" ? instance[handler] : handler) - .apply(instance, arguments); - } - - // copy the guid so direct unbinding works - if (typeof handler !== "string") { - handlerProxy.guid = handler.guid = - handler.guid || handlerProxy.guid || $.guid++; - } - - var match = event.match(/^(\w+)\s*(.*)$/), - eventName = match[1] + instance.eventNamespace, - selector = match[2]; - if (selector) { - delegateElement.on(eventName, selector, handlerProxy); - } else { - element.on(eventName, handlerProxy); - } - }); - }, - - _off: function (element, eventName) { - eventName = (eventName || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace; - element.off(eventName).off(eventName); - }, - - _trigger: function (type, event, data) { - var prop, orig, - callback = this.options[type]; - - data = data || {}; - event = $.Event(event); - event.type = (type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[0]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if (orig) { - for (prop in orig) { - if (!(prop in event)) { - event[prop] = orig[prop]; - } - } - } - - this.element[0].dispatchEvent(new CustomEvent(event.type, { - bubbles: true, - detail: { - data: data, - originalEvent: event - } - })); - - //this.element.trigger(event, data); - return !($.isFunction(callback) && - callback.apply(this.element[0], [event].concat(data)) === false || - event.isDefaultPrevented()); - } - }; - - })(jQuery); - - (function ($, undefined) { - - $.extend($.Widget.prototype, { - _getCreateOptions: function () { - - var option, value, - elem = this.element[0], - options = {}; - - // - if (!this.element.data("defaults")) { - for (option in this.options) { - - value = this.element.data(option); - - if (value != null) { - options[option] = value; - } - } - } - - return options; - } - }); - - })(jQuery); - - (function ($, undefined) { - - - var originalWidget = $.widget; - - $.widget = (function (orig) { - return function () { - var constructor = orig.apply(this, arguments), - name = constructor.prototype.widgetName; - - constructor.initSelector = ((constructor.prototype.initSelector !== undefined) ? - constructor.prototype.initSelector : "*[data-role='" + name + "']:not([data-role='none'])"); - - $.mobile.widgets[name] = constructor; - - return constructor; - }; - })($.widget); - - // Make sure $.widget still has bridge and extend methods - $.extend($.widget, originalWidget); - - })(jQuery); - -}); \ No newline at end of file +define(["jQuery"],function(){jQuery.mobile={},function($,window,undefined){$.extend($.mobile,{behaviors:{}}),$.fn.extend({enhanceWithin:function(){var index,widgetElements={},that=this;$.each($.mobile.widgets,function(name,constructor){if(constructor.initSelector){var elements=that[0].querySelectorAll(constructor.initSelector);elements.length>0&&(widgetElements[constructor.prototype.widgetName]=$(elements))}});for(index in widgetElements)widgetElements[index][index]();return this}})}(jQuery,this),jQuery.mobile.widgets={},$.fn.extend({enhanceWithin:function(){var index,widgetElements={},that=this;$.each($.mobile.widgets,function(name,constructor){if(constructor.initSelector){var elements=that[0].querySelectorAll(constructor.initSelector);elements.length>0&&(widgetElements[constructor.prototype.widgetName]=$(elements))}});for(index in widgetElements)widgetElements[index][index]();return this}}),jQuery(document).on("create",function(event){jQuery(event.target).enhanceWithin()}),function($,undefined){var uuid=0,slice=Array.prototype.slice,_cleanData=$.cleanData;$.cleanData=function(elems){for(var elem,i=0;null!=(elem=elems[i]);i++)try{$(elem).triggerHandler("remove")}catch(e){}_cleanData(elems)},$.widget=function(name,base,prototype){var fullName,existingConstructor,constructor,basePrototype,proxiedPrototype={},namespace=name.split(".")[0];return name=name.split(".")[1],fullName=namespace+"-"+name,prototype||(prototype=base,base=$.Widget),$.expr[":"][fullName.toLowerCase()]=function(elem){return!!$.data(elem,fullName)},$[namespace]=$[namespace]||{},existingConstructor=$[namespace][name],constructor=$[namespace][name]=function(options,element){return this._createWidget?void(arguments.length&&this._createWidget(options,element)):new constructor(options,element)},$.extend(constructor,existingConstructor,{version:prototype.version,_proto:$.extend({},prototype),_childConstructors:[]}),basePrototype=new base,basePrototype.options=$.widget.extend({},basePrototype.options),$.each(prototype,function(prop,value){return $.isFunction(value)?void(proxiedPrototype[prop]=function(){var _super=function(){return base.prototype[prop].apply(this,arguments)},_superApply=function(args){return base.prototype[prop].apply(this,args)};return function(){var returnValue,__super=this._super,__superApply=this._superApply;return this._super=_super,this._superApply=_superApply,returnValue=value.apply(this,arguments),this._super=__super,this._superApply=__superApply,returnValue}}()):void(proxiedPrototype[prop]=value)}),constructor.prototype=$.widget.extend(basePrototype,{widgetEventPrefix:existingConstructor?basePrototype.widgetEventPrefix||name:name},proxiedPrototype,{constructor:constructor,namespace:namespace,widgetName:name,widgetFullName:fullName}),existingConstructor?($.each(existingConstructor._childConstructors,function(i,child){var childPrototype=child.prototype;$.widget(childPrototype.namespace+"."+childPrototype.widgetName,constructor,child._proto)}),delete existingConstructor._childConstructors):base._childConstructors.push(constructor),$.widget.bridge(name,constructor),constructor},$.widget.extend=function(target){for(var key,value,input=slice.call(arguments,1),inputIndex=0,inputLength=input.length;inputIndex",options:{disabled:!1,create:null},_createWidget:function(options,element){element=$(element||this.defaultElement||this)[0],this.element=$(element),this.uuid=uuid++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=$.widget.extend({},this.options,this._getCreateOptions(),options),this.bindings=$(),this.hoverable=$(),this.focusable=$(),element!==this&&($.data(element,this.widgetFullName,this),this._on(!0,this.element,{remove:function(event){event.target===element&&this.destroy()}}),this.document=$(element.style?element.ownerDocument:element.document||element),this.window=$(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:$.noop,_getCreateEventData:$.noop,_create:$.noop,_init:$.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData($.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:$.noop,widget:function(){return this.element},option:function(key,value){var parts,curOption,i,options=key;if(0===arguments.length)return $.widget.extend({},this.options);if("string"==typeof key)if(options={},parts=key.split("."),key=parts.shift(),parts.length){for(curOption=options[key]=$.widget.extend({},this.options[key]),i=0;i .jstree-ocl { - cursor: default; -} -.jstree .jstree-open > .jstree-children { - display: block; -} -.jstree .jstree-closed > .jstree-children, -.jstree .jstree-leaf > .jstree-children { - display: none; -} -.jstree-anchor > .jstree-themeicon { - margin-right: 2px; -} -.jstree-no-icons .jstree-themeicon, -.jstree-anchor > .jstree-themeicon-hidden { - display: none; -} -.jstree-rtl .jstree-anchor { - padding: 0 1px 0 4px; -} -.jstree-rtl .jstree-anchor > .jstree-themeicon { - margin-left: 2px; - margin-right: 0; -} -.jstree-rtl .jstree-node { - margin-left: 0; -} -.jstree-rtl .jstree-container-ul > .jstree-node { - margin-right: 0; -} -.jstree-wholerow-ul { - position: relative; - display: inline-block; - min-width: 100%; -} -.jstree-wholerow-ul .jstree-leaf > .jstree-ocl { - cursor: pointer; -} -.jstree-wholerow-ul .jstree-anchor, -.jstree-wholerow-ul .jstree-icon { - position: relative; -} -.jstree-wholerow-ul .jstree-wholerow { - width: 100%; - cursor: pointer; - position: absolute; - left: 0; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} -.vakata-context { - display: none; -} -.vakata-context, -.vakata-context ul { - margin: 0; - padding: 2px; - position: absolute; - background: #f5f5f5; - border: 1px solid #979797; - -moz-box-shadow: 5px 5px 4px -4px #666666; - -webkit-box-shadow: 2px 2px 2px #999999; - box-shadow: 2px 2px 2px #999999; -} -.vakata-context ul { - list-style: none; - left: 100%; - margin-top: -2.7em; - margin-left: -4px; -} -.vakata-context .vakata-context-right ul { - left: auto; - right: 100%; - margin-left: auto; - margin-right: -4px; -} -.vakata-context li { - list-style: none; - display: inline; -} -.vakata-context li > a { - display: block; - padding: 0 2em 0 2em; - text-decoration: none; - width: auto; - color: black; - white-space: nowrap; - line-height: 2.4em; - -moz-text-shadow: 1px 1px 0 white; - -webkit-text-shadow: 1px 1px 0 white; - text-shadow: 1px 1px 0 white; - -moz-border-radius: 1px; - -webkit-border-radius: 1px; - border-radius: 1px; -} -.vakata-context li > a:hover { - position: relative; - background-color: #e8eff7; - -moz-box-shadow: 0 0 2px #0a6aa1; - -webkit-box-shadow: 0 0 2px #0a6aa1; - box-shadow: 0 0 2px #0a6aa1; -} -.vakata-context li > a.vakata-context-parent { - background-image: url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw=="); - background-position: right center; - background-repeat: no-repeat; -} -.vakata-context li > a:focus { - outline: 0; -} -.vakata-context .vakata-context-hover > a { - position: relative; - background-color: #e8eff7; - -moz-box-shadow: 0 0 2px #0a6aa1; - -webkit-box-shadow: 0 0 2px #0a6aa1; - box-shadow: 0 0 2px #0a6aa1; -} -.vakata-context .vakata-context-separator > a, -.vakata-context .vakata-context-separator > a:hover { - background: white; - border: 0; - border-top: 1px solid #e2e3e3; - height: 1px; - min-height: 1px; - max-height: 1px; - padding: 0; - margin: 0 0 0 2.4em; - border-left: 1px solid #e0e0e0; - -moz-text-shadow: 0 0 0 transparent; - -webkit-text-shadow: 0 0 0 transparent; - text-shadow: 0 0 0 transparent; - -moz-box-shadow: 0 0 0 transparent; - -webkit-box-shadow: 0 0 0 transparent; - box-shadow: 0 0 0 transparent; - -moz-border-radius: 0; - -webkit-border-radius: 0; - border-radius: 0; -} -.vakata-context .vakata-contextmenu-disabled a, -.vakata-context .vakata-contextmenu-disabled a:hover { - color: silver; - background-color: transparent; - border: 0; - box-shadow: 0 0 0; -} -.vakata-context li > a > i { - text-decoration: none; - display: inline-block; - width: 2.4em; - height: 2.4em; - background: transparent; - margin: 0 0 0 -2em; - vertical-align: top; - text-align: center; - line-height: 2.4em; -} -.vakata-context li > a > i:empty { - width: 2.4em; - line-height: 2.4em; -} -.vakata-context li > a .vakata-contextmenu-sep { - display: inline-block; - width: 1px; - height: 2.4em; - background: white; - margin: 0 0.5em 0 0; - border-left: 1px solid #e2e3e3; -} -.vakata-context .vakata-contextmenu-shortcut { - color: silver; - opacity: 0.5; - display: none; -} -.vakata-context-rtl ul { - left: auto; - right: 100%; - margin-left: auto; - margin-right: -4px; -} -.vakata-context-rtl li > a.vakata-context-parent { - background-image: url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7"); - background-position: left center; - background-repeat: no-repeat; -} -.vakata-context-rtl .vakata-context-separator > a { - margin: 0 2.4em 0 0; - border-left: 0; - border-right: 1px solid #e2e3e3; -} -.vakata-context-rtl .vakata-context-left ul { - right: auto; - left: 100%; - margin-left: -4px; - margin-right: auto; -} -.vakata-context-rtl li > a > i { - margin: 0 -2em 0 0; -} -.vakata-context-rtl li > a .vakata-contextmenu-sep { - margin: 0 0 0 0.5em; - border-left-color: white; - background: #e2e3e3; -} -#jstree-marker { - position: absolute; - top: 0; - left: 0; - margin: -5px 0 0 0; - padding: 0; - border-right: 0; - border-top: 5px solid transparent; - border-bottom: 5px solid transparent; - border-left: 5px solid; - width: 0; - height: 0; - font-size: 0; - line-height: 0; -} -#jstree-dnd { - line-height: 16px; - margin: 0; - padding: 4px; -} -#jstree-dnd .jstree-icon, -#jstree-dnd .jstree-copy { - display: inline-block; - text-decoration: none; - margin: 0 2px 0 0; - padding: 0; - width: 16px; - height: 16px; -} -#jstree-dnd .jstree-ok { - background: green; -} -#jstree-dnd .jstree-er { - background: red; -} -#jstree-dnd .jstree-copy { - margin: 0 2px 0 2px; -} -.jstree-default .jstree-node, -.jstree-default .jstree-icon { - background-repeat: no-repeat; - background-color: transparent; -} -.jstree-default .jstree-anchor, -.jstree-default .jstree-wholerow { - transition: background-color 0.15s, box-shadow 0.15s; -} -.jstree-default .jstree-hovered { - background: #e7f4f9; - border-radius: 2px; - box-shadow: inset 0 0 1px #cccccc; -} -.jstree-default .jstree-clicked { - background: #beebff; - border-radius: 2px; - box-shadow: inset 0 0 1px #999999; -} -.jstree-default .jstree-no-icons .jstree-anchor > .jstree-themeicon { - display: none; -} -.jstree-default .jstree-disabled { - background: transparent; - color: #666666; -} -.jstree-default .jstree-disabled.jstree-hovered { - background: transparent; - box-shadow: none; -} -.jstree-default .jstree-disabled.jstree-clicked { - background: #efefef; -} -.jstree-default .jstree-disabled > .jstree-icon { - opacity: 0.8; - filter: url("data:image/svg+xml;utf8,#jstree-grayscale"); - /* Firefox 10+ */ - filter: gray; - /* IE6-9 */ - -webkit-filter: grayscale(100%); - /* Chrome 19+ & Safari 6+ */ -} -.jstree-default .jstree-search { - font-style: italic; - color: #8b0000; - font-weight: bold; -} -.jstree-default .jstree-no-checkboxes .jstree-checkbox { - display: none !important; -} -.jstree-default.jstree-checkbox-no-clicked .jstree-clicked { - background: transparent; - box-shadow: none; -} -.jstree-default.jstree-checkbox-no-clicked .jstree-clicked.jstree-hovered { - background: #e7f4f9; -} -.jstree-default.jstree-checkbox-no-clicked > .jstree-wholerow-ul .jstree-wholerow-clicked { - background: transparent; -} -.jstree-default.jstree-checkbox-no-clicked > .jstree-wholerow-ul .jstree-wholerow-clicked.jstree-wholerow-hovered { - background: #e7f4f9; -} -.jstree-default > .jstree-striped { - background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAMAAAB/qqA+AAAABlBMVEUAAAAAAAClZ7nPAAAAAnRSTlMNAMM9s3UAAAAXSURBVHjajcEBAQAAAIKg/H/aCQZ70AUBjAATb6YPDgAAAABJRU5ErkJggg==") left top repeat; -} -.jstree-default > .jstree-wholerow-ul .jstree-hovered, -.jstree-default > .jstree-wholerow-ul .jstree-clicked { - background: transparent; - box-shadow: none; - border-radius: 0; -} -.jstree-default .jstree-wholerow { - -moz-box-sizing: border-box; - -webkit-box-sizing: border-box; - box-sizing: border-box; -} -.jstree-default .jstree-wholerow-hovered { - background: #e7f4f9; -} -.jstree-default .jstree-wholerow-clicked { - background: #beebff; - background: -moz-linear-gradient(top, #beebff 0%, #a8e4ff 100%); - background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #beebff), color-stop(100%, #a8e4ff)); - background: -webkit-linear-gradient(top, #beebff 0%, #a8e4ff 100%); - background: -o-linear-gradient(top, #beebff 0%, #a8e4ff 100%); - background: -ms-linear-gradient(top, #beebff 0%, #a8e4ff 100%); - background: linear-gradient(to bottom, #beebff 0%, #a8e4ff 100%); - /*filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='@color1', endColorstr='@color2',GradientType=0 );*/ -} -.jstree-default .jstree-node { - min-height: 24px; - line-height: 24px; - margin-left: 24px; - min-width: 24px; -} -.jstree-default .jstree-anchor { - line-height: 24px; - height: 24px; -} -.jstree-default .jstree-icon { - width: 24px; - height: 24px; - line-height: 24px; -} -.jstree-default .jstree-icon:empty { - width: 24px; - height: 24px; - line-height: 24px; -} -.jstree-default.jstree-rtl .jstree-node { - margin-right: 24px; -} -.jstree-default .jstree-wholerow { - height: 24px; -} -.jstree-default .jstree-node, -.jstree-default .jstree-icon { - background-image: url("32px.png"); -} -.jstree-default .jstree-node { - background-position: -292px -4px; - background-repeat: repeat-y; -} -.jstree-default .jstree-last { - background: transparent; -} -.jstree-default .jstree-open > .jstree-ocl { - background-position: -132px -4px; -} -.jstree-default .jstree-closed > .jstree-ocl { - background-position: -100px -4px; -} -.jstree-default .jstree-leaf > .jstree-ocl { - background-position: -68px -4px; -} -.jstree-default .jstree-themeicon { - background-position: -260px -4px; -} -.jstree-default > .jstree-no-dots .jstree-node, -.jstree-default > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -36px -4px; -} -.jstree-default > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: -4px -4px; -} -.jstree-default .jstree-disabled { - background: transparent; -} -.jstree-default .jstree-disabled.jstree-hovered { - background: transparent; -} -.jstree-default .jstree-disabled.jstree-clicked { - background: #efefef; -} -.jstree-default .jstree-checkbox { - background-position: -164px -4px; -} -.jstree-default .jstree-checkbox:hover { - background-position: -164px -36px; -} -.jstree-default.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox, -.jstree-default .jstree-checked > .jstree-checkbox { - background-position: -228px -4px; -} -.jstree-default.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox:hover, -.jstree-default .jstree-checked > .jstree-checkbox:hover { - background-position: -228px -36px; -} -.jstree-default .jstree-anchor > .jstree-undetermined { - background-position: -196px -4px; -} -.jstree-default .jstree-anchor > .jstree-undetermined:hover { - background-position: -196px -36px; -} -.jstree-default > .jstree-striped { - background-size: auto 48px; -} -.jstree-default.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg=="); - background-position: 100% 1px; - background-repeat: repeat-y; -} -.jstree-default.jstree-rtl .jstree-last { - background: transparent; -} -.jstree-default.jstree-rtl .jstree-open > .jstree-ocl { - background-position: -132px -36px; -} -.jstree-default.jstree-rtl .jstree-closed > .jstree-ocl { - background-position: -100px -36px; -} -.jstree-default.jstree-rtl .jstree-leaf > .jstree-ocl { - background-position: -68px -36px; -} -.jstree-default.jstree-rtl > .jstree-no-dots .jstree-node, -.jstree-default.jstree-rtl > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default.jstree-rtl > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -36px -36px; -} -.jstree-default.jstree-rtl > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: -4px -36px; -} -.jstree-default .jstree-themeicon-custom { - background-color: transparent; - background-image: none; - background-position: 0 0; -} -.jstree-default > .jstree-container-ul .jstree-loading > .jstree-ocl { - background: url("throbber.gif") center center no-repeat; -} -.jstree-default .jstree-file { - background: url("32px.png") -100px -68px no-repeat; -} -.jstree-default .jstree-folder { - background: url("32px.png") -260px -4px no-repeat; -} -.jstree-default > .jstree-container-ul > .jstree-node { - margin-left: 0; - margin-right: 0; -} -#jstree-dnd.jstree-default { - line-height: 24px; - padding: 0 4px; -} -#jstree-dnd.jstree-default .jstree-ok, -#jstree-dnd.jstree-default .jstree-er { - background-image: url("32px.png"); - background-repeat: no-repeat; - background-color: transparent; -} -#jstree-dnd.jstree-default i { - background: transparent; - width: 24px; - height: 24px; - line-height: 24px; -} -#jstree-dnd.jstree-default .jstree-ok { - background-position: -4px -68px; -} -#jstree-dnd.jstree-default .jstree-er { - background-position: -36px -68px; -} -.jstree-default.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg=="); -} -.jstree-default.jstree-rtl .jstree-last { - background: transparent; -} -.jstree-default-small .jstree-node { - min-height: 18px; - line-height: 18px; - margin-left: 18px; - min-width: 18px; -} -.jstree-default-small .jstree-anchor { - line-height: 18px; - height: 18px; -} -.jstree-default-small .jstree-icon { - width: 18px; - height: 18px; - line-height: 18px; -} -.jstree-default-small .jstree-icon:empty { - width: 18px; - height: 18px; - line-height: 18px; -} -.jstree-default-small.jstree-rtl .jstree-node { - margin-right: 18px; -} -.jstree-default-small .jstree-wholerow { - height: 18px; -} -.jstree-default-small .jstree-node, -.jstree-default-small .jstree-icon { - background-image: url("32px.png"); -} -.jstree-default-small .jstree-node { - background-position: -295px -7px; - background-repeat: repeat-y; -} -.jstree-default-small .jstree-last { - background: transparent; -} -.jstree-default-small .jstree-open > .jstree-ocl { - background-position: -135px -7px; -} -.jstree-default-small .jstree-closed > .jstree-ocl { - background-position: -103px -7px; -} -.jstree-default-small .jstree-leaf > .jstree-ocl { - background-position: -71px -7px; -} -.jstree-default-small .jstree-themeicon { - background-position: -263px -7px; -} -.jstree-default-small > .jstree-no-dots .jstree-node, -.jstree-default-small > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default-small > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -39px -7px; -} -.jstree-default-small > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: -7px -7px; -} -.jstree-default-small .jstree-disabled { - background: transparent; -} -.jstree-default-small .jstree-disabled.jstree-hovered { - background: transparent; -} -.jstree-default-small .jstree-disabled.jstree-clicked { - background: #efefef; -} -.jstree-default-small .jstree-checkbox { - background-position: -167px -7px; -} -.jstree-default-small .jstree-checkbox:hover { - background-position: -167px -39px; -} -.jstree-default-small.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox, -.jstree-default-small .jstree-checked > .jstree-checkbox { - background-position: -231px -7px; -} -.jstree-default-small.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox:hover, -.jstree-default-small .jstree-checked > .jstree-checkbox:hover { - background-position: -231px -39px; -} -.jstree-default-small .jstree-anchor > .jstree-undetermined { - background-position: -199px -7px; -} -.jstree-default-small .jstree-anchor > .jstree-undetermined:hover { - background-position: -199px -39px; -} -.jstree-default-small > .jstree-striped { - background-size: auto 36px; -} -.jstree-default-small.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg=="); - background-position: 100% 1px; - background-repeat: repeat-y; -} -.jstree-default-small.jstree-rtl .jstree-last { - background: transparent; -} -.jstree-default-small.jstree-rtl .jstree-open > .jstree-ocl { - background-position: -135px -39px; -} -.jstree-default-small.jstree-rtl .jstree-closed > .jstree-ocl { - background-position: -103px -39px; -} -.jstree-default-small.jstree-rtl .jstree-leaf > .jstree-ocl { - background-position: -71px -39px; -} -.jstree-default-small.jstree-rtl > .jstree-no-dots .jstree-node, -.jstree-default-small.jstree-rtl > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default-small.jstree-rtl > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -39px -39px; -} -.jstree-default-small.jstree-rtl > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: -7px -39px; -} -.jstree-default-small .jstree-themeicon-custom { - background-color: transparent; - background-image: none; - background-position: 0 0; -} -.jstree-default-small > .jstree-container-ul .jstree-loading > .jstree-ocl { - background: url("throbber.gif") center center no-repeat; -} -.jstree-default-small .jstree-file { - background: url("32px.png") -103px -71px no-repeat; -} -.jstree-default-small .jstree-folder { - background: url("32px.png") -263px -7px no-repeat; -} -.jstree-default-small > .jstree-container-ul > .jstree-node { - margin-left: 0; - margin-right: 0; -} -#jstree-dnd.jstree-default-small { - line-height: 18px; - padding: 0 4px; -} -#jstree-dnd.jstree-default-small .jstree-ok, -#jstree-dnd.jstree-default-small .jstree-er { - background-image: url("32px.png"); - background-repeat: no-repeat; - background-color: transparent; -} -#jstree-dnd.jstree-default-small i { - background: transparent; - width: 18px; - height: 18px; - line-height: 18px; -} -#jstree-dnd.jstree-default-small .jstree-ok { - background-position: -7px -71px; -} -#jstree-dnd.jstree-default-small .jstree-er { - background-position: -39px -71px; -} -.jstree-default-small.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAACAQMAAABv1h6PAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMHBgAAiABBI4gz9AAAAABJRU5ErkJggg=="); -} -.jstree-default-small.jstree-rtl .jstree-last { - background: transparent; -} -.jstree-default-large .jstree-node { - min-height: 32px; - line-height: 32px; - margin-left: 32px; - min-width: 32px; -} -.jstree-default-large .jstree-anchor { - line-height: 32px; - height: 32px; -} -.jstree-default-large .jstree-icon { - width: 32px; - height: 32px; - line-height: 32px; -} -.jstree-default-large .jstree-icon:empty { - width: 32px; - height: 32px; - line-height: 32px; -} -.jstree-default-large.jstree-rtl .jstree-node { - margin-right: 32px; -} -.jstree-default-large .jstree-wholerow { - height: 32px; -} -.jstree-default-large .jstree-node, -.jstree-default-large .jstree-icon { - background-image: url("32px.png"); -} -.jstree-default-large .jstree-node { - background-position: -288px 0px; - background-repeat: repeat-y; -} -.jstree-default-large .jstree-last { - background: transparent; -} -.jstree-default-large .jstree-open > .jstree-ocl { - background-position: -128px 0px; -} -.jstree-default-large .jstree-closed > .jstree-ocl { - background-position: -96px 0px; -} -.jstree-default-large .jstree-leaf > .jstree-ocl { - background-position: -64px 0px; -} -.jstree-default-large .jstree-themeicon { - background-position: -256px 0px; -} -.jstree-default-large > .jstree-no-dots .jstree-node, -.jstree-default-large > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default-large > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -32px 0px; -} -.jstree-default-large > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: 0px 0px; -} -.jstree-default-large .jstree-disabled { - background: transparent; -} -.jstree-default-large .jstree-disabled.jstree-hovered { - background: transparent; -} -.jstree-default-large .jstree-disabled.jstree-clicked { - background: #efefef; -} -.jstree-default-large .jstree-checkbox { - background-position: -160px 0px; -} -.jstree-default-large .jstree-checkbox:hover { - background-position: -160px -32px; -} -.jstree-default-large.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox, -.jstree-default-large .jstree-checked > .jstree-checkbox { - background-position: -224px 0px; -} -.jstree-default-large.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox:hover, -.jstree-default-large .jstree-checked > .jstree-checkbox:hover { - background-position: -224px -32px; -} -.jstree-default-large .jstree-anchor > .jstree-undetermined { - background-position: -192px 0px; -} -.jstree-default-large .jstree-anchor > .jstree-undetermined:hover { - background-position: -192px -32px; -} -.jstree-default-large > .jstree-striped { - background-size: auto 64px; -} -.jstree-default-large.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg=="); - background-position: 100% 1px; - background-repeat: repeat-y; -} -.jstree-default-large.jstree-rtl .jstree-last { - background: transparent; -} -.jstree-default-large.jstree-rtl .jstree-open > .jstree-ocl { - background-position: -128px -32px; -} -.jstree-default-large.jstree-rtl .jstree-closed > .jstree-ocl { - background-position: -96px -32px; -} -.jstree-default-large.jstree-rtl .jstree-leaf > .jstree-ocl { - background-position: -64px -32px; -} -.jstree-default-large.jstree-rtl > .jstree-no-dots .jstree-node, -.jstree-default-large.jstree-rtl > .jstree-no-dots .jstree-leaf > .jstree-ocl { - background: transparent; -} -.jstree-default-large.jstree-rtl > .jstree-no-dots .jstree-open > .jstree-ocl { - background-position: -32px -32px; -} -.jstree-default-large.jstree-rtl > .jstree-no-dots .jstree-closed > .jstree-ocl { - background-position: 0px -32px; -} -.jstree-default-large .jstree-themeicon-custom { - background-color: transparent; - background-image: none; - background-position: 0 0; -} -.jstree-default-large > .jstree-container-ul .jstree-loading > .jstree-ocl { - background: url("throbber.gif") center center no-repeat; -} -.jstree-default-large .jstree-file { - background: url("32px.png") -96px -64px no-repeat; -} -.jstree-default-large .jstree-folder { - background: url("32px.png") -256px 0px no-repeat; -} -.jstree-default-large > .jstree-container-ul > .jstree-node { - margin-left: 0; - margin-right: 0; -} -#jstree-dnd.jstree-default-large { - line-height: 32px; - padding: 0 4px; -} -#jstree-dnd.jstree-default-large .jstree-ok, -#jstree-dnd.jstree-default-large .jstree-er { - background-image: url("32px.png"); - background-repeat: no-repeat; - background-color: transparent; -} -#jstree-dnd.jstree-default-large i { - background: transparent; - width: 32px; - height: 32px; - line-height: 32px; -} -#jstree-dnd.jstree-default-large .jstree-ok { - background-position: 0px -64px; -} -#jstree-dnd.jstree-default-large .jstree-er { - background-position: -32px -64px; -} -.jstree-default-large.jstree-rtl .jstree-node { - background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAACAQMAAAAD0EyKAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjgIIGBgABCgCBvVLXcAAAAABJRU5ErkJggg=="); -} -.jstree-default-large.jstree-rtl .jstree-last { - background: transparent; -} -@media (max-width: 768px) { - #jstree-dnd.jstree-dnd-responsive { - line-height: 40px; - font-weight: bold; - text-shadow: 1px 1px white; - } - #jstree-dnd.jstree-dnd-responsive > i { - background: transparent; - width: 40px; - height: 40px; - } - #jstree-dnd.jstree-dnd-responsive > .jstree-ok { - background-image: url("40px.png"); - background-position: 0 -200px; - background-size: 120px 240px; - } - #jstree-dnd.jstree-dnd-responsive > .jstree-er { - background-image: url("40px.png"); - background-position: -40px -200px; - background-size: 120px 240px; - } - #jstree-marker.jstree-dnd-responsive { - border-left-width: 10px; - border-top-width: 10px; - border-bottom-width: 10px; - margin-top: -10px; - } -} -@media (max-width: 768px) { - .jstree-default-responsive { - /* - .jstree-open > .jstree-ocl, - .jstree-closed > .jstree-ocl { border-radius:20px; background-color:white; } - */ - } - .jstree-default-responsive .jstree-icon { - background-image: url("40px.png"); - } - .jstree-default-responsive .jstree-node, - .jstree-default-responsive .jstree-leaf > .jstree-ocl { - background: transparent; - } - .jstree-default-responsive .jstree-node { - min-height: 40px; - line-height: 40px; - margin-left: 40px; - min-width: 40px; - white-space: nowrap; - } - .jstree-default-responsive .jstree-anchor { - line-height: 40px; - height: 40px; - } - .jstree-default-responsive .jstree-icon, - .jstree-default-responsive .jstree-icon:empty { - width: 40px; - height: 40px; - line-height: 40px; - } - .jstree-default-responsive > .jstree-container-ul > .jstree-node { - margin-left: 0; - } - .jstree-default-responsive.jstree-rtl .jstree-node { - margin-left: 0; - margin-right: 40px; - } - .jstree-default-responsive.jstree-rtl .jstree-container-ul > .jstree-node { - margin-right: 0; - } - .jstree-default-responsive .jstree-ocl, - .jstree-default-responsive .jstree-themeicon, - .jstree-default-responsive .jstree-checkbox { - background-size: 120px 240px; - } - .jstree-default-responsive .jstree-leaf > .jstree-ocl { - background: transparent; - } - .jstree-default-responsive .jstree-open > .jstree-ocl { - background-position: 0 0px !important; - } - .jstree-default-responsive .jstree-closed > .jstree-ocl { - background-position: 0 -40px !important; - } - .jstree-default-responsive.jstree-rtl .jstree-closed > .jstree-ocl { - background-position: -40px 0px !important; - } - .jstree-default-responsive .jstree-themeicon { - background-position: -40px -40px; - } - .jstree-default-responsive .jstree-checkbox, - .jstree-default-responsive .jstree-checkbox:hover { - background-position: -40px -80px; - } - .jstree-default-responsive.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox, - .jstree-default-responsive.jstree-checkbox-selection .jstree-clicked > .jstree-checkbox:hover, - .jstree-default-responsive .jstree-checked > .jstree-checkbox, - .jstree-default-responsive .jstree-checked > .jstree-checkbox:hover { - background-position: 0 -80px; - } - .jstree-default-responsive .jstree-anchor > .jstree-undetermined, - .jstree-default-responsive .jstree-anchor > .jstree-undetermined:hover { - background-position: 0 -120px; - } - .jstree-default-responsive .jstree-anchor { - font-weight: bold; - text-shadow: 1px 1px white; - } - .jstree-default-responsive > .jstree-striped { - background: transparent; - } - .jstree-default-responsive .jstree-wholerow { - border-top: 1px solid rgba(255, 255, 255, 0.7); - border-bottom: 1px solid rgba(64, 64, 64, 0.2); - background: #ebebeb; - height: 40px; - } - .jstree-default-responsive .jstree-wholerow-hovered { - background: #e7f4f9; - } - .jstree-default-responsive .jstree-wholerow-clicked { - background: #beebff; - } - .jstree-default-responsive .jstree-children .jstree-last > .jstree-wholerow { - box-shadow: inset 0 -6px 3px -5px #666666; - } - .jstree-default-responsive .jstree-children .jstree-open > .jstree-wholerow { - box-shadow: inset 0 6px 3px -5px #666666; - border-top: 0; - } - .jstree-default-responsive .jstree-children .jstree-open + .jstree-open { - box-shadow: none; - } - .jstree-default-responsive .jstree-node, - .jstree-default-responsive .jstree-icon, - .jstree-default-responsive .jstree-node > .jstree-ocl, - .jstree-default-responsive .jstree-themeicon, - .jstree-default-responsive .jstree-checkbox { - background-image: url("40px.png"); - background-size: 120px 240px; - } - .jstree-default-responsive .jstree-node { - background-position: -80px 0; - background-repeat: repeat-y; - } - .jstree-default-responsive .jstree-last { - background: transparent; - } - .jstree-default-responsive .jstree-leaf > .jstree-ocl { - background-position: -40px -120px; - } - .jstree-default-responsive .jstree-last > .jstree-ocl { - background-position: -40px -160px; - } - .jstree-default-responsive .jstree-themeicon-custom { - background-color: transparent; - background-image: none; - background-position: 0 0; - } - .jstree-default-responsive .jstree-file { - background: url("40px.png") 0 -160px no-repeat; - background-size: 120px 240px; - } - .jstree-default-responsive .jstree-folder { - background: url("40px.png") -40px -40px no-repeat; - background-size: 120px 240px; - } - .jstree-default-responsive > .jstree-container-ul > .jstree-node { - margin-left: 0; - margin-right: 0; - } -} +.jstree-anchor,.jstree-node{white-space:nowrap}.jstree-anchor:focus,.vakata-context li>a:focus{outline:0}.jstree-children,.jstree-container-ul,.jstree-node{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-anchor,.jstree-icon,.jstree-icon:empty{display:inline-block;margin:0;vertical-align:top}.jstree-anchor{padding:0 4px 0 1px}.jstree-anchor,.jstree-anchor:active,.jstree-anchor:hover,.jstree-anchor:link,.jstree-anchor:visited{text-decoration:none;color:inherit}.jstree-icon,.jstree-icon:empty{text-decoration:none;padding:0;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children,.jstree-anchor>.jstree-themeicon-hidden,.jstree-no-icons .jstree-themeicon{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;-webkit-box-shadow:2px 2px 2px #999;box-shadow:2px 2px 2px #999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none;display:inline}.vakata-context li>a{display:block;padding:0 2em;text-decoration:none;width:auto;color:#000;white-space:nowrap;line-height:2.4em;-moz-text-shadow:1px 1px 0 #fff;-webkit-text-shadow:1px 1px 0 #fff;text-shadow:1px 1px 0 #fff;-webkit-border-radius:1px;border-radius:1px}.vakata-context li>a>i,.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;-webkit-box-shadow:0 0 2px #0a6aa1;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url(data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==);background-position:right center;background-repeat:no-repeat}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;-webkit-box-shadow:0 0 2px #0a6aa1;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:#fff;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;-moz-text-shadow:0 0 0 transparent;-webkit-text-shadow:0 0 0 transparent;text-shadow:0 0 0 transparent;-webkit-box-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;-webkit-border-radius:0;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;-webkit-box-shadow:0 0 0;box-shadow:0 0 0}.vakata-context li>a>i{text-decoration:none;display:inline-block;height:2.4em;background:0 0;margin:0 0 0 -2em;vertical-align:top;text-align:center}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:#fff;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url(data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7);background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:#fff;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-copy,#jstree-dnd .jstree-icon{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:green}#jstree-dnd .jstree-er{background:red}#jstree-dnd .jstree-copy{margin:0 2px}.jstree-default .jstree-icon,.jstree-default .jstree-node{background-repeat:no-repeat;background-color:transparent}.jstree-default .jstree-anchor,.jstree-default .jstree-wholerow{-webkit-transition:background-color .15s,-webkit-box-shadow .15s;-o-transition:background-color .15s,box-shadow .15s;transition:background-color .15s,box-shadow .15s}.jstree-default .jstree-hovered{background:#e7f4f9;-webkit-border-radius:2px;border-radius:2px;-webkit-box-shadow:inset 0 0 1px #ccc;box-shadow:inset 0 0 1px #ccc}.jstree-default .jstree-clicked{background:#beebff;-webkit-border-radius:2px;border-radius:2px;-webkit-box-shadow:inset 0 0 1px #999;box-shadow:inset 0 0 1px #999}.jstree-default .jstree-no-icons .jstree-anchor>.jstree-themeicon{display:none}.jstree-default .jstree-disabled{color:#666}.jstree-default .jstree-disabled.jstree-hovered{-webkit-box-shadow:none;box-shadow:none}.jstree-default .jstree-disabled>.jstree-icon{opacity:.8;filter:url("data:image/svg+xml;utf8,#jstree-grayscale");filter:gray;-webkit-filter:grayscale(100%)}.jstree-default .jstree-search{font-style:italic;color:#8b0000;font-weight:700}.jstree-default .jstree-no-checkboxes .jstree-checkbox{display:none!important}.jstree-default.jstree-checkbox-no-clicked .jstree-clicked{background:0 0;-webkit-box-shadow:none;box-shadow:none}.jstree-default.jstree-checkbox-no-clicked .jstree-clicked.jstree-hovered{background:#e7f4f9}.jstree-default.jstree-checkbox-no-clicked>.jstree-wholerow-ul .jstree-wholerow-clicked{background:0 0}.jstree-default.jstree-checkbox-no-clicked>.jstree-wholerow-ul .jstree-wholerow-clicked.jstree-wholerow-hovered{background:#e7f4f9}.jstree-default>.jstree-striped{background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAMAAAB/qqA+AAAABlBMVEUAAAAAAAClZ7nPAAAAAnRSTlMNAMM9s3UAAAAXSURBVHjajcEBAQAAAIKg/H/aCQZ70AUBjAATb6YPDgAAAABJRU5ErkJggg==) left top}.jstree-default>.jstree-wholerow-ul .jstree-clicked,.jstree-default>.jstree-wholerow-ul .jstree-hovered{background:0 0;-webkit-box-shadow:none;box-shadow:none;-webkit-border-radius:0;border-radius:0}.jstree-default .jstree-wholerow{-webkit-box-sizing:border-box;box-sizing:border-box;height:24px}.jstree-default .jstree-wholerow-hovered{background:#e7f4f9}.jstree-default .jstree-wholerow-clicked{background:#beebff;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#beebff),color-stop(100%,#a8e4ff));background:-webkit-linear-gradient(top,#beebff 0,#a8e4ff 100%);background:-o-linear-gradient(top,#beebff 0,#a8e4ff 100%);background:-webkit-gradient(linear,left top,left bottom,from(#beebff),to(#a8e4ff));background:linear-gradient(to bottom,#beebff 0,#a8e4ff 100%)}.jstree-default .jstree-node{min-height:24px;line-height:24px;margin-left:24px;min-width:24px;background-position:-292px -4px;background-repeat:repeat-y}.jstree-default .jstree-anchor{line-height:24px;height:24px}.jstree-default .jstree-icon,.jstree-default .jstree-icon:empty{width:24px;height:24px;line-height:24px}.jstree-default .jstree-icon,.jstree-default .jstree-node{background-image:url(32px.png)}.jstree-default .jstree-last{background:0 0}.jstree-default .jstree-open>.jstree-ocl{background-position:-132px -4px}.jstree-default .jstree-closed>.jstree-ocl{background-position:-100px -4px}.jstree-default .jstree-leaf>.jstree-ocl{background-position:-68px -4px}.jstree-default .jstree-themeicon{background-position:-260px -4px}.jstree-default>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default>.jstree-no-dots .jstree-node{background:0 0}.jstree-default>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-36px -4px}.jstree-default>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-4px -4px}.jstree-default .jstree-disabled,.jstree-default .jstree-disabled.jstree-hovered{background:0 0}.jstree-default .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default .jstree-checkbox{background-position:-164px -4px}.jstree-default .jstree-checkbox:hover{background-position:-164px -36px}.jstree-default .jstree-checked>.jstree-checkbox,.jstree-default.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox{background-position:-228px -4px}.jstree-default .jstree-checked>.jstree-checkbox:hover,.jstree-default.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover{background-position:-228px -36px}.jstree-default .jstree-anchor>.jstree-undetermined{background-position:-196px -4px}.jstree-default .jstree-anchor>.jstree-undetermined:hover{background-position:-196px -36px}.jstree-default>.jstree-striped{-webkit-background-size:auto 48px;background-size:auto 48px}.jstree-default.jstree-rtl .jstree-node{margin-right:24px;background-position:100% 1px;background-repeat:repeat-y}.jstree-default.jstree-rtl .jstree-open>.jstree-ocl{background-position:-132px -36px}.jstree-default.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-100px -36px}.jstree-default.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-68px -36px}.jstree-default.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default.jstree-rtl>.jstree-no-dots .jstree-node{background:0 0}.jstree-default.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-36px -36px}.jstree-default.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-4px -36px}.jstree-default .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default .jstree-file{background:url(32px.png) -100px -68px no-repeat}.jstree-default .jstree-folder{background:url(32px.png) -260px -4px no-repeat}.jstree-default>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default{line-height:24px;padding:0 4px}#jstree-dnd.jstree-default .jstree-er,#jstree-dnd.jstree-default .jstree-ok{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default i{background:0 0;width:24px;height:24px;line-height:24px}#jstree-dnd.jstree-default .jstree-ok{background-position:-4px -68px}#jstree-dnd.jstree-default .jstree-er{background-position:-36px -68px}.jstree-default.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==)}.jstree-default.jstree-rtl .jstree-last{background:0 0}.jstree-default-small .jstree-node{min-height:18px;line-height:18px;margin-left:18px;min-width:18px;background-position:-295px -7px;background-repeat:repeat-y}.jstree-default-small .jstree-anchor{line-height:18px;height:18px}.jstree-default-small .jstree-icon,.jstree-default-small .jstree-icon:empty{width:18px;height:18px;line-height:18px}.jstree-default-small .jstree-wholerow{height:18px}.jstree-default-small .jstree-icon,.jstree-default-small .jstree-node{background-image:url(32px.png)}.jstree-default-small .jstree-last{background:0 0}.jstree-default-small .jstree-open>.jstree-ocl{background-position:-135px -7px}.jstree-default-small .jstree-closed>.jstree-ocl{background-position:-103px -7px}.jstree-default-small .jstree-leaf>.jstree-ocl{background-position:-71px -7px}.jstree-default-small .jstree-themeicon{background-position:-263px -7px}.jstree-default-small>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default-small>.jstree-no-dots .jstree-node{background:0 0}.jstree-default-small>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-39px -7px}.jstree-default-small>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-7px -7px}.jstree-default-small .jstree-disabled,.jstree-default-small .jstree-disabled.jstree-hovered{background:0 0}.jstree-default-small .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default-small .jstree-checkbox{background-position:-167px -7px}.jstree-default-small .jstree-checkbox:hover{background-position:-167px -39px}.jstree-default-small .jstree-checked>.jstree-checkbox,.jstree-default-small.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox{background-position:-231px -7px}.jstree-default-small .jstree-checked>.jstree-checkbox:hover,.jstree-default-small.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover{background-position:-231px -39px}.jstree-default-small .jstree-anchor>.jstree-undetermined{background-position:-199px -7px}.jstree-default-small .jstree-anchor>.jstree-undetermined:hover{background-position:-199px -39px}.jstree-default-small>.jstree-striped{-webkit-background-size:auto 36px;background-size:auto 36px}.jstree-default-small.jstree-rtl .jstree-node{margin-right:18px;background-position:100% 1px;background-repeat:repeat-y}.jstree-default-small.jstree-rtl .jstree-open>.jstree-ocl{background-position:-135px -39px}.jstree-default-small.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-103px -39px}.jstree-default-small.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-71px -39px}.jstree-default-small.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default-small.jstree-rtl>.jstree-no-dots .jstree-node{background:0 0}.jstree-default-small.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-39px -39px}.jstree-default-small.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-7px -39px}.jstree-default-small .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-small>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default-small .jstree-file{background:url(32px.png) -103px -71px no-repeat}.jstree-default-small .jstree-folder{background:url(32px.png) -263px -7px no-repeat}.jstree-default-small>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default-small{line-height:18px;padding:0 4px}#jstree-dnd.jstree-default-small .jstree-er,#jstree-dnd.jstree-default-small .jstree-ok{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default-small i{background:0 0;width:18px;height:18px;line-height:18px}#jstree-dnd.jstree-default-small .jstree-ok{background-position:-7px -71px}#jstree-dnd.jstree-default-small .jstree-er{background-position:-39px -71px}.jstree-default-small.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAACAQMAAABv1h6PAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMHBgAAiABBI4gz9AAAAABJRU5ErkJggg==)}.jstree-default-small.jstree-rtl .jstree-last{background:0 0}.jstree-default-large .jstree-node{min-height:32px;line-height:32px;margin-left:32px;min-width:32px;background-position:-288px 0;background-repeat:repeat-y}.jstree-default-large .jstree-anchor{line-height:32px;height:32px}.jstree-default-large .jstree-icon,.jstree-default-large .jstree-icon:empty{width:32px;height:32px;line-height:32px}.jstree-default-large .jstree-wholerow{height:32px}.jstree-default-large .jstree-icon,.jstree-default-large .jstree-node{background-image:url(32px.png)}.jstree-default-large .jstree-last{background:0 0}.jstree-default-large .jstree-open>.jstree-ocl{background-position:-128px 0}.jstree-default-large .jstree-closed>.jstree-ocl{background-position:-96px 0}.jstree-default-large .jstree-leaf>.jstree-ocl{background-position:-64px 0}.jstree-default-large .jstree-themeicon{background-position:-256px 0}.jstree-default-large>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default-large>.jstree-no-dots .jstree-node{background:0 0}.jstree-default-large>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-32px 0}.jstree-default-large>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:0 0}.jstree-default-large .jstree-disabled,.jstree-default-large .jstree-disabled.jstree-hovered{background:0 0}.jstree-default-large .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default-large .jstree-checkbox{background-position:-160px 0}.jstree-default-large .jstree-checkbox:hover{background-position:-160px -32px}.jstree-default-large .jstree-checked>.jstree-checkbox,.jstree-default-large.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox{background-position:-224px 0}.jstree-default-large .jstree-checked>.jstree-checkbox:hover,.jstree-default-large.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover{background-position:-224px -32px}.jstree-default-large .jstree-anchor>.jstree-undetermined{background-position:-192px 0}.jstree-default-large .jstree-anchor>.jstree-undetermined:hover{background-position:-192px -32px}.jstree-default-large>.jstree-striped{-webkit-background-size:auto 64px;background-size:auto 64px}.jstree-default-large.jstree-rtl .jstree-node{margin-right:32px;background-position:100% 1px;background-repeat:repeat-y}.jstree-default-large.jstree-rtl .jstree-open>.jstree-ocl{background-position:-128px -32px}.jstree-default-large.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-96px -32px}.jstree-default-large.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-64px -32px}.jstree-default-large.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl,.jstree-default-large.jstree-rtl>.jstree-no-dots .jstree-node{background:0 0}.jstree-default-large.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-32px -32px}.jstree-default-large.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:0 -32px}.jstree-default-large .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-large>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default-large .jstree-file{background:url(32px.png) -96px -64px no-repeat}.jstree-default-large .jstree-folder{background:url(32px.png) -256px 0 no-repeat}.jstree-default-large>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default-large{line-height:32px;padding:0 4px}#jstree-dnd.jstree-default-large .jstree-er,#jstree-dnd.jstree-default-large .jstree-ok{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default-large i{background:0 0;width:32px;height:32px;line-height:32px}#jstree-dnd.jstree-default-large .jstree-ok{background-position:0 -64px}#jstree-dnd.jstree-default-large .jstree-er{background-position:-32px -64px}.jstree-default-large.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAACAQMAAAAD0EyKAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjgIIGBgABCgCBvVLXcAAAAABJRU5ErkJggg==)}.jstree-default-large.jstree-rtl .jstree-last{background:0 0}@media (max-width:768px){#jstree-dnd.jstree-dnd-responsive{line-height:40px;font-weight:700;text-shadow:1px 1px #fff}#jstree-dnd.jstree-dnd-responsive>i{background:0 0;width:40px;height:40px}#jstree-dnd.jstree-dnd-responsive>.jstree-ok{background-image:url(40px.png);background-position:0 -200px;-webkit-background-size:120px 240px;background-size:120px 240px}#jstree-dnd.jstree-dnd-responsive>.jstree-er{background-image:url(40px.png);background-position:-40px -200px;-webkit-background-size:120px 240px;background-size:120px 240px}#jstree-marker.jstree-dnd-responsive{border-left-width:10px;border-top-width:10px;border-bottom-width:10px;margin-top:-10px}.jstree-default-responsive .jstree-leaf>.jstree-ocl,.jstree-default-responsive .jstree-node{background:0 0}.jstree-default-responsive .jstree-node{min-height:40px;line-height:40px;margin-left:40px;min-width:40px;white-space:nowrap}.jstree-default-responsive .jstree-anchor{line-height:40px;height:40px;font-weight:700;text-shadow:1px 1px #fff}.jstree-default-responsive .jstree-icon,.jstree-default-responsive .jstree-icon:empty{width:40px;height:40px;line-height:40px}.jstree-default-responsive.jstree-rtl .jstree-node{margin-left:0;margin-right:40px}.jstree-default-responsive.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-default-responsive .jstree-checkbox,.jstree-default-responsive .jstree-ocl,.jstree-default-responsive .jstree-themeicon{-webkit-background-size:120px 240px;background-size:120px 240px}.jstree-default-responsive .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-responsive .jstree-open>.jstree-ocl{background-position:0 0!important}.jstree-default-responsive .jstree-closed>.jstree-ocl{background-position:0 -40px!important}.jstree-default-responsive.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-40px 0!important}.jstree-default-responsive .jstree-themeicon{background-position:-40px -40px}.jstree-default-responsive .jstree-checkbox,.jstree-default-responsive .jstree-checkbox:hover{background-position:-40px -80px}.jstree-default-responsive .jstree-checked>.jstree-checkbox,.jstree-default-responsive .jstree-checked>.jstree-checkbox:hover,.jstree-default-responsive.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox,.jstree-default-responsive.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover{background-position:0 -80px}.jstree-default-responsive .jstree-anchor>.jstree-undetermined,.jstree-default-responsive .jstree-anchor>.jstree-undetermined:hover{background-position:0 -120px}.jstree-default-responsive>.jstree-striped{background:0 0}.jstree-default-responsive .jstree-wholerow{border-top:1px solid rgba(255,255,255,.7);border-bottom:1px solid rgba(64,64,64,.2);background:#ebebeb;height:40px}.jstree-default-responsive .jstree-wholerow-hovered{background:#e7f4f9}.jstree-default-responsive .jstree-wholerow-clicked{background:#beebff}.jstree-default-responsive .jstree-children .jstree-last>.jstree-wholerow{-webkit-box-shadow:inset 0 -6px 3px -5px #666;box-shadow:inset 0 -6px 3px -5px #666}.jstree-default-responsive .jstree-children .jstree-open>.jstree-wholerow{-webkit-box-shadow:inset 0 6px 3px -5px #666;box-shadow:inset 0 6px 3px -5px #666;border-top:0}.jstree-default-responsive .jstree-children .jstree-open+.jstree-open{-webkit-box-shadow:none;box-shadow:none}.jstree-default-responsive .jstree-checkbox,.jstree-default-responsive .jstree-icon,.jstree-default-responsive .jstree-node,.jstree-default-responsive .jstree-node>.jstree-ocl,.jstree-default-responsive .jstree-themeicon{background-image:url(40px.png);-webkit-background-size:120px 240px;background-size:120px 240px}.jstree-default-responsive .jstree-node{background-position:-80px 0;background-repeat:repeat-y}.jstree-default-responsive .jstree-last{background:0 0}.jstree-default-responsive .jstree-leaf>.jstree-ocl{background-position:-40px -120px}.jstree-default-responsive .jstree-last>.jstree-ocl{background-position:-40px -160px}.jstree-default-responsive .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-responsive .jstree-file{background:url(40px.png) 0 -160px no-repeat;-webkit-background-size:120px 240px;background-size:120px 240px}.jstree-default-responsive .jstree-folder{background:url(40px.png) -40px -40px no-repeat;-webkit-background-size:120px 240px;background-size:120px 240px}.jstree-default-responsive>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}} \ No newline at end of file diff --git a/dashboard-ui/thirdparty/paper-button-style.css b/dashboard-ui/thirdparty/paper-button-style.css index 015404e45e..a111cc7f26 100644 --- a/dashboard-ui/thirdparty/paper-button-style.css +++ b/dashboard-ui/thirdparty/paper-button-style.css @@ -1,91 +1 @@ -.ui-body-b .raised { - background: rgba(170,170,190, .4); - color: #fff; -} - -.ui-body-a .raised { - background: #3388cc; - color: #fff; -} - -.ui-body-a .button-submit { - background: #52B54B; - color: #fff; -} - -.ui-body-a .button-cancel { - background: #fff; - color: inherit; - box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); -} - -.ui-body-b .button-submit { - background: #52B54B; - color: #fff; -} - -.ui-body-a .button-accent, .ui-body-b .button-accent { - background: #52B54B; - color: #fff; -} - -.button-accent-flat { - color: #52B54B !important; -} - -button.emby-button.raised.more { - background: #3388cc; - color: #fff; -} - -.emby-button > span { - vertical-align: middle; -} - -.clearButton { - background: transparent; - border: 0; - padding: 0; - cursor: pointer; - outline: none; - color: inherit; - width: 100%; - vertical-align: middle; - font-family: inherit; - font-weight: inherit; -} - -.clearLink { - text-decoration: none; - font-weight: inherit !important; - vertical-align: middle; - color: inherit !important; -} - -button.emby-button.mini:not(.fab) { - padding: 0.5em 0.7em; -} - -.ui-body-b .paperListLabel, .ui-body-b .fieldDescription, .ui-body-b .selectLabelUnfocused, .ui-body-b .inputLabelUnfocused, .ui-body-b .textareaLabelUnfocused { - color: #ccc; -} - -.ui-body-b .paperList { - background-color: #2b2b2b; -} - -.ui-body-a div.formDialogHeader { - background-color: #52B54B; - color: #fff; -} - -.ui-body-a div.formDialogFooter { - background-color: #f0f0f0; - border-top: 1px solid #ddd; - color: inherit; -} - -.ui-body-a .formDialogHeader a { - color: #fff !important; - text-transform: uppercase; -} +.clearButton,.clearLink,.emby-button>span{vertical-align:middle}.ui-body-b .raised{background:rgba(170,170,190,.4);color:#fff}.ui-body-a .raised{background:#38c;color:#fff}.ui-body-a .button-submit{background:#52B54B;color:#fff}.ui-body-a .button-cancel{background:#fff;color:inherit;-webkit-box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2);box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12),0 3px 1px -2px rgba(0,0,0,.2)}.ui-body-a .button-accent,.ui-body-b .button-accent,.ui-body-b .button-submit{background:#52B54B;color:#fff}.button-accent-flat{color:#52B54B!important}button.emby-button.raised.more{background:#38c;color:#fff}.clearButton{background:0 0;border:0;padding:0;cursor:pointer;outline:0;color:inherit;width:100%;font-family:inherit;font-weight:inherit}.clearLink{text-decoration:none;font-weight:inherit!important;color:inherit!important}button.emby-button.mini:not(.fab){padding:.5em .7em}.ui-body-b .fieldDescription,.ui-body-b .inputLabelUnfocused,.ui-body-b .paperListLabel,.ui-body-b .selectLabelUnfocused,.ui-body-b .textareaLabelUnfocused{color:#ccc}.ui-body-b .paperList{background-color:#2b2b2b}.ui-body-a div.formDialogHeader{background-color:#52B54B;color:#fff}.ui-body-a div.formDialogFooter{background-color:#f0f0f0;border-top:1px solid #ddd;color:inherit}.ui-body-a .formDialogHeader a{color:#fff!important;text-transform:uppercase} \ No newline at end of file