Supercharged Local Directory File Browser

Makes file:/// directory ("Index of...") pages (and many server-generated index pages) actually useful. Adds sidebar and preview pane; keyboard navigation and sorting; media playback with shuffle, loop, and playlist (m3u) support; preview, edit, and save markdown/plain text files; preview images and fonts, with grid view; user-defined bookmarks; more.

Tính đến 22-09-2019. Xem phiên bản mới nhất.

// ==UserScript==
// @name              Supercharged Local Directory File Browser
// @version           4.1.3.2
// @description       Makes file:/// directory ("Index of...") pages (and many server-generated index pages) actually useful. Adds sidebar and preview pane; keyboard navigation and sorting; media playback with shuffle, loop, and playlist (m3u) support; preview, edit, and save markdown/plain text files; preview images and fonts, with grid view; user-defined bookmarks; more.
// @author            gaspar_schot
// @license           GPL-3.0-or-later
// @homepageURL       https://openuserjs.org/scripts/gaspar_schot/Supercharged_Local_Directory_File_Browser
// @contributionURL   https://paypal.me/mschrauzer
// @include           file://*
// @include           about:blank

// @require      https://code.jquery.com/jquery-latest.min.js

// @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it/9.0.1/markdown-it.js
// @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it-footnote/3.0.2/markdown-it-footnote.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-toc-done-right@2.1.0/dist/markdown-it-toc-made-right.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-sub@1.0.0/dist/markdown-it-sub.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-sup@1.0.0/dist/markdown-it-sup.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-deflist@2.0.3/dist/markdown-it-deflist.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-multimd-table@3.2.3/dist/markdown-it-multimd-table.min.js
// @require https://cdn.jsdelivr.net/npm/markdown-it-center-text@1.0.4/dist/markdown-it-center-text.min.js

// @require https://cdn.jsdelivr.net/npm/opentype.js@latest/dist/opentype.min.js

// UPDATE URL

// NOTE: This script was developed in Vivaldi, running on Mac OS High Sierra. It has been tested in various Chrome and Gecko-based browsers.
// It has been minimally tested on Windows and not at all on other OSes. It should work, but please report any issues.
// The script does not work on local directories in Safari because Safari does not allow local directories to be browsed, but it will work on remote directories (or on local directories through a local server).

// NOTE: By default, Greasemonkey and Tampermonkey will not run scripts on file:/// urls, so for this script to work, you will have to enable it first.
// For Tampermonkey, go to Chrome extension page, and tick the 'Allow access to file URLs' checkbox at the Tampermonkey extension section.
// For Greasemonkey, open about:config and change greasemonkey.fileIsGreaseable to true.

// @namespace https://greasyfork.org/users/16170
// ==/UserScript==

(function() {
	'use strict';
	const $ = window.jQuery;

    // ***** USER SETTINGS ***** //

	const $settings = {
		// Paste your exported settings between the two lines below:
		//--------------------------------------------------------//

		bookmarks: // N.B.: Directory links must end with "/", file links must end with another character.
		// You may add as many menus and links as you like; just copy the example below and edit as needed.
		// Local directory bookmarks must begin with "file:///"; external bookmarks must begin with the correct protocol ("http://" or "ftp://", etc.).
		// Note that because of same-origin security concerns, the browser will not allow you to navigate from an external webpage to a local directory.
		// But see this page for possible workarounds: https://stackoverflow.com/questions/39007243/cannot-open-local-file-chrome-not-allowed-to-load-local-resource
		[
            {
                "menu_title":"My Sample Menu",
                "links":
                [
                    { "link_name":"My Directory Link 1", "link":"file:///Path/To/My/Directory/" },
                    { "link_name":"My Directory Link 2", "link":"file:///Path/To/My/Directory_2/" },
                    { "link_name":"My External Link", "link":"https://www.mywebpage.com/" },
                    { "link_name":"My File Link", "link":"file:///Path/To/My/File.ext" },
                ]
            },
            {
                "menu_title":"My Second Sample Menu",
                "links":
                [
                    { "link_name":"My Directory Link 1", "link":"file:///Path/To/My/Directory/" },
                    { "link_name":"My Directory Link 2", "link":"file:///Path/To/My/Directory_2/" },
                    { "link_name":"My External Link", "link":"https://www.mywebpage.com/" },
                    { "link_name":"My File Link", "link":"file:///Path/To/My/File.ext" },
                ]
            },
        ],
		// GENERAL USER SETTINGS
		alternate_background:  true,       // If true (default true), alternate sidebar row background color.
		apps_as_dirs:         false,       // Un*x/Mac OS only: if true, treat apps as directories; allows app contents to be browsed. This is the default behavior for Chrome.
                                              // If false (default), treat apps as ignored files.
		autoload_media:        true,       // If true (default: true), the first audio or video file found in a directory will be automatically selected and loaded for playback; also, cover art (if any, will be loaded in the preview pane).
		autoload_index_files: false,       // If true (default: false), automatically select first "index.xxx" (.xxx !== .htm) file found in directory.
                                              // Note: the browser will automatically load any index.html files it finds in the directory, so the script will not work properly in such cases.
		theme:              'light',       // Options: 'light' or 'dark'
		sort_by:          'default',       // Choose from: 'name', 'size', 'date', 'kind', 'ext', 'default'.
                                              // default = Chrome sorting: dirs on top, files alphabetical.
		dirs_on_top:          false,       // If true, directories will always be listed firs except when sorting by "name" (since otherwise sorting by "name" would equal "default").
                                              // If false (default), directories and files will be sorted together. (In practice, dirs will typically still be separated when sorting by size, kind, and extension.)
		grid_font_size:           1,       // Default = 1
		grid_image_size:        184,       // Default = 184 (200px - 16px)
		show_details:          true,       // If true (default), hide file and directory details; if false, show them.
		show_ignored_files:   false,       // If true, ignored files will appear greyed-out.
                                              // If false (default), ignored files will be completely hidden from the file list;
		ignore_ignored_files:  true,       // If true (default), ignored files (see "$row_settings" below, after Keybindings and Changelog) will be greyed-out (default) in the file list and will not be loaded in the content pane when selected;
                                              // If false, ignored files will be treated like normal files, so if they are selected, the browser will attempt to download any file types it can't handle (which makes keyboard navigation inconvenient but may be useful in some circumstances).
		show_invisibles:       true,       // Un*x/Mac OS only: If true (default), files or directories beginning with a "." will be hidden.
		show_numbers:          true,       // If true (default true), number index items
		UI_font: 'system-ui, sans-serif',  // Choose an installed font for the UI; if undefined, use browser defaults instead.
		UI_font_size:        '13px',       // Choose a default UI font size; use any standard CSS units.
		use_custom_icons:      true,       // if true (default), use custom icons for dirs and files
                                              // if false, use browser/server default icons
		// TEXT EDITING SETTINGS
		enable_text_editing:   true,       // If true (default), allow plain text files to be edited.
		default_text_view: 'preview_text', // Options: 'source_text' or 'preview_text' for text editor.
                                              // Note that split_view = true overrides this setting.
		split_view:            true,       // If true, show split view on plain text file load.
                                              // if true (default), use default preview_text setting.
		sync_scroll:           true        // If true (default: true), show split view on plain text file load
                                              // if false, use default preview_text setting.
		//--------------------------------------------------------//
		// Paste your exported settings between the above two lines.
	};

	// $ROW_TYPES:
	// DO NOT DELETE ANY EXISTING CATEGORIES!
	// Add file extensions for sorting and custom icon display to the existing categories.
	// You can also define your own new categories, but do not add an extension to more than one row_type category.
	// Do not add leading "." to the extensions.
	const $row_types = {
		// myRowType: ['ext1','ext2'],
		dir:      ['/'],
		app:      ['app/','app','bat','cgi','com','exe','jar','msi','wsf'],
		alias:    ['alias','desktop','directory','lnk','symlink'],
		archive:  ['7z','archive','b6z','bin','bzip','bz2','cbr','dmg','gz','iso','mpkg','pkg','rar','sit','sitx','tar','tar.gz','zip','zipx'],
		audio:    ['aac','aif','aiff','ape','flac','m4a','mp3','ogg','opus','wav'],
		bin:      ['a','dll','dylib','icc','msi','o'],
		code:     ['bak','bash','bash_profile','bashrc','c','cfg','cnf','codes','coffee','conf','csh','cshrc','cson','css','custom_aliases','default','dist','editorconfig','emacs','example','gemspec','gitconfig','gitignore','gitignore_global','h','hd','ini','js','json','jsx','less','list','local','login','logout','lua','mkshrc','old','php','pl','plist','pre-oh-my-zsh','profile','pth','py','rb','rc','rdoc','sass','settings','sh','strings','taskrc','tcl','viminfo','vimrc','vue','xml','yaml','yml','zlogin','zlogout','zpreztorc','zprofile','zsh','zshenv','zshrc'],
		database: ['accdb','db','dbf','mdb','pdb','sql', 'sqlite','sqlitedb','sqlite3'],
		ebook:    ['azw','azw1','azw3','azw4','epub','ibook','kfx','mobi','tpz'],
		font:     ['otf','ttf','woff','woff2','afm','pfb','pfm','tfm'],
		graphics: ['afdesign','ai','book','dtp','eps','fm','icml','idml','indd','indt','inx','mif','pmd','pub','qxb','qxd','qxp','sla','swf'],
		htm:      ['htm','html','xhtm','xhtml'],
		image:    ['apng','bmp','gif','ico','jpeg','jpg','png','svg','webp'],
		ignored_image: ['ai','arw','cr2','dng','eps','jpf','nef','psd','psd','raw','tif','tiff'],
		markdown: ['md','markdown','mdown','mkdn','mkd','mdwn','mdtxt','mdtext'],
		office:   ['csv','doc','docx','epub','key','numbers','odf','ods','odt','pages','rtf','scriv','wpd','wps','xlr','xls','xlsx','xlm'],
		pdf:      ['pdf'],
		system:   ['DS_Store','ds_store','icon','ics'],
		text:     ['log','nfo','txt','m3u'],
		video:    ['m4v','mov','mp4','mpeg','webm']
	};

	// $ROW_SETTINGS: Ignore or Exclude files by extension
	const $row_settings = {
		// Ignore: $row_types or files with extensions added here will not be loaded if selected in the sidebar (prevents the browser from attempting to download the file).
		ignore: $row_types.archive.concat( 'alias', $row_types.bin, $row_types.database, $row_types.graphics, $row_types.ignored_image, $row_types.office, $row_types.system),
		// Exclude: Files with these exensions will not be inverted in dark mode
		exclude: ['htm','html','xhtm','xhtml']
	};

	// ***** END USER SETTINGS ***** //

	// ## FEATURES INCLUDE:
	// - Resizable sidebar and directory/file preview pane.
	// - Arrow navigation in sidebar:
	//   - Up and Down Arrows select next/prev item.
	//   - Left and Right Arrows select next/prev item of same type.
	// - Navigate sidebar by typed string.
	// - Show/Hide file details (size (if avail), date modified (if avail), kind, extension).
	// - Sort sidebar items by name or file details.
	//   - Default sort = sort by name with folders on top.
	// - Preview all file types supported by browser (html, text, images, pdf, audio, video, etc.) and preview fonts.
	// - Preview and edit markdown and plain text files, with option to save files locally.
	//   - Markdown rendered with markdownit.js ( https://github.com/markdown-it/markdown-it ).
	//   - Uses Github Markdown styles for preview ( https://github.com/sindresorhus/github-markdown-css ), with a few customizations.
	//   - Support for:
	//     - TOC creation ( `${toc}` ) ( https://github.com/nagaozen/markdown-it-toc-done-right )
	//     - Multimarkdown table syntax ( https://github.com/RedBug312/markdown-it-multimd-table )
	//     - Live checkboxes ( `\[ ], [x]` ), allowed in lists and deflists.
	//     - Superscript ( `^sup^` ) ( https://github.com/markdown-it/markdown-it-sup )
	//     - Subscript ( `~sub~` ) ( https://github.com/markdown-it/markdown-it-sub )
	//     - Definition lists ( https://github.com/markdown-it/markdown-it-deflist; for syntax, see http://pandoc.org/MANUAL.html#definition-lists )
	//     - Centered text ( `->centered<-` ) ( https://github.com/jay-hodgson/markdown-it-center-text )
	//     - Footnotes ( https://github.com/markdown-it/markdown-it-footnote )
	//   - View source text, preview, or split pane with proportional sync scroll.
	//   - Save edited source text or previewed HTML.
	// - Create and edit text in separate text editor.
	// - Audio and video playback, with shuffle, loop, skip audio +/- 10 or 30 sec via keyboard.
	//   - Preview other files (e.g., lyrics or cover art) in same directory while playing audio.
	//   - User setting to autoload cover art (if any images in directory, load "cover.ext" or first image found)
	//   - Grid view for images and fonts.
	// - User settings (see $settings in code; some settings can be changed via the main menu in the UI and will be remembered in URL query):
	//   - Light or Dark theme.
	//   - Bookmarks for local or remote directories.
	//   - Default image grid size.
	//   - Default UI font size and font-family.
	//   - Default UI font and font-size.
	//   - Default file sorting.
	//   - Sort with directories on top.
	//   - Treat apps as directories (MacOS and *nix only)
	//   - Show or hide invisible files.
	//   - Show or hide ignored files in the ignored files list (see $row_settings in code below $settings).
	//   - Show or hide file details.
	//   - Use custom file icons or browser defaults.
	//   - Autoload index.ext files.
	//   - Autoload cover art in directories with audio files.
	//   - Text editing default view: split, source, or preview.
	//   - Text editing sync scroll: on or off.

	// ## KEYBINDINGS (These don't work in all browsers):

	// - <kbd>Arrow Up/Down</kbd>: Select prev/next item.
	//   - If audio is playing, and prev/next file is also audio, it will be highlighted but not loaded in the audio player; press return to load it.
	// - <kbd>Arrow Left/Right</kbd>: Select prev/next row of the same kind as the current selection.
	//   - If current selection is a media file, select and begin playback of the next media item.
	// - <kbd>Opt/Alt + Arrow Left/Right</kbd>: Skip audio ±10s
	// - <kbd>Opt/Alt + Shift + Arrow Left/Right</kbd>: Skip audio ±30s
	// - <kbd>Cmd/Ctrl + Arrow Up</kbd>: Go to parent directory
	// - <kbd>Cmd/Ctrl + Arrow Down</kbd>: Open selected directory
	// - <kbd>Return</kbd>: Open selected directory, select file, or pause/play media.
	// - <kbd>Space</kbd>: Pause/Play media files
	// - <kbd>Cmd/Ctrl + D</kbd>: Toggle file details (size, date modified) in some index page types.
	// - <kbd>Cmd/Ctrl + E</kbd>: Show text editor.
	// - <kbd>Cmd/Ctrl + G</kbd>: Show or Reset Grid.
	// - <kbd>Cmd/Ctrl + I</kbd>: Toggle Invisibles.
	// - <kbd>Cmd/Ctrl + Shift + O</kbd>: Open selected item in new window/tab.
	// - <kbd>Cmd/Ctrl + R</kbd>: Reload grids and previewed content, reset scaled images/fonts, reset media files to beginning.
	// - <kbd>Cmd/Ctrl + W</kbd>: Close previewed content (doesn't work in all browsers; use close button instead), or close window if no content is being previewed.
	// - <kbd>Cmd/Ctrl + Shift + < or ></kbd>: Scale preview items and grids.

	// CHANGELOG:

    // **VERSION 4.1.3.2**
    // **FIXED:** Image grid didn't show SVG files if width and height were set to 100%.
    // **FIXED:** Up/Down arrow navigation didn't work for images with hidden grid.
    // Added custom folder favicon for local directories.
    // Other small style tweaks.

    // **VERSION 4.1.3.1**
    // **FIXED:** Images couldn't be scaled to less than 24 x 24px.

    // **VERSION 4.1.3**
    // **FIXED:** _Finally_ fixed image scaling and zooming. Sorry for the delay.
    // **IMPROVED:** Allow image scaling > 100%.
    // **IMPROVED:** Show image scale percentage in the content title bar.
    // **IMPROVED:** Show custom file icons in content title bar.
    // **IMPROVED:** Highlight grid button when grid is loaded (or hidden).
    // **FIXED:** Invisible files were being selected even if "Show invisibles" was unchecked.
    // Various other small fixes and style tweaks.

    // **VERSION 4.1.2**
    // **FIXED, CHANGED, & IMPROVED:** Image, font, and font glyph grids.
    //   - Added up/down arrow navigation. This is a change from the previous behavior, where up/down arrows always navigated the sidebar. This will also work if the grid is hidden after selecting an image or font glyph.
    //   - Also added arrow navigation for font glyphs, and :hover and selected styles.
    //   - Fixed a deeply-buried bug that prevented the selected grid item from scrolling into view with arrow navigation.
    //   - Fixed a stupid bug that prevented the first font in the directory from being included in the grid.
    //   - Fixed some problems with normal font file browsing after viewing font glyphs.
    //   - Improved styling for previewed and zoomed images.
    //
    // **FIXED and IMPROVED:** Playlists.
    //   - Window title and sidebar head are now reset to indicate presence of playlist.
    //   - First track wasn't being selected when "autoload_media" = true.
    //   - Directory stats weren't being reset after closing a playlist.
    //   - Grid button and "show invisibles" checkbox are hidden with open playlist.
    //
    // **IMPROVED:** Currently selected sidebar item will now scroll into view after various events, like sorting change, showing/hiding details, resizing sidebar, etc.
    // **FIXED:** Several menu items weren't working: Default User Settings, Export User settings, Contact, and [Donate](https://paypal.me/mschrauzer) (that might explain a few things...).
    // **FIXED:** Document title didn't include entire path.
    // Many other small bug fixes and style tweaks, including some specifically for Firefox and Safari.

    // **VERSION 4.1.1**
    // A few small fixes and style tweaks.

    // **VERSION 4.1.0**
    // **NEW:** Basic support for media playlists (.m3u and .m3u8).
    // - Added "Open Playlist..." item to the main menu.
    // - Playlist items will replace the current directory items in the sidebar. Times (if available) will be displayed in the "size" column. "Default" sorting = original playlist sort.
    // - Playlist can be closed via the "Close" button or shortcut, and the previous directory contents will be loaded.
    // - Streaming links are not supported.
    // - Beware of cross-origin limitations. For example, if your playlist includes locally-hosted media files, you will need to load it from a file:/// page in your browser.
    // - For remote files, if you are using a javascript-blocker (like uMatrix or NoScript), you may have to allow scripts from the hosting site (e.g., archive.org) in order for playback to work.
    // **NEW:** Open local fonts directly and view font information and complete glyph repertoire. (The previous ability to browse fonts in the directory list is unchanged.)
    // - Added "Open Font..." item in the menu item.
    // - View individual glyphs and save as SVG.
    // **FIXED:** Apps weren't being properly classified in the index.
    // **FIXED:** An issue with formatting the current directory name in the sidebar header.
    // **IMPROVED:** Refreshed UI colors and icons; added icons for more file types.
    // **IMPROVED:** Many styling adjustments, including setting numbers (for sizes and date, etc.) to tabular spacing.
    // **CHANGED:** Renamed "shortcuts" user setting to "bookmarks"; if you use exported settings, you'll have to change this in your code.
    // **INTERNALS:** Prettified and modularized some code. Removed some newly-unnecessary functions. Began to prune CSS.
    // - Updated markdown-it to 9.1.0.

    // ***** GENERAL SETUP ***** //

	// ************************************ //
	// DON'T EDIT ANYTHING BELOW THIS LINE. //
	// ************************************ //

    // PATHS
	// Fix "%" error in file name; see https://stackoverflow.com/questions/7449588/why-does-decodeuricomponent-lock-up-my-browser
 	function decodeURIComponentSafe(s) {
 		if ( !s ) { return s; }
        return decodeURIComponent(s.replace(/%(?![0-9a-fA-F]{2})/g, '%25') ); // replace % with %25 if not followed by two a-f/number
 	}
    const $protocol = window.location.protocol;
	const $origin = $protocol +'//'+ window.location.host;
	const $location = decodeURIComponentSafe( [location.protocol, '//', location.host, location.pathname].join('') );
	const $current_dir_path = $location.replace(/([\/|_|—])/g,'$1<wbr>').replace(/\\/g,'/'); // URL w/o query string for display

    function escapeStr(str) { str = str.replace(/([\^\$\|\?\*\+\(\)\[])/g,'\$1'); }

	// if URL is a file, change window location to parent dir, add querystring of file name; then autoload file.
	function loadFile() {
		if ( $location.slice($location.lastIndexOf('/')).indexOf('.') !== -1 && !$location.endsWith('/') && window.top === window.self ) {
			let $query_prefs = getQueryPrefs();
			$query_prefs.set( 'file', $location.slice($location.lastIndexOf('/') + 1) );
			window.location = $location.slice(0,$location.lastIndexOf('/') + 1) +'?'+ $query_prefs;
			return;
		}
	}
	loadFile();

	// QUERY PREFS
	function getQueryPrefs() { return new URL(window.location).searchParams; }
    // const initialQueryPrefs = getQueryPrefs();
	// set query key/value
	function setQuery(key, value) {
		let $query_prefs = getQueryPrefs();
		$query_prefs.set( key, value );
		updateQuery($query_prefs);
	}
	// get query value
	function getQuery(key) {
		let $query_prefs = getQueryPrefs();
		let value = '';
		if ( key === 'width' ) {
			value = ( !$query_prefs.has(key) ? 30 : Math.round(100 * Number.parseInt($query_prefs.get('width'))/window.innerWidth) ); // number string
		} else {
			value = ( $query_prefs.has(key) ? $query_prefs.get(key) : $settings[key] !== undefined ? $settings[key].toString() : '' );
            value = value.replace('%2F','').replace('/',''); // some servers add a '/' to end of query string
		}
		return value;
	}
	// toggle query key
	function toggleQuery(key) {
		let $query_prefs = getQueryPrefs();
		let nonBoolPrefs = {
			'theme_light':     {'theme':'dark'},
			'theme_dark':      {'theme':'light'},
			'source_text':     {'default_text_view':'preview_text'},
			'preview_text':    {'default_text_view':'source_text'},
			'sort_by_default': {'sort_by':'default'},
			'sort_by_name':    {'sort_by':'name'},
			'sort_by_size':    {'sort_by':'size'},
			'sort_by_date':    {'sort_by':'date'},
			'sort_by_kind':    {'sort_by':'kind'},
			'sort_by_ext':     {'sort_by':'ext'}
		};
		var value, queryValue, settingsValue;
		if ( nonBoolPrefs[key] !== undefined ) {
			value = Object.values(nonBoolPrefs[key]).toString();
			key = Object.keys(nonBoolPrefs[key]).toString(); // must come after value: i.e., don't redefine key before getting value
			if ( $settings[key] === value ) { $query_prefs.delete( key ); } else { $query_prefs.set( key, value ); }
		} else {
			queryValue = $query_prefs.get(key);
			settingsValue = $settings[key];
			value = ( queryValue === null ? settingsValue.toString() : queryValue.toString() );
			value = ( value === 'true' ? 'false' : 'true' );
			if ( ( queryValue !== null && queryValue !== settingsValue ) ) {
				$query_prefs.delete( key );
			} else {
				$query_prefs.set( key, value );
			}
		}
		updateQuery($query_prefs);
	}
	// remove query key
	function removeQuery(key) {
		let $query_prefs = getQueryPrefs();
		$query_prefs.delete(key);
		updateQuery($query_prefs);
	}
	// update query string
	function updateQuery(querystr) {
        querystr = querystr.toString().replace('%2F','').replace('/','');
		window.history.replaceState({}, document.title, window.location.pathname +'?'+ querystr);
		updateParentLinks();
	}

	// ***** SET UP UI ELEMENTS ***** //

	// SIDEBAR ELEMENTS
	// ***** BUILD MENUS ***** //
	// Parent and Parents Menus
	function updateQueryStr(str) {
		str = str.replace(/([^\?]*)selected=[^&]*(.*)$/m,'$1$2') // delete current selected query, if any
			.replace(/([^\?]*)history=(\d+)\+*([^&]*)(&*)(.*)/m,'$1$4$5&selected=$2&history=$3').replace(/&{2,}/g,'&').replace(/\?&/m,'\?'); // format query with selected and history at end
		if ( str.endsWith('&history=') ) { str = str.replace(/(.+)&history=$/m,'$1'); } // if no history, delete query
		return str;
	}
    // create links
	function createParentLinks() {
		let $links = [];
		let str = decodeURIComponentSafe(window.location.search);
            str = str.replace('/','').replace('%2F','');
		let $linkPieces = $location.split('/');
   		    $linkPieces = $linkPieces.slice(2,-2); // remove beginning and ending empty elements and current directory
		while ( $linkPieces.length > 0 ) { // while there are link pieces...
			str = updateQueryStr(str); // update selected and history
			let link = $protocol +'//'+ $linkPieces.join('/') +'/'+ str; // assemble link
			$links.push(link); // add to link array
			$linkPieces.pop(); // remove last link piece and repeat...
		}
		return $links;
	}
    // create menu items
	function createParentLinkItems() {
		let $parent_link_menu_items = [];
		let $links = createParentLinks();
        $('#parent_dir_menu').find('a').attr( 'href', $links[0] ); // set parent link
		for ( let i = 0; i < $links.length; i++ ) {
            let display_name = $links[i].slice(0,$links[i].lastIndexOf('?') - 1);
                display_name = display_name.replace(/\//g,'\/<wbr>');
			let menu_item = '<li><a href="'+ $links[i] +'">' + display_name + '/</a></li>';
			$parent_link_menu_items.push(menu_item);
		}
		return $parent_link_menu_items; // return parents link items
	}
	function updateParentLinks() { $('#parents_dir_menu').siblings('ul').empty().append( createParentLinkItems() ); }

	// MENUS: User bookmarks
	function bookmarksMenuItems() {
		const $bookmarks = $settings.bookmarks;
          let menu_items = [];
          let $links_arr = [];
          let $links_arr_str = '';
          let $links;
        if ( $bookmarks.length > 0 ) {
			for ( let i = 0; i < $bookmarks.length; i+=1 ) {
				$links = $bookmarks[i].links;
				// make array of links
				for ( let j = 0; j < $links.length; j+=1 ) {
					if ( !$links[j].link.endsWith('/') ) {
						$links[j].link = $links[j].link.slice(0,$links[j].link.lastIndexOf('/') + 1) + '?file=' + $links[j].link.slice($links[j].link.lastIndexOf('/') + 1) ;
					}
                    $links[j].link_name = $links[j].link_name.split('/').join('/<wbr>');
					$links_arr[j] = '<li><a href="'+ $links[j].link +'">' + $links[j].link_name + '</a></li>';
				}
				$links_arr_str = $links_arr.join('');
				menu_items[i] = '<li class="bookmarks has_submenu"><a>'+ $bookmarks[i].menu_title +'</a><ul>'+ $links_arr_str +'</ul></li>';
			}
			menu_items = menu_items.join('');
		}
		return menu_items;
	}
	// MENUS: Other menu items
    const MenuItems = function() {
           let sort_by =              '<li class="has_submenu rule" id="sort_by"><span>Sort by&hellip;</span><ul id="sort_menu"><li id="name"><span>Name</span></li><li id="size"><span>Size</span></li><li id="date"><span>Date</span></li><li id="kind"><span>Kind</span></li><li id="ext"><span>Extension</span></li><li id="default"><span>Default</span></li></ul>';
           let autoload_media =       '<li class="toggle_UI_pref rule" id="autoload_media"><span id="autoload_media_menu">Autoload Media</span></li>';
           let theme =                '<li><span id="theme" class="toggle_UI_pref"><span id="theme_dark">Dark Theme</span><span id="theme_light">Light Theme</span></span></li>';
           let alternate_background = '<li class="toggle_UI_pref" id="alternate_background"><span>Alternate Backgrounds</span></li>';
           let show_numbers =         '<li class="toggle_UI_pref rule" id="show_numbers"><span>Show Numbers</span></li>';
           let text_editing =         '<li class="has_submenu" id="text_editing"><span>Text Editing</span><ul id="text_editing_menu"><li id="text_editor_menu_item" class="rule"><span id="text_editor">Toggle Text Editor</span></li><li id="split_view" class="toggle_UI_pref rule"><span id="toggle_split_view">Split View</span></li><li id="preview_text_menu_item"><span class="toggle_UI_pref" id="source_text">Source Text</span><span class="toggle_UI_pref" id="preview_text">Preview Text</span></li></ul>';
           let disable_text_editing = '<li class="rule"><span class="toggle_UI_pref" id="enable_text_editing">Disable Text Editing</span></li>';
           let open_playlist =        '<li class="rule"><label id="open_playlist_label" for="open_playlist">Open Playlist&hellip;</label><input type="file" id="open_playlist" name="open_playlist" accept=".m3u,.m3u8"></input></li>';
           let open_font =            '<li class="rule"><label id="open_font_label" for="open_font">Open Font&hellip;</label><input type="file" id="open_font" name="open_font" accept=".otf,.ttf,.woff"></input></li>';
           let default_settings =     '<li><a href="#" id="default_settings" title="Delete URL query string and reload page.">Default User Settings</a></li>';
           let export_settings =      '<li class="rule"><a href="#" id="export_settings" title="Export user settings to text file.">Export User Settings</a></li>';
           let contact_link =         '<li><a id="contact" href="mailto:mshroud@vivaldi.net">Contact</a></li>';
           let donate_link =          '<li><a id="donate" href="https://paypal.me/mschrauzer" target="_blank" rel="noopener">Donate</a></li>';
        return sort_by + theme + alternate_background + show_numbers + autoload_media + text_editing + disable_text_editing + open_playlist + open_font + default_settings + export_settings + contact_link + donate_link;
    };
    const SidebarHeaderEls = function() {
           let parent_link_items =    createParentLinkItems();
           let parent_link =          $(parent_link_items[0]).find('a').attr('href');
               parent_link_items =    parent_link_items.toString().replace(/<\/li>,<li>/g,'</li><li>');
           let parent_dir_menu =     '<nav id="parent_dir_menu"><a href="'+ parent_link +'">&nbsp;</a></nav>';
           let parents_dir_menu =    '<nav id="parents_dir_menu"><div>'+ $current_dir_path +'</div></nav><ul class="menu">'+ parent_link_items +'</ul>';
           let bookmarks_menu =      '<nav id="bookmarks_menu"><div>&nbsp;</div></nav><ul id="bookmarks" class="menu">'+ bookmarksMenuItems() + MenuItems() +'</ul>';
           let show_details =        '<button class="toggle_UI_pref" id="show_details" tabindex="-1"><span>Show details</span><span>Hide details</span></button>';
           let inv_checkbox =        '<label><input class="toggle_UI_pref" type="checkbox" id="show_invisibles" for="inv_checkbox" name="inv_checkbox" tabindex="-1" />Show Invisibles</label>';
           let grid_btn =            '<td id="grid_btn" tabindex="-1" title="Show Grid"><ul class="menu"><li id="show_image_grid">Show Image Grid</li><li id="show_font_grid">Show Font Grid</li></ul></td>';
           let sorting =             '<tr class="header"><th id="sorting" colspan="4"><div><div class="toggle_UI_pref name sorting" id="sort_by_name" colspan="2"><span><input id="play_toggle" type="checkbox" tabindex="-1" checked="true" />Name</span></div><div class="toggle_UI_pref sorting" id="sort_by_default" colspan="2"><span>Default</span></div><div class="toggle_UI_pref details sorting" id="sort_by_size"><span>Size</span></div><div class="toggle_UI_pref details sorting" id="sort_by_date"><span>Date</span></div><div class="toggle_UI_pref details sorting" id="sort_by_kind"><span>Kind</span></div><div class="toggle_UI_pref details sorting" id="sort_by_ext"><span>Ext</span></div></div></th></tr>';
           let text_editor_row =     '<tr id="text_editor_row"><th colspan="4"><a href="#" title="Toggle Text Editor">Text Editor</a></th></tr>';
           let sidebar_header =      '<table id="sidebar_header"><thead><tr id="sidebar_title"><th colspan="4"></th></tr></thead><tbody><tr id="sidebar_menus"><td>'+ parent_dir_menu +'</td><td colspan="2">'+ parents_dir_menu +'</td><td id="bookmarks_menu_container">'+ bookmarks_menu +'</td></tr><tr id="sidebar_buttons"><td colspan="3">'+ show_details + inv_checkbox +'</td>'+ grid_btn +'</tr>'+ sorting + text_editor_row +'</tbody></table>';
           let sidebar_header_els =   sidebar_header;
        return sidebar_header_els;
    };
    // Dir List Elements
    const SidebarDirListEls = function() {
           let dir_list_body =       '<tbody id="tbody"></tbody>';
           let dir_list_foot =       '<tfoot id="tfoot"><tr id="index_stats"><td id="stats"></td><td id="toggle_info" data-kind="info" title="View current directory index source">&nbsp;</td></tr></tfoot>';
           let sidebar_dir_list_els = '<table id="dir_list">'+ dir_list_body + dir_list_foot +'</table>';
        return sidebar_dir_list_els;
    };
    // CONTENT PANE ELEMENTS
    const ContentHeaderEls = function() {
           let title_buttons_left =  '<td id="title_buttons_left"><button id="reload_btn" tabindex="-1"><span>Reload</span></button><button id="prev_next_btns" class="split_btn"><span id="prev_btn"><span>&nbsp;</span></span><span id="next_btn"><span>&nbsp;</span></span></button></td>';
           let title =               '<td id="title"><span></span></td>';
           let title_buttons_right = '<td id="title_buttons_right"><button id="scale" class="split_btn"><span id="decrease">&nbsp;</span><span id="increase">&nbsp;</span></button><button id="close_btn" tabindex="-1"><span>Close</span></button></td>';
           let content_title =       '<tr id="content_title">'+ title_buttons_left + title + title_buttons_right +'</tr>';
           let content_header_els =  '<header id="content_header"><table><tbody>'+ content_title + ContentAudioEls() +'</tbody></table></header>';
        return content_header_els;
    };
    // Content containers
    const ContentEls = function() {
           let content_grid =        '<div id="content_grid" data-grid-scale-factor="1" data-kind="grid"></div>';
           let content_text =        '<div id="content_text"></div>';
           let content_font =        '<div id="content_font" class="content" spellcheck="false" data-kind="font">'+ ContentFontEls() +'</div>';
           let content_image =       '<div id="content_image" class="content" data-kind="image"><img /></div>';
           let content_video =       '<video id="content_video" class="content media" controls data-kind="video">Your browser does not support the video tag.</video>';
           let content_pdf =         '<embed id="content_pdf" class="content" name="plugin" tabindex="0" data-kind="pdf"></embed>';
           let content_iframe =      '<iframe id="content_iframe" class="content" name="content_iframe" sandbox="allow-scripts allow-same-origin allow-modals" tabindex="0" data-kind="file"></iframe>';
           let content_els =         '<section id="content_container">'+ content_grid + content_text + content_font + content_image + content_pdf + content_video + content_iframe +'</section>';
        return content_els;
    };
    // Content Audio Els
    const ContentAudioEls = function() {
           let prev_track =          '<div id="prev_track" class="prev_next_track_btn" title="Previous track">&nbsp;</div>';
           let next_track =          '<div id="next_track" class="prev_next_track_btn" title="Next track">&nbsp;</div>';
           let audio_player =        '<audio id="audio" preload="auto" tabindex="0" controls >Sorry, your browser does not support HTML5 audio.</audio>';
           let loop =                '<label><input type="checkbox" id="loop" for="loop" name="loop" tabindex="0" />Loop</label>';
           let shuffle =             '<label><input type="checkbox" id="shuffle" for="shuffle" name="shuffle" tabindex="0" />Shuffle</label>';
           let checkbox_cont =       '<div id="checkbox_div">'+ loop + shuffle +'</div>';
           let close_audio =         '<div id="close_audio" title="Close audio"></div>';
           let content_audio_title = '<tr id="content_audio_title"><td colspan="3"></td></tr>';
           let content_audio_els =    content_audio_title +'<tr id="content_audio"><td colspan="3"><div id="audio_container">'+ prev_track + next_track + audio_player + close_audio +'</div>'+ checkbox_cont +'</td></tr>';
        return content_audio_els;
    };
    // Content Font Els
    const ContentFontEls = function() {
           let sample_string =       'ABCDEFGHIJKLMNOPQRSTUVWXYZ<br />abcdefghijklmnopqrstuvwxyz<br />0123456789 [(!@#$%^&*;:)]';
           let specimen =            '<div class="specimen" contenteditable="true" style="font-size:4em;word-break: break-all;line-height: 1.2;">'+ sample_string +'</div>';
           let hamburger_string =    '<h1 style="font-size:8em">Typography</h1><h4 style="font-size:1.618em">The art of using types to produce impressions on paper, vellum, &amp;c.</h4><h2 style="font-size:6em;text-align:justify;">S P E C I M E N</h2><h3 style="font-size:2em">Typography is the work of typesetters (also known as compositors), typographers, graphic designers, art directors, manga artists, comic book artists, graffiti artists, and, now, anyone who arranges words, letters, numbers, and symbols for publication, display, or distribution.</h3>';
           let lorem_string =        'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
           let lorem =               '<div class="lorem" style="text-align:justify;font-size:1em;line-height: 1.4;column-gap:1.5em;overflow-wrap: normal;word-break: normal;" contenteditable="true">'+ lorem_string +'</div>';
           let lorem2 =              lorem.replace('style="','style="columns:2;');
           let lorem3 =              lorem.replace('style="','style="columns:3;');
           let hamburger =           '<div class="hamburger" style="text-align:justify" contenteditable="true">'+ hamburger_string +'</div>'+ lorem + lorem2 + lorem3 +'</div>';
           let font_specimen =       '<div id="font_specimen">'+ specimen + hamburger + ContentFontViewer() +'</div>';
        return font_specimen;
    };
    const ContentFontViewer = function() {
        let glyphs_container =    '<div id="glyphs_container"></div>';
        let glyph_viewer =        '<div id="glyph_viewer"><div id="glyph_viewer_info" style="height:18px;line-height:1.6;"><button id="save_svg_hidden" style="visibility:hidden;float:left;">Save SVG</button><div></div><button id="save_svg" style="float:right;">Save SVG</button></div></div>';
        let font_viewer =         '<div id="font_viewer" style="font-family:unset">'+ glyphs_container + glyph_viewer +'</div>';
        return font_viewer;
    }
    // ASSEMBLE SIBEBAR & CONTENT PANE ELEMENTS
    const MainContent = function() {
           let handle =              '<div id="handle"></div>';
           let toggle_sidebar =      '<div id="toggle_sidebar"></div>';
           let warnings =            '<div id="warnings"><h3>Warning:</h3><p id="warning_unsaved">You have unsaved changes.</p><p id="warning_clear">Are you sure you want to clear all your text?</p><p id="warning_local">Can\'t load local directories or files from non-local web pages. Use your browser\'s bookmarks or enter the URL manually.</p><div><button id="warning_ignore_btn">Don\'t Save</button><button id="warning_cancel_btn" >Cancel</button><button id="warning_clear_btn">Clear</button><button id="warning_save_btn">Save</button><button id="warning_ok_btn">OK</button></div></div>';
           let overlay =             '<div id="overlay"></div>';
           let sidebar =             '<div id="sidebar">'+ SidebarHeaderEls() + SidebarDirListEls() +'</div>';
           let sidebar_wrapper =     '<td id="sidebar_wrapper">'+ sidebar + handle + toggle_sidebar +'</td>';
           let content_pane =        '<td id="content_pane" class="">'+ ContentHeaderEls() + ContentEls() +'</td>';

           let main_head =           '<thead><tr><th>'+ warnings + overlay +'</th></tr></thead>';
           let main_body =           '<tbody><tr>'+ sidebar_wrapper + content_pane +'</tr></tbody>';
           let main_foot =           '<tfoot></tfoot>';
           let main_content =        '<table id="main_content">'+ main_head + main_body + main_foot +'</table>';
        return $(main_content);
    };
    // DEFINE Content Elements
    const $main_content = MainContent();
    // DIR LIST
    const $dir_list_body =        $main_content.find('#tbody');
    const $dir_list =             $main_content.find('#dir_list');
    // CONTENT
    const $content_pane =         $main_content.find('#content_pane');
    const $audio_player =         $main_content.find('#audio');
    const $content_text =         $main_content.find('#content_text');
    const $content_grid =         $main_content.find('#content_grid');
    const $content_font =         $main_content.find('#content_font');
    const $content_image =        $main_content.find('#content_image');
    const $content_pdf =          $main_content.find('#content_pdf');
    const $content_video =        $main_content.find('#content_video');
    const $content_iframe =       $main_content.find('#content_iframe');

	// SVG UI ICONS
    function SVG_UI_Icon(icon_name) {
        let svg = '';
        if ( icon_name.endsWith('_dark') ) {
            icon_name = icon_name.slice(0,-5);
            svg = SVG_UI_Icons[icon_name];
            svg = svg.replace(/4{6}/g,'BBBBBB');
        } else {
            svg = SVG_UI_Icons[icon_name];
        }
        return 'url("data:image/svg+xml;utf8,'+ svg +'")';
    }
    const SVG_UI_Icons = {
        'arrow':                   '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M4 4l12 6-12 6z\' /></svg>',
        'bookmark':                '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M2 2c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v18l-8-4-8 4V2zm2 0v15l6-3 6 3V2H4z\' /></svg>',
        'check_mark':              '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 12 09\'><g transform=\'matrix(0.55,5.55112e-17,-5.55112e-17,0.55,0.578932,-1.01245)\'><path d=\'M-0.071,10.929L2.5,8.358L7,12.857L17.285,2.572L19.856,5.144L7,18L-0.071,10.929Z\' style=\'fill:rgb(68,68,68);fill-rule:nonzero;\'/></g></svg>',
        'chevron_up':              '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 12 08\'><g transform=\'matrix(1,0,0,1,-3.843,-5.843)\'><path d=\'M10.707,7.05L10,6.343L4.343,12L5.757,13.414L10,9.172L14.243,13.414L15.657,12L10.707,7.05Z\' style=\'fill:rgb(68,68,68);fill-rule:nonzero;\'/></g></svg>',
        'chevron_right':           '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 08 12\'><g transform=\'matrix(1,0,0,1,-6.086,-4)\'><path d=\'M12.95,10.707L13.657,10L8,4.343L6.586,5.757L10.828,10L6.586,14.243L8,15.657L12.95,10.707Z\' style=\'fill:rgb(68,68,68);fill-rule:nonzero;\'/></g></svg>',
        'chevron_down':            '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 12 08\'><g transform=\'matrix(1,0,0,1,-4,-6.157)\'><path d=\'M9.293,12.95L10,13.657L15.657,8L14.243,6.586L10,10.828L5.757,6.586L4.343,8L9.293,12.95Z\' style=\'fill:rgb(68,68,68);fill-rule:nonzero;\'/></g></svg>',
        'chevron_left':            '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 08 12\'><g transform=\'matrix(1,0,0,1,-5.843,-4)\'><path d=\'M7.05,9.293L6.343,10L12,15.657L13.414,14.243L9.172,10L13.414,5.757L12,4.343L7.05,9.293Z\' style=\'fill:rgb(68,68,68);fill-rule:nonzero;\'/></g></svg>',
        'document':                '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M4 18h12V6h-4V2H4v16zm-2 1V0h12l4 4v16H2v-1z\' /></svg>',
        'error':                   '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23FFB636\' id=\'Layer_2\' d=\'M1.075,18.05l8.146,-16.683c0.236,-0.484 0.924,-0.491 1.169,-0.011l8.537,16.683c0.223,0.435 -0.093,0.952 -0.582,0.952l-16.683,0c-0.483,0 -0.799,-0.507 -0.587,-0.941Z\' style=\'fill-opacity:0.75;fill-rule:nonzero;\'/><path id=\'Layer_3\' d=\'M11.055,7.131l-0.447,6.003c-0.034,0.45 -0.425,0.787 -0.874,0.753c-0.408,-0.03 -0.724,-0.356 -0.753,-0.753l-0.447,-6.003c-0.052,-0.696 0.47,-1.302 1.167,-1.354c0.696,-0.052 1.302,0.47 1.354,1.166c0.005,0.061 0.004,0.129 0,0.188Zm-1.26,8.037c-0.641,0 -1.159,0.518 -1.159,1.158c0,0.641 0.518,1.159 1.159,1.159c0.64,0 1.158,-0.518 1.158,-1.159c0,-0.64 -0.518,-1.158 -1.158,-1.158Z\' style=\'fill:%23444;fill-opacity:0.75;fill-rule:nonzero;\'/></svg>',
        'folder':                  '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M0 4c0-1.1.9-2 2-2h7l2 2h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V4zm2 2v10h16V6H2z\' /></svg>',
        'grid':                    '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M0 0h9v9H0V0zm2 2v5h5V2H2zm-2 9h9v9H0v-9zm2 2v5h5v-5H2zm9-13h9v9h-9V0zm2 2v5h5V2h-5zm-2 9h9v9h-9v-9zm2 2v5h5v-5h-5z\' /></svg>',
        'grid_loaded':             '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23118888\' d=\'M0 0h9v9H0V0zm2 2v5h5V2H2zm-2 9h9v9H0v-9zm2 2v5h5v-5H2zm9-13h9v9h-9V0zm2 2v5h5V2h-5zm-2 9h9v9h-9v-9zm2 2v5h5v-5h-5z\' /></svg>',
        'grid_loaded_dark':        '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23AA4444\' d=\'M0 0h9v9H0V0zm2 2v5h5V2H2zm-2 9h9v9H0v-9zm2 2v5h5v-5H2zm9-13h9v9h-9V0zm2 2v5h5V2h-5zm-2 9h9v9h-9v-9zm2 2v5h5v-5h-5z\' /></svg>',
        'ignored':                 '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M0 10a10 10 0 1 1 20 0 10 10 0 0 1-20 0zm16.32-4.9L5.09 16.31A8 8 0 0 0 16.32 5.09zm-1.41-1.42A8 8 0 0 0 3.68 14.91L14.91 3.68z\' opacity=\'0.25\' /></svg>',
        'menu':                    '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z\' /></svg>',
        'minus':                   '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><rect fill=\'%23444444\' x=\'1\' y=\'8\' width=\'18\' height=\'4\' /></svg>',
        'multiply':                '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M10,7l6,-6l3,3l-6,6l6,6l-3,3l-6,-6l-6,6l-3,-3l6,-6l-6,-6l3,-3l6,6Z\'/></svg>',
        'music':                   '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23888888\' d=\'M15.987,13.982c0,0.906 -0.413,1.664 -1.239,2.274c-0.757,0.554 -1.604,0.831 -2.541,0.831c-0.548,0 -0.998,-0.129 -1.348,-0.388c-0.389,-0.295 -0.583,-0.708 -0.583,-1.238c0,-0.838 0.398,-1.574 1.192,-2.209c0.752,-0.597 1.559,-0.896 2.421,-0.896c0.727,0 1.257,0.145 1.59,0.434l0,-9.489l-6.755,1.82l0,10.774c0,0.906 -0.413,1.663 -1.238,2.273c-0.758,0.555 -1.605,0.832 -2.541,0.832c-0.549,0 -0.998,-0.13 -1.35,-0.388c-0.388,-0.296 -0.582,-0.709 -0.582,-1.238c0,-0.838 0.398,-1.574 1.192,-2.209c0.752,-0.597 1.559,-0.896 2.421,-0.896c0.727,0 1.257,0.145 1.589,0.434l0,-11.605l7.772,-2.098l0,12.982Z\' style=\'fill-opacity:0.4;fill-rule:nonzero;\'/></svg>',
        'plus':                    '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M8.001,1l3.999,0l0,7l7,0l0,4l-7,0l-0.001,7l-3.999,0l0,-7l-7,0l0,-4l7,0l0.001,-7Z\'/></svg>',
        'prev_next_track':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M13,5l2,0l0,10l-2,0l0,-10Zm-8,0l8,5l-8,5l0,-10Z\'/></svg>',
        'prev_next_track_ff':      '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23FFFFFF\' d=\'M12.8,14l-10.8,-7l10.8,-7l0,14Z\'\'/><rect x=\'0\' y=\'0\' width=\'2\' height=\'14\' style=\'fill:%23fff;\'/></svg>',
        'spinner':                 '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 40 40\'><g><g transform=\'translate(1 1)\'><circle style=\'fill:none;stroke:%23666666;stroke-width:4;stroke-opacity:0.5;\' cx=\'18\' cy=\'18\' r=\'18\'/><path style=\'fill:none;stroke:%23AAAAAA;stroke-width:4;\' d=\'M36,18c0-9.94-8.061-18-18-18 \'><animateTransform type=\'rotate\' fill=\'remove\' repeatCount=\'indefinite\' attributeName=\'transform\' restart=\'always\' dur=\'1s\' from=\'0 18 18\' calcMode=\'linear\' to=\'360 18 18\' accumulate=\'none\' additive=\'replace\'></animateTransform></path></g></g></svg>',
        'toggle':                  '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 20 20\'><path fill=\'%23444444\' d=\'M10.207,9.293l-0.707,0.707l5.657,5.657l1.414,-1.414l-4.242,-4.243l4.242,-4.243l-1.414,-1.414l-4.95,4.95Z\' /><path fill=\'%23444444\' d=\'M4.207,9.293l-0.707,0.707l5.657,5.657l1.414,-1.414l-4.242,-4.243l4.242,-4.243l-1.414,-1.414l-4.95,4.95Z\'/></svg>',
    };

    function SVG_UI_File_Icon(icon_name) {
        if ( icon_name === 'file_icon_dir_default' ) { // default chrome icons
            return 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAd5JREFUeNqMU79rFUEQ/vbuodFEEkzAImBpkUabFP4ldpaJhZXYm/RiZWsv/hkWFglBUyTIgyAIIfgIRjHv3r39MePM7N3LcbxAFvZ2b2bn22/mm3XMjF+HL3YW7q28YSIw8mBKoBihhhgCsoORot9d3/ywg3YowMXwNde/PzGnk2vn6PitrT+/PGeNaecg4+qNY3D43vy16A5wDDd4Aqg/ngmrjl/GoN0U5V1QquHQG3q+TPDVhVwyBffcmQGJmSVfyZk7R3SngI4JKfwDJ2+05zIg8gbiereTZRHhJ5KCMOwDFLjhoBTn2g0ghagfKeIYJDPFyibJVBtTREwq60SpYvh5++PpwatHsxSm9QRLSQpEVSd7/TYJUb49TX7gztpjjEffnoVw66+Ytovs14Yp7HaKmUXeX9rKUoMoLNW3srqI5fWn8JejrVkK0QcrkFLOgS39yoKUQe292WJ1guUHG8K2o8K00oO1BTvXoW4yasclUTgZYJY9aFNfAThX5CZRmczAV52oAPoupHhWRIUUAOoyUIlYVaAa/VbLbyiZUiyFbjQFNwiZQSGl4IDy9sO5Wrty0QLKhdZPxmgGcDo8ejn+c/6eiK9poz15Kw7Dr/vN/z6W7q++091/AQYA5mZ8GYJ9K0AAAAAASUVORK5CYII= ")';
        } else if ( icon_name === 'file_icon_file_default' ) {
            return 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABnRSTlMAAAAAAABupgeRAAABHUlEQVR42o2RMW7DIBiF3498iHRJD5JKHurL+CRVBp+i2T16tTynF2gO0KSb5ZrBBl4HHDBuK/WXACH4eO9/CAAAbdvijzLGNE1TVZXfZuHg6XCAQESAZXbOKaXO57eiKG6ft9PrKQIkCQqFoIiQFBGlFIB5nvM8t9aOX2Nd18oDzjnPgCDpn/BH4zh2XZdlWVmWiUK4IgCBoFMUz9eP6zRN75cLgEQhcmTQIbl72O0f9865qLAAsURAAgKBJKEtgLXWvyjLuFsThCSstb8rBCaAQhDYWgIZ7myM+TUBjDHrHlZcbMYYk34cN0YSLcgS+wL0fe9TXDMbY33fR2AYBvyQ8L0Gk8MwREBrTfKe4TpTzwhArXWi8HI84h/1DfwI5mhxJamFAAAAAElFTkSuQmCC ")';
        } else { // custom icons
            return 'url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons[icon_name] +'")';
        }
    }
    const SVG_UI_File_Icons = {
        'file_icon_alias':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23808080;fill-rule:nonzero;\'/><path d=\'M3,12.5c0,-3.863 2.253,-7.5 6.259,-7.5\' style=\'fill:none;stroke:%23fc6;stroke-width:3px;\'/><path d=\'M13,5l-4,-4l0,8l4,-4Z\' style=\'fill:%23fc6;\'/></svg>',
        'file_icon_archive':       '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M11,8.5l0,-1l2,0l0,2l-5,1l-2,0l0,1.5l4,0l0,1l-4,0l0,1l-3,0l0,-1l-2,0l0,-1l2,0l0,-1.5l-2,0l0,-2l2,0l0,-6.5l-2,0l0,-2l7,0l5,1l0,2l-2,0l0,-1l-5,0l0,6.5l5,0Z\' style=\'fill:%23999;\'/></svg>',
        'file_icon_app':           '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path id=\'rect6894\' d=\'M6.125,0l-0.292,1.859c-0.587,0.135 -1.146,0.38 -1.64,0.693l0,-0.018l-1.532,-1.094l-1.221,1.221l1.094,1.532l0.018,0c-0.313,0.495 -0.559,1.051 -0.693,1.64l-1.859,0.292l0,1.75l1.859,0.292c0.134,0.589 0.38,1.145 0.693,1.64l-0.018,0l-1.094,1.532l1.221,1.221l1.532,-1.094l0,-0.018c0.494,0.313 1.053,0.558 1.64,0.693l0.292,1.859l1.75,0l0.292,-1.859c0.596,-0.137 1.14,-0.372 1.64,-0.693l1.532,1.112l1.221,-1.221l-1.112,-1.532c0.309,-0.492 0.523,-1.057 0.656,-1.64l1.896,-0.292l0,-1.75l-1.896,-0.292c-0.133,-0.583 -0.347,-1.148 -0.656,-1.64l0.018,0l1.094,-1.532l-1.221,-1.221l-1.532,1.094l0,0.018c-0.5,-0.321 -1.044,-0.556 -1.64,-0.693l-0.292,-1.859l-1.75,0Zm0.875,4.667c1.288,0 2.333,1.036 2.333,2.333c0,1.297 -1.045,2.333 -2.333,2.333c-1.288,0 -2.333,-1.036 -2.333,-2.333c0,-1.297 1.045,-2.333 2.333,-2.333Z\' style=\'fill:%237a7ab8;\'/></svg>',
        'file_icon_audio':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><g id=\'Layer1\'><circle cx=\'7\' cy=\'7\' r=\'7\' style=\'fill:%230f8a8a;\'/></g><path d=\'M11,9.5l0,0c-0.019,0.681 -0.796,1.339 -1.75,1.475c-0.966,0.138 -1.75,-0.31 -1.75,-1c0,-0.69 0.784,-1.362 1.75,-1.5c0.268,-0.038 0.523,-0.031 0.75,0.013l0,-4.488l-4,0l0,6.5l0,0c-0.019,0.681 -0.796,1.339 -1.75,1.475c-0.966,0.138 -1.75,-0.31 -1.75,-1c0,-0.69 0.784,-1.362 1.75,-1.5c0.268,-0.038 0.523,-0.031 0.75,0.013l0,-6.488l6,-1l0,7.5Z\' style=\'fill:%23fff;\'/><path d=\'M11,2l-6,1l0,2l6,-1l0,-2Z\' style=\'fill:%23fff;\'/></svg>',
        'file_icon_binary':        '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23808080;fill-rule:nonzero;\'/><g><path d=\'M1.247,6.495l3.263,0l0,-1.067l-0.881,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.284,0.479l0,0.82l0.928,0l0,2.536l-1.052,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M7,6.588c1.082,0 1.825,-0.89 1.825,-2.567c0,-1.67 -0.743,-2.521 -1.825,-2.521c-1.082,0 -1.825,0.843 -1.825,2.521c0,1.677 0.743,2.567 1.825,2.567Zm0,-1.021c-0.309,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.263,-1.5 0.572,-1.5c0.309,0 0.572,0.201 0.572,1.5c0,1.299 -0.263,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M9.598,6.495l3.263,0l0,-1.067l-0.882,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.283,0.479l0,0.82l0.927,0l0,2.536l-1.051,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M2.825,12.588c1.082,0 1.824,-0.89 1.824,-2.567c0,-1.67 -0.742,-2.521 -1.824,-2.521c-1.083,0 -1.825,0.843 -1.825,2.521c0,1.677 0.742,2.567 1.825,2.567Zm0,-1.021c-0.31,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.262,-1.5 0.572,-1.5c0.309,0 0.572,0.201 0.572,1.5c0,1.299 -0.263,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M5.423,12.495l3.263,0l0,-1.067l-0.882,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.284,0.479l0,0.82l0.928,0l0,2.536l-1.051,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M11.175,12.588c1.083,0 1.825,-0.89 1.825,-2.567c0,-1.67 -0.742,-2.521 -1.825,-2.521c-1.082,0 -1.824,0.843 -1.824,2.521c0,1.677 0.742,2.567 1.824,2.567Zm0,-1.021c-0.309,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.263,-1.5 0.572,-1.5c0.31,0 0.572,0.201 0.572,1.5c0,1.299 -0.262,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/></g></svg>',
        'file_icon_code':          '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M14,0l-14,0l0,14l14,0l0,-14Z\' style=\'fill:%2372d;fill-rule:nonzero;\'/><g><path d=\'M5.923,12.965c-1.049,0 -1.784,-0.161 -2.209,-0.48c-0.425,-0.317 -0.638,-0.82 -0.638,-1.503l0,-2.067c0,-0.446 -0.146,-0.764 -0.438,-0.95c-0.292,-0.188 -0.709,-0.281 -1.256,-0.281l0,-1.368c0.547,0 0.967,-0.094 1.259,-0.28c0.292,-0.186 0.438,-0.5 0.438,-0.938l0,-2.092c0,-0.675 0.217,-1.172 0.65,-1.491c0.432,-0.32 1.164,-0.479 2.195,-0.479l0,1.312c-0.401,0.01 -0.718,0.09 -0.952,0.24c-0.233,0.15 -0.348,0.426 -0.348,0.827l0,1.985c0,0.876 -0.511,1.396 -1.532,1.559l0,0.083c1.021,0.154 1.532,0.67 1.532,1.544l0,1.997c0,0.41 0.116,0.688 0.349,0.835c0.233,0.146 0.55,0.223 0.951,0.232l-0.001,1.315Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/><path d=\'M8.076,12.965l0,-1.313c0.392,-0.009 0.706,-0.089 0.944,-0.239c0.236,-0.15 0.355,-0.426 0.355,-0.829l0,-1.996c0,-0.867 0.511,-1.382 1.531,-1.545l0,-0.084c-1.02,-0.164 -1.53,-0.679 -1.53,-1.546l0,-1.997c0,-0.41 -0.116,-0.688 -0.349,-0.834c-0.232,-0.146 -0.549,-0.224 -0.951,-0.233l0,-1.313c1.049,0 1.785,0.159 2.21,0.479c0.423,0.319 0.637,0.821 0.637,1.505l0,2.065c0,0.447 0.146,0.765 0.438,0.951c0.292,0.187 0.711,0.28 1.257,0.28l0,1.367c-0.546,0.012 -0.967,0.107 -1.259,0.287c-0.293,0.183 -0.438,0.5 -0.438,0.945l0,2.08c0,0.674 -0.217,1.172 -0.65,1.491c-0.432,0.319 -1.165,0.479 -2.195,0.479Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/></g></svg>',
        'file_icon_database':      '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M14,2.5l0,9c0,1.38 -3.137,2.5 -7,2.5c-3.863,0 -7,-1.12 -7,-2.5l0,-9\' style=\'fill:%23808080;\'/><path d=\'M13,2.5l0,9c0,0.828 -2.689,1.5 -6,1.5c-3.311,0 -6,-0.672 -6,-1.5l0,-9\' style=\'fill:%23b4b4b4;\'/><path d=\'M14,8.5c0,1.38 -3.137,2.5 -7,2.5c-3.863,0 -7,-1.12 -7,-2.5\' style=\'fill:%23808080;\'/><path d=\'M13,8.5c0,0.828 -2.689,1.5 -6,1.5c-3.311,0 -6,-0.672 -6,-1.5\' style=\'fill:%23b4b4b4;\'/><path d=\'M14,5.5c0,1.38 -3.137,2.5 -7,2.5c-3.863,0 -7,-1.12 -7,-2.5\' style=\'fill:%23808080;\'/><path d=\'M13,5.5c0,0.828 -2.689,1.5 -6,1.5c-3.311,0 -6,-0.672 -6,-1.5\' style=\'fill:%23b4b4b4;\'/><ellipse cx=\'7\' cy=\'2.5\' rx=\'7\' ry=\'2.5\' style=\'fill:%23808080;\'/><ellipse cx=\'7\' cy=\'2.5\' rx=\'5.5\' ry=\'1.5\' style=\'fill:%23b4b4b4;\'/></svg>',
        'file_icon_dir':           '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M6,2.5l-1,-1.5l-5,0l0,12l14,0l0,-10.5l-8,0Z\' style=\'fill:%2339f;fill-rule:nonzero;\'/><rect x=\'1.5\' y=\'4\' width=\'11\' height=\'7.5\' style=\'fill:%239cf;\'/></svg>',
        'file_icon_dir_invisible': '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M6,2.5l-1,-1.5l-5,0l0,12l14,0l0,-10.5l-8,0Z\' style=\'fill:%23888;fill-rule:nonzero;\'/><rect x=\'1.5\' y=\'4\' width=\'11\' height=\'7.5\' style=\'fill:%23bbb;\'/><circle cx=\'7\' cy=\'7.5\' r=\'1.5\' style=\'fill:%23888;\'/></svg>',
        'file_icon_ebook':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M2.668,-0.001c1.705,0.001 3.492,0.35 4.332,1.257c0.84,-0.908 2.627,-1.256 4.332,-1.257l2.668,0c0,4.112 0,8.43 0,12.541c-0.818,0 -2.181,0.005 -3,0.023c-1.184,0.026 -3.008,0.42 -3,1.437l-1,-0.017l-1,0.017c0.008,-1.017 -2,-1.437 -3,-1.437c-0.819,0 -2.182,-0.023 -3,-0.023l0,-12.541l2.668,0Z\' style=\'fill:%23808080;\'/><path d=\'M1.5,1.499l0,9.501l1.286,0c1.086,0.025 2.213,0.081 3.204,0.568l0.01,0.006c0,-2.859 0,-5.717 0,-8.576c0,-1.136 -1.49,-1.398 -2.336,-1.47c-0.708,-0.059 -1.438,-0.029 -2.164,-0.029Z\' style=\'fill:%23cdcdcd;\'/><path d=\'M12.5,1.499l0,9.501l-1.286,0c-1.086,0.025 -2.213,0.081 -3.204,0.568l-0.01,0.006c0,-2.859 0,-5.717 0,-8.576c0,-1.136 1.49,-1.398 2.336,-1.47c0.708,-0.059 1.438,-0.029 2.164,-0.029Z\' style=\'fill:%23cdcdcd;\'/></svg>',
        'file_icon_file':          '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><g><path d=\'M8.3,0l-6.8,0l0,14l11,0l0,-9.8l-4.2,-4.2Z\' style=\'fill:%23888;fill-rule:nonzero;\'/><path d=\'M11,12.5l-8,0l0,-11l3.8,0l0,4.2l4.2,0l0,6.8Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/><path d=\'M8.3,4.2l1.9,0l-1.9,-2l0,2Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/></g></svg>',
        'file_icon_invisible':     '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><g><path d=\'M8.3,0l-6.8,0l0,14l11,0l0,-9.8l-4.2,-4.2Z\' style=\'fill:%23888;fill-rule:nonzero;\'/><path d=\'M11,12.5l-8,0l0,-11l3.8,0l0,4.2l4.2,0l0,6.8Z\' style=\'fill:%23bbb;fill-rule:nonzero;\'/><path d=\'M8.3,4.2l1.9,0l-1.9,-2l0,2Z\' style=\'fill:%23bbb;fill-rule:nonzero;\'/></g><circle cx=\'7\' cy=\'9\' r=\'1.5\' style=\'fill:%23878787;\'/></svg>',
        'file_icon_font':          '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M14,0l-14,0l0,14l14,0l0,-14Z\' style=\'fill:%23709;fill-rule:nonzero;\'/><path d=\'M4.678,11.179l1.393,0l0,-8.266l-2.616,0l0,1.052l-1.455,0l0,-2.553l10,0l0,2.554l-1.456,0l0,-1.053l-2.599,0l0,8.266l1.347,0l0,1.409l-4.614,0l0,-1.409Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/></svg>',
        'file_icon_graphics':      '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23808080;fill-rule:nonzero;\'/><path d=\'M7.774,8.285l4.726,4.715l-8,-3.525l-1.5,-4.975l-2,0l0,-3.5l3.525,0l-0.025,2l5,1.5l3.5,8l-4.7,-4.752c0.127,-0.22 0.2,-0.476 0.2,-0.748c0,-0.828 -0.672,-1.5 -1.5,-1.5c-0.828,0 -1.5,0.672 -1.5,1.5c0,0.828 0.672,1.5 1.5,1.5c0.283,0 0.548,-0.079 0.774,-0.215Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/></svg>',
        'file_icon_htm':           '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M6.967,0.5c-3.553,0.018 -6.467,2.947 -6.467,6.5c0,3.566 2.934,6.5 6.5,6.5c3.566,0 6.5,-2.934 6.5,-6.5c0,-3.553 -2.914,-6.482 -6.467,-6.5l-0.066,0Zm0.033,0l0,13m6.5,-6.5l-13,0m1.467,-4c3.004,2.143 7.062,2.143 10.066,0m0,8c-3.004,-2.143 -7.062,-2.143 -10.066,0m4.533,-10.333c-1.874,1.582 -2.957,3.914 -2.957,6.366c0,2.453 1.083,4.785 2.957,6.367m1,0c1.874,-1.582 2.957,-3.914 2.957,-6.367c0,-2.452 -1.083,-4.784 -2.957,-6.366\' style=\'fill:%23fff;fill-rule:nonzero;stroke:%23E44D26;stroke-width:1px;\'/></svg>',
        'file_icon_ignored':       '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M7,0c-3.9,0 -7,3.1 -7,7c0,3.9 3.1,7 7,7c3.9,0 7,-3.1 7,-7c0,-3.9 -3.1,-7 -7,-7Z\' style=\'fill:%23999;fill-rule:nonzero;\'/><path d=\'M7,2c2.8,0 5,2.2 5,5c0,2.8 -2.2,5 -5,5c-2.8,0 -5,-2.2 -5,-5c0,-2.8 2.2,-5 5,-5\' style=\'fill:%23ddd;fill-rule:nonzero;\'/><path d=\'M10.695,1.774l-8.839,8.839l1.626,1.626l8.839,-8.839l-1.626,-1.626Z\' style=\'fill:%23999;\'/></svg>',
        'file_icon_image':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M0.369,9.141c-0.252,-0.678 -0.369,-1.396 -0.369,-2.141c0,-3.863 3.137,-7 7,-7c3.863,0 7,3.137 7,7l-0.137,1.353l-3.853,-3.853l-3.5,3.5l-2.5,-2.5l-3.641,3.641Z\' style=\'fill:%238080ff;\'/><path d=\'M0.839,10.151l-0.47,-1.01l3.641,-3.641l2.5,2.5l3.5,-3.5l3.853,3.853c-0.076,0.395 -0.201,0.778 -0.341,1.147l-10.371,3.345c-0.293,-0.194 -0.579,-0.416 -0.838,-0.651l-1.474,-2.043Z\' style=\'fill:%23fff;\'/><g><path d=\'M13.522,9.5c-0.99,2.64 -3.539,4.5 -6.522,4.5c-1.426,0 -2.753,-0.421 -3.849,-1.155l6.859,-6.866l3.512,3.521Z\' style=\'fill:%2333c;\'/><path d=\'M0.839,10.151l3.171,-3.172l1.761,1.761l-3.459,3.454c-0.591,-0.632 -1.079,-1.313 -1.473,-2.043Z\' style=\'fill:%2333c;\'/></g><circle cx=\'6\' cy=\'3.5\' r=\'1.5\' style=\'fill:%23fff;\'/></svg>',
        'file_icon_ignored_image': '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M0.369,9.141c-0.252,-0.678 -0.369,-1.396 -0.369,-2.141c0,-3.863 3.137,-7 7,-7c3.863,0 7,3.137 7,7l-0.137,1.353l-3.853,-3.853l-3.5,3.5l-2.5,-2.5l-3.641,3.641Z\' style=\'fill:%23808080;\'/><path d=\'M0.839,10.151l-0.47,-1.01l3.641,-3.641l2.5,2.5l3.5,-3.5l3.853,3.853c-0.076,0.395 -0.201,0.778 -0.341,1.147l-10.371,3.345c-0.293,-0.194 -0.579,-0.416 -0.838,-0.651l-1.474,-2.043Z\' style=\'fill:%23fff;\'/><g><path d=\'M13.522,9.5c-0.99,2.64 -3.539,4.5 -6.522,4.5c-1.426,0 -2.753,-0.421 -3.849,-1.155l6.859,-6.866l3.512,3.521Z\' style=\'fill:%23808080;\'/><path d=\'M0.839,10.151l3.171,-3.172l1.761,1.761l-3.459,3.454c-0.591,-0.632 -1.079,-1.313 -1.473,-2.043Z\' style=\'fill:%23808080;\'/></g><circle cx=\'6\' cy=\'3.5\' r=\'1.5\' style=\'fill:%23fff;\'/></svg>',
        'file_icon_markdown':      '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M14,0l-14,0l0,14l14,0l0,-14Z\' style=\'fill:%236a6a95;fill-rule:nonzero;\'/><path d=\'M12,11.5l-2.5,0l0,-5.143l-2.5,2.948l-2.5,-2.948l0,5.143l-2.5,0l0,-9l2.273,0l2.721,3.377l2.733,-3.377l2.273,0l0,9Z\' style=\'fill:%23DDD;fill-rule:nonzero;\'/></svg>',
        'file_icon_office':        '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23808080;fill-rule:nonzero;\'/><rect x=\'10\' y=\'1.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'10\' y=\'4\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'10\' y=\'6.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'10\' y=\'9\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'10\' y=\'11.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'6.5\' y=\'1.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'6.5\' y=\'4\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'6.5\' y=\'6.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'6.5\' y=\'9\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'6.5\' y=\'11.5\' width=\'2.5\' height=\'1\' style=\'fill:%23cdcdcd;\'/><rect x=\'1.5\' y=\'1.5\' width=\'4\' height=\'11\' style=\'fill:%23cdcdcd;\'/></svg>',
        'file_icon_pdf':           '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23d20000;fill-rule:nonzero;\'/><path d=\'M12.69,9.115c-0.075,0.048 -0.291,0.076 -0.428,0.076c-0.443,0 -0.99,-0.204 -1.762,-0.534c0.297,-0.022 0.568,-0.031 0.811,-0.031c0.446,0 0.575,0 1.012,0.109c0.433,0.108 0.438,0.333 0.367,0.38Zm-7.72,0.069c0.172,-0.303 0.349,-0.622 0.526,-0.961c0.44,-0.83 0.719,-1.484 0.923,-2.017c0.413,0.749 0.926,1.383 1.525,1.894c0.077,0.063 0.157,0.125 0.242,0.189c-1.224,0.246 -2.283,0.539 -3.216,0.895Zm1.428,-7.856c0.244,0 0.384,0.612 0.395,1.191c0.011,0.573 -0.121,0.974 -0.29,1.277c-0.141,-0.445 -0.205,-1.14 -0.205,-1.596c0,-0.001 -0.01,-0.872 0.1,-0.872Zm-4.788,11.025c0.142,-0.378 0.687,-1.124 1.494,-1.788c0.051,-0.038 0.177,-0.157 0.292,-0.266c-0.843,1.35 -1.412,1.885 -1.786,2.054Zm11.312,-4.029c-0.242,-0.241 -0.789,-0.367 -1.615,-0.377c-0.56,-0.008 -1.23,0.041 -1.942,0.139c-0.315,-0.184 -0.641,-0.381 -0.9,-0.622c-0.689,-0.646 -1.262,-1.539 -1.621,-2.521c0.021,-0.095 0.044,-0.173 0.062,-0.256c0,0 0.387,-2.208 0.283,-2.954c-0.015,-0.105 -0.021,-0.132 -0.051,-0.212l-0.033,-0.089c-0.104,-0.243 -0.313,-0.502 -0.639,-0.488l-0.19,-0.006l-0.003,0c-0.362,0 -0.661,0.186 -0.736,0.461c-0.236,0.872 0.007,2.171 0.448,3.856l-0.114,0.275c-0.315,0.768 -0.711,1.542 -1.058,2.225l-0.048,0.09c-0.365,0.717 -0.7,1.328 -1,1.843l-0.313,0.167c-0.021,0.014 -0.556,0.294 -0.681,0.37c-1.064,0.634 -1.77,1.356 -1.887,1.929c-0.037,0.181 -0.009,0.414 0.18,0.525l0.302,0.15c0.13,0.064 0.272,0.097 0.41,0.097c0.757,0 1.637,-0.941 2.845,-3.053c1.4,-0.457 2.994,-0.836 4.39,-1.045c1.062,0.6 2.369,1.015 3.194,1.015c0.147,0 0.274,-0.013 0.377,-0.042c0.156,-0.04 0.29,-0.13 0.372,-0.256c0.158,-0.238 0.193,-0.569 0.148,-0.91c-0.01,-0.1 -0.093,-0.226 -0.18,-0.311Z\' style=\'fill:%23fff;fill-rule:nonzero;\'/></svg>',
        'file_icon_system':        '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><rect x=\'0\' y=\'0\' width=\'14\' height=\'14\' style=\'fill:%23808080;fill-rule:nonzero;\'/><g><path d=\'M1.247,6.495l3.263,0l0,-1.067l-0.881,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.284,0.479l0,0.82l0.928,0l0,2.536l-1.052,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M7,6.588c1.082,0 1.825,-0.89 1.825,-2.567c0,-1.67 -0.743,-2.521 -1.825,-2.521c-1.082,0 -1.825,0.843 -1.825,2.521c0,1.677 0.743,2.567 1.825,2.567Zm0,-1.021c-0.309,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.263,-1.5 0.572,-1.5c0.309,0 0.572,0.201 0.572,1.5c0,1.299 -0.263,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M9.598,6.495l3.263,0l0,-1.067l-0.882,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.283,0.479l0,0.82l0.927,0l0,2.536l-1.051,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M2.825,12.588c1.082,0 1.824,-0.89 1.824,-2.567c0,-1.67 -0.742,-2.521 -1.824,-2.521c-1.083,0 -1.825,0.843 -1.825,2.521c0,1.677 0.742,2.567 1.825,2.567Zm0,-1.021c-0.31,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.262,-1.5 0.572,-1.5c0.309,0 0.572,0.201 0.572,1.5c0,1.299 -0.263,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M5.423,12.495l3.263,0l0,-1.067l-0.882,0l0,-3.835l-0.974,0c-0.371,0.232 -0.727,0.371 -1.284,0.479l0,0.82l0.928,0l0,2.536l-1.051,0l0,1.067Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/><path d=\'M11.175,12.588c1.083,0 1.825,-0.89 1.825,-2.567c0,-1.67 -0.742,-2.521 -1.825,-2.521c-1.082,0 -1.824,0.843 -1.824,2.521c0,1.677 0.742,2.567 1.824,2.567Zm0,-1.021c-0.309,0 -0.572,-0.247 -0.572,-1.546c0,-1.299 0.263,-1.5 0.572,-1.5c0.31,0 0.572,0.201 0.572,1.5c0,1.299 -0.262,1.546 -0.572,1.546Z\' style=\'fill:%23CCC;fill-rule:nonzero;\'/></g></svg>',
        'file_icon_text':          '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><path d=\'M14,0l-14,0l0,14l14,0l0,-14Z\' style=\'fill:%236A6A95;fill-rule:nonzero;\'/><rect x=\'6.5\' y=\'1.5\' width=\'6\' height=\'1\' style=\'fill:%23fff;\'/><rect x=\'1.5\' y=\'1.5\' width=\'3.5\' height=\'3.5\' style=\'fill:%23fff;\'/><rect x=\'1.5\' y=\'6.5\' width=\'11\' height=\'1\' style=\'fill:%23fff;\'/><rect x=\'6.5\' y=\'4\' width=\'6\' height=\'1\' style=\'fill:%23fff;\'/><rect x=\'1.5\' y=\'11.5\' width=\'8\' height=\'1\' style=\'fill:%23fff;\'/><rect x=\'1.5\' y=\'9\' width=\'11\' height=\'1\' style=\'fill:%23fff;\'/></svg>',
        'file_icon_video':         '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 14 14\'><g id=\'Layer1\'><path d=\'M14,14l0,-14l-14,0l0,14l14,0Z\'/><path d=\'M9.5,3l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M3.5,3l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M6.5,3l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M12.5,3l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M9.5,13l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M3.5,13l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M6.5,13l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M12.5,13l0,-2l-2,0l0,2l2,0Z\' style=\'fill:%23fff;\'/><path d=\'M12.5,10l0,-6l-11,0l0,6l11,0Z\' style=\'fill:%23eda412;\'/></g></svg>',
    };
    // Programatically add File icon CSS rules
    function CSS_UI_Icon_Rules(el) {
        let class_name;
        let selector;
        let kinds = ['dir','dir_invisible','file','alias','code','font','audio','video','htm','image','pdf','text','markdown','app','invisible','ignore','archive','bin','database','ebook','graphics','ignored_image','office','system'];
        let rules = '';
        if ( el === 'body' ) {
            rules += '#bookmarks ul a { background-image:'+ SVG_UI_File_Icon('file_icon_file') +'; }';
            rules += '#bookmarks ul a[href^="file"] { background-image:'+ SVG_UI_File_Icon('file_icon_dir') +'; }';
            rules += '#bookmarks ul a[href^="http"] { background-image:'+ SVG_UI_File_Icon('file_icon_htm') +'; }';
            rules += 'body:not(.use_custom_icons) #dir_list tr.dir a.icon span { background-image:'+ SVG_UI_File_Icon('file_icon_dir_default') + '; background-size:auto 13px; }';
            rules += 'body:not(.use_custom_icons) #dir_list tr.file:not(.app) a.icon span { background-image:'+ SVG_UI_File_Icon('file_icon_file_default') + '; background-size:auto 13px; }';
        } else {
            rules += '#iframe_body:not(.use_custom_icons) #dir_list tr.dir td.name a::before { background:'+ SVG_UI_File_Icon('file_icon_dir_default') +'; }';
            rules += '#iframe_body:not(.use_custom_icons) #dir_list tr.file td.name a::before { background:'+ SVG_UI_File_Icon('file_icon_file_default') +'; }';
        }
        for ( let kind of kinds ) {
            class_name = kind;
            switch(kind) {
                case 'dir': class_name = 'dir:not(.app)'; break;
                case 'dir_invisible': class_name = 'dir.invisible'; break;
            }
            if ( el === 'body' ) {
                selector = el +'.use_custom_icons #dir_list tr.'+ class_name +':not(.media) a.icon span ';
                // selectors for iframe content kinds, icons in content titlebar
                if ( kind !== undefined && !['audio','dir','font','ignored','image','pdf','video'].includes(kind) ) {
                    selector += ', #content_pane.has_iframe #title span.has_'+ kind +'::before, #content_pane.has_ignored #title span.has_'+ kind +'::before'
                }
            } else {
                selector = el +'.use_custom_icons #dir_list tr.'+ class_name +' td.name a::before ';
            }
            let background_image = '{ background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_'+kind] +'"); }' ;
            let rule = selector + background_image;
            rules += rule;
        }
        return rules;
    }
	//***** STYLES *****//

	// DEFINE STYLES
	var $main_style_rules =
    '#content_pane.has_image #content_image                 { align-items: center; justify-content: center; }' +
    '.image_grid_item a                                     { align-self: center;  justify-self: center; }' +
    '#sidebar_wrapper, body.theme_light #sidebar, body.theme_light #sidebar ul, body.theme_light  #preview_text, body.theme_light  #source_text, body.theme_light #content_header' +
                                                           '{ background-color: lightgray; }' +
        // light non-media ("light cyan")
    'body.theme_light #dir_list tr.selected:not(.playing), body.theme_light #dir_list tr.selected.loaded:not(.playing), body.theme_light #dir_list tr.selected.loaded:hover'+
                                                           '{ background-color: rgba(172,202,235,1.00) !important; }' +
    'body.theme_light #dir_list tr.loaded:not(.selected), body.theme_light #dir_list tbody tr:not(.media):hover, body.theme_light.alternate_background #dir_list #tbody tr:not(.media):hover, body.theme_light #dir_list .hovered:not(.media), body.theme_light.alternate_background #dir_list #tbody tr.hovered:not(.media)'+
                                                           '{ background-color: rgba(172,202,235,0.60); }' +
        // light media ("light aqua")
    'body.theme_light #dir_list tr.media.playing            { background-color: rgba(130,196,196,1); }' + // #82C4C4
    'body.theme_light #dir_list tr.media.selected:not(.playing)'+
                                                           '{ background-color: rgba(116,190,190,0.60) !important; }' +
    'body.theme_light #dir_list tr.media.selected:not(.playing):hover, body.theme_light #dir_list tr.media:not(.selected):hover'+
                                                           '{ background-color: rgba(116,190,190,0.40) !important; }' +
        // dark non-media ("dark cyan")
    'body.theme_dark #dir_list tr.selected:not(.playing), body.theme_dark #dir_list tr.selected.loaded:not(.playing), body.theme_dark #dir_list tr.selected.loaded:hover'+
                                                           '{ background-color: rgba(101,140,179,1.00) !important; }' + //#658CB3
    'body.theme_dark #dir_list tr.loaded:not(.selected), body.theme_dark #dir_list tbody tr:not(.media):hover, body.theme_dark.alternate_background #dir_list #tbody tr:not(.media):hover, body.theme_dark #dir_list .hovered:not(.media), body.theme_dark.alternate_background #dir_list #tbody tr.hovered:not(.media)'+
                                                           '{ background-color: rgba(101,140,179,0.66); }' +
        // dark media ("dark aqua")
    'body.theme_dark #dir_list tr.media.playing             { background-color: rgba(076,143,143,1.00) !important; }' +
    'body.theme_dark #dir_list tr.media.selected:not(.playing)'+
                                                           '{ background-color: rgba(076,143,143,0.70) !important; }' +
    'body.theme_dark #dir_list tr.media.selected:not(.playing):hover, body.theme_dark #dir_list tr.media:not(.selected):hover'+
                                                           '{ background-color: rgba(076,143,143,0.45) !important; }' +
        // text editor row ("purple")
    'body.theme_light.has_text #text_editor_row, body.theme_light.edited #text_editor_row' +
                                                           '{ background-color: rgba(160,160,230,1.00); }' + // #A0A0E6
    'body.theme_dark.has_text #text_editor_row, body.theme_dark.edited #text_editor_row' +
                                                           '{ background-color: rgba(100,100,160,1.00); }' + // #6464A0
        // other UI elements
    'body.theme_dark #content_pane.has_grid #content_container, body.theme_dark #content_grid > div:hover, body.theme_dark #content_grid > div.hovered, body.theme_dark #content_grid > div.selected, body.theme_dark .glyph_container:hover, body.theme_dark .glyph_container.selected' +
                                                           '{ background-color: #262626; }' +
    'body.theme_dark #content_pane, body.theme_dark #content_pane.has_image, body.theme_dark #content_pane.has_grid #content_grid::after, body.theme_dark #content_grid > div, body.theme_dark #content_font, .split_btn::after' +
                                                           '{ background-color: #333; }' +
    'body.theme_dark #sidebar ul, body.theme_dark #preview_text_menu_item span, body.theme_dark #sidebar_header thead, body.theme_dark #sidebar_menus, body.theme_dark #preview_text, body.theme_dark  #source_text, body.theme_dark.alternate_background #dir_list tbody tr:nth-of-type(odd):not(.selected):not(.playing):not(.loaded), body.theme_dark.alternate_background #dir_list tbody tr:nth-of-type(odd):not(.loaded), body.theme_dark #tfoot, body.theme_dark .playlist_item:nth-of-type(odd), body.theme_dark #font_info, body.theme_dark #glyph_viewer_info' +
                                                           '{ background-color: #444; }' +
    'body.theme_dark #sidebar, body.theme_dark #dir_list #tbody, body.theme_dark #content_header, body.theme_dark .font_grid_item:hover, body.theme_dark .font_grid_item.hovered, body.theme_dark .image_grid_item:hover, body.theme_dark .image_grid_item.hovered' +
                                                           '{ background-color: #555; }' +
    'body.theme_dark #sidebar ul li:not(#preview_text_menu_item):hover, body.theme_dark li.has_submenu:hover, body.theme_dark #preview_text_menu_item span:hover, body.theme_dark #preview_text:hover, body.theme_dark #source_text:hover' +
                                                           '{ background-color: #666; }' +
    'body.theme_dark #sidebar .hovered, body.theme_dark #dir_list tbody tr:hover, body.theme_dark.alternate_background #dir_list #tbody tr:hover, body.theme_dark.alternate_background #dir_list #tbody tr:nth-of-type(odd).hovered, body.theme_dark #content_iframe[href^="/"]' +
                                                           '{ background-color: #777; }' +
    'body.theme_dark #grid_btn .menu li:hover               { background-color: #888 !important; }' +
    'body.theme_dark #grid_btn .menu, body.theme_dark #grid_btn .menu li' +
                                                           '{ background-color: #AAA; }' +
    'body.theme_light #sidebar_header thead tr, body.theme_light #sidebar_menus, #parents_dir_menu + ul li:hover, #bookmarks li:hover, body.theme_light #preview_text_menu_item span:hover, body.theme_light #preview_text:hover, body.theme_light #source_text:hover, body.theme_light #grid_btn .menu li:hover' +
                                                           '{ background-color: #BBB; }' +
    'body.theme_light #grid_btn .menu li, body.theme_light.alternate_background #dir_list tbody tr:nth-of-type(odd):not(.selected):not(.playing):not(.loaded), body.theme_light #tfoot, body.theme_light .playlist_item:nth-of-type(odd), body.theme_dark #glyph_viewer' +
                                                           '{ background-color: #CCC; }' +
    'body.theme_light #dir_list tbody                       { background-color: #DFDFDF !important; }' +
    'body.theme_light #content_grid > div, #warnings, body.theme_light #content_pane.has_grid #content_grid::after, body.theme_light #font_info, body.theme_light #glyph_viewer_info' +
                                                           '{ background-color: #EEE; }' +
    'body.theme_light #content_pane, body.theme_light #content_grid, body.theme_light #content_grid div.selected, body.theme_light #content_pane.has_image, #content_font, #content_iframe, #scale, body.theme_light #content_grid div:hover, body.theme_light #content_grid div.hovered, body.theme_light #glyph_viewer, body.is_safari button, body.theme_light .glyph_container:hover, body.theme_light .glyph_container.selected' +
                                                           '{ background-color: #FFF; }' +
    'body.is_chrome #audio_container                        { background-color: rgb(241, 243, 244); }' +
    '#warnings button:focus,#warnings button.focus          { background-color: #0E4399; }' +
    '#bookmarks_menu div                                    { background-image:'+ SVG_UI_Icon('menu') + '; }' +
    'body.theme_light .bookmarks > a::before                { background-image:'+ SVG_UI_Icon('bookmark') +'; }' +
    'body.theme_dark .bookmarks > a::before                 { background-image:'+ SVG_UI_Icon('bookmark_dark') +'; }' +
    'body.theme_light li.has_submenu                        { background-image:'+ SVG_UI_Icon('arrow') +'; }' +
    'body.theme_dark li.has_submenu                         { background-image:'+ SVG_UI_Icon('arrow_dark') +'; }' +
    '#theme::before, body.sort_by_default #default span::before, body.sort_by_name #name span::before, body.sort_by_size #size span::before, body.sort_by_date #date span::before, body.sort_by_kind #kind span::before, body.sort_by_ext #ext span::before, body.alternate_background #alternate_background span::before, body.show_numbers #show_numbers span::before, body.autoload_media #autoload_media span::before, body.split_view #split_view_menu_item, body.split_view #split_view span::before, body:not(.enable_text_editing) #enable_text_editing::before, body.source_text:not(.preview_text) #source_text::before, body.preview_text:not(.source_text) #preview_text::before, body.sort_by_default #sort_by_default span::before, body.sort_by_name #sort_by_name span::before, body.sort_by_size #sort_by_size span::before, body.sort_by_date #sort_by_date span::before, body.sort_by_kind #sort_by_kind span::before, body.sort_by_ext #sort_by_ext span::before'+
                                                           '{ background-image:'+ SVG_UI_Icon('check_mark') +'; }' +
    '#parent_dir_menu a, body.sort_by_default #sort_by_default span::after, body.sort_by_name #sort_by_name span::after, body.sort_by_size #sort_by_size span::after, body.sort_by_date #sort_by_date span::after, body.sort_by_kind #sort_by_kind span::after, body.sort_by_ext #sort_by_ext span::after'+
                                                           '{ background-image:'+ SVG_UI_Icon('chevron_up') +'; }' +
    '#prev_btn                                              { background-image:'+ SVG_UI_Icon('chevron_left') + '; }' +
    '#next_btn                                              { background-image:'+ SVG_UI_Icon('chevron_right') + '; }' +
    'body.is_error #content_pane, #warnings h3::before      { background-image:'+ SVG_UI_Icon('error') +'; }' +
    'body.has_fonts #grid_btn, body.has_images #grid_btn, #grid_btn .menu'+
                                                           '{ background-image:'+ SVG_UI_Icon('grid') +'; }' +
    'body #content_pane.has_ignored:not(.has_grid)          { background-image:'+ SVG_UI_Icon('ignored') +'; }' +
    'body.theme_dark #content_pane.has_ignored:not(.has_grid){ background-image:'+SVG_UI_Icon('ignored_dark') +'; }' +
    '#decrease                                              { background-image:'+ SVG_UI_Icon('minus') +'; }' +
    '#close_audio                                           { background-image:'+ SVG_UI_Icon('multiply') +'; }' +
    'body.has_audio #content_pane:not(.has_image):not(.has_video):not(.has_ignored):not(.has_grid):not(.has_zoom_image)'+
                                                           '{ background-image:'+ SVG_UI_Icon('music') +'; }' +
    '#increase                                              { background-image:'+ SVG_UI_Icon('plus') +'; }' +
    '#prev_track, #next_track                               { background-image:'+ SVG_UI_Icon('prev_next_track') +'; }' +
    '#toggle_sidebar, #toggle_info                          { background-image:'+ SVG_UI_Icon('toggle') +'; }' +

     CSS_UI_Icon_Rules('body') + // FILE & DIR ICONS, plus additions:
    '#content_pane #title span::before                      { width:14px; height:14px; display:inline-block; margin:0 5px -3px 2px; }' +
    '#content_pane.has_dir #title span::before, #content_pane.has_grid #title span::before, #content_pane.has_font_grid #title span::before, #content_pane.has_image_grid #title span::before'+
                                                           '{ background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_dir'] +'"); }' +
    '#content_pane.has_font #title span::before             { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_font'] +'"); }' +
    '#content_pane.has_image #title span::before, #content_pane.has_zoom_image #title span::before'+
                                                           '{ background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_image'] +'"); }' +
    '#content_pane.has_ignored #title span::before          { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_ignored'] +'"); }' +
    '#content_pane.has_iframe #title span.has_other::before { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_file'] +'"); }' +
    '#content_audio_title td:before                         { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_audio'] +'"); height:14px !important; }' +
    '#content_pane.has_pdf #title span::before              { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_pdf'] +'"); }' +
    '#content_pane.has_video #title span::before            { background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_File_Icons['file_icon_video'] +'"); }' +
    'body.theme_light #grid_btn.has_grid, body.theme_light #grid_btn.has_grid:hover ul'+
                                                           '{ background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_Icons['grid_loaded'] +'") !important; opacity:1 !important; }' +
    'body.theme_dark #grid_btn.has_grid, body.theme_dark #grid_btn.has_grid:hover ul'+
                                                           '{ background-image: url("data:image/svg+xml;utf8,'+ SVG_UI_Icons['grid_loaded_dark'] +'") !important; opacity:1 !important; }' +

    '#parent_dir_menu a, #bookmarks_menu div, #bookmarks li a::before, #bookmarks li.toggle_UI_pref span::before, #theme::before, #enable_text_editing::before, #sort_menu span::before, #preview_text_menu_item span::before, #sorting div span::before, #sorting div span::after, #toggle_sidebar, #toggle_info, #content_pane, #close_audio, #prev_track, #next_track, #glyph_viewer' +
                                                           '{ background-position: center; }' +
    '#prev_next_btns span, #scale span                      { background-position: center 36%; }' +
    '.toggle_UI_pref, .bookmarks > a                        { background-position: 5px center; }' +
    '#dir_list tbody a                                      { background-position: 6px 4px; }' +
    '#dir_list a.icon span                                  { background-position: 6px 0; }' +
    '#bookmarks ul a                                        { background-position: 8px center; }' +
    '#bookmarks > li                                        { background-position: right 6px center; }' +
    '#grid_btn,#grid_btn .menu                              { background-position: right 5px top 6px; }' +
    '#content_audio_title td:before                         { background-position: right 4px center; }' +
    '#bookmarks li a::before, .toggle_UI_pref, #toggle_sidebar, #grid_btn, #grid_btn .menu, #toggle_info, #main_content a, a, div, li, span, span::before, span::after, #dir_list a.icon span, #content_pane, #glyph_viewer, #warnings h3::before, #content_audio_title td:before'+
                                                           '{ background-repeat: no-repeat; }' +
    '#glyph_viewer                                          { background-size: contain; }' +
    '.toggle_UI_pref, th .sorting, #scale span              { background-size: 10px; }' +
    '.bookmarks > a, li.has_submenu, #parent_dir_menu a     { background-size: 12px; }' +
    '#dir_list tbody a, #dir_list a.icon span, #bookmarks ul a, #close_audio, #grid_btn, #grid_btn .menu'+
                                                           '{ background-size: 14px; }' +
    '#toggle_sidebar, #toggle_info                          { background-size: 18px; }' +
    '#warnings h3::before                                   { background-size: 24px; }' +
    '#prev_next_btns span                                   { background-size: 33%; }' +
    '#content_pane                                          { background-size: 50%; }' +
    ':root, html, body, #sidebar_wrapper, #sidebar_header, #dir_list, #main_content, #content_pane, #content_pdf, #content_iframe' +
                                                           '{ border: 0 !important; }' +
    'body.theme_dark ul                                     { border: solid 1px #222; }' +
    'button                                                 { border: solid 1px #333; }' +
    'body.theme_light #sidebar ul                           { border: solid 1px gray; }' +
    'body.theme_dark #sidebar_header .menu, body.theme_dark #text_editor_row, body.theme_dark:not(.is_error) #dir_list #tbody, body.theme_dark #tfoot' +
                                                           '{ border-top: solid 1px #111; }' +
    'body.theme_light #dir_list tbody, #grid_btn .menu, body.theme_light #bookmarks, body.theme_light #text_editor_row, #tfoot, .font_grid_item:not(:first-of-type), .image_grid_item + .font_grid_item, #font_info th, #font_info td' +
                                                           '{ border-top: solid 1px grey; }' +
    '#sort_by, tr.sorted, tr:not(.invisible) ~ tr.invisible + tr:not(.invisible)' + // , tr.dir ~ tr:not(.dir,.invisible,.ignore)
                                                           '{ border-top: solid 1px #999; }' +
    'body.theme_dark #grid_btn ul.menu                      { border-top: solid 1px #EEE; }' +
    '#parents_dir_menu + ul, #bookmarks_menu + ul, #grid_btn ul.menu'+
                                                           '{ border-right: 0 !important; }' +
    'body.theme_dark #parents_dir_menu, body.theme_dark #sidebar, body.theme_dark #warnings' +
                                                           '{ border-right: solid 1px #111; }' +
    '#sidebar, body.theme_light #parents_dir_menu, body.theme_light #grid_btn .menu li, .image_grid_item, div.glyph_container, #font_info td:first-of-type' +
                                                           '{ border-right: solid 1px grey; }' +
    'body.theme_dark #grid_btn .menu li                     { border-right: solid 1px #EEE; }' +
    'body.theme_dark #sidebar_title, body.theme_dark #sidebar_menus, body.theme_dark #sidebar_header .menu, body.theme_dark #content_header, body.theme_dark #content_pane.has_audio #content_title, body.theme_dark #warnings' +
                                                           '{ border-bottom: solid 1px #111; }' +
    'body.theme_light #sidebar_header thead tr, body.theme_light #bookmarks, body.theme_light #sidebar_menus, body.theme_light #grid_btn .menu li#show_image_grid, #grid_btn .menu, .specimen, .font_grid_item:last-of-type, .image_grid_item, div.glyph_container, #glyph_viewer_info' +
                                                           '{ border-bottom: solid 1px grey; }' +
    'body.theme_light #content_title, body.theme_light #content_pane.has_audio #content_header' +
                                                           '{ border-bottom: solid 1px #888; }' +
    '#bookmarks_menu + ul > li.has_submenu.ruled, .rule     { border-bottom: solid 1px #999; }' +
    'body.theme_dark #content_pane.has_font #content_font hr, .hamburger h4'+
                                                           '{ border-bottom: solid 1px #CCC; }' +
    'body.theme_dark #grid_btn ul.menu, body.theme_dark #grid_btn .menu li#show_image_grid'+
                                                           '{ border-bottom: solid 1px #EEE; }' +
    '#parents_dir_menu + ul, #bookmarks_menu + ul           { border-left:0; }' +
    'body.theme_dark #parents_dir_menu, body.theme_dark  #grid_btn ul.menu, body.theme_dark #warnings' +
                                                           '{ border-left: solid 1px #111; }' +
    'body.theme_light #parents_dir_menu, #grid_btn .menu    { border-left: solid 1px grey; }' +
    'body.theme_dark #grid_btn ul.menu                      { border-left: solid 1px #EEE; }' +
    'table                                                  { border-collapse: collapse; }' +
    'html, body, :root                                      { border-radius: 0; }' +
    'button                                                 { border-radius: 3px; }' +
    '#warnings                                              { border-radius: 0 0 3px 3px; }' +
    'body.theme_light #sidebar ul                           { box-shadow: 0px 2px 3px -2px #888; }' +
    'body.theme_dark #sidebar ul                            { box-shadow: 0px 2px 3px -2px #111; }' +
    '#warnings                                              { box-shadow: 0px 2px 12px 0 #111; }' +
    'body.theme_dark  #grid_btn ul.menu                     { box-shadow: none; }' +
    'html, body, :root, #sidebar, #grid_btn .menu li, #content_container, #content_source, #content_preview' +
                                                           '{ box-sizing: border-box; }' +
    '#checkbox_div label, #grid_btn .menu li, #content_grid .font_grid_item'+
                                                           '{ clear: both; }' +
    '#dir_list tbody .name                                  { clear: right; }' +
    'body.theme_light #sidebar, body.theme_light #sidebar a, #content_header, body.theme_light #content_font, body.theme_light .font_grid_item a, body.theme_light .image_grid_item p, body.theme_light #content_font, body.theme_light .font_grid_item p, body.theme_light .font_grid_item a, body.theme_light .image_grid_item p, .split_btn span, body #warnings, body.theme_dark #grid_btn .menu li' +
                                                           '{ color: #111 }' +
    'body.theme_light #sidebar #tfoot tr                    { color: #444 }' +
    'body.theme_light #dir_list tr.ignore a, body.theme_light #dir_list tr.ignore.app a, .glyph_info' +
                                                           '{ color: #777 }' +
    '#sort_menu .disabled span, #dir_list th.disabled       { color: #999 }' +
    'body.theme_dark #dir_list tr.ignore td, body.theme_dark #dir_list tr.file.ignore a, body.theme_dark #sidebar #tfoot td' +
                                                           '{ color: #BBB }' +
    'body.theme_dark #sidebar th:not(.disabled), body.theme_dark #sidebar td, body.theme_dark #sidebar a, body.theme_dark #error_message *, body.theme_dark #content_header tr, body.theme_dark #content_header tr a, body.theme_dark #content_font, body.theme_dark .font_grid_item p, body.theme_dark .font_grid_item a, body.theme_dark .image_grid_item p, #warnings button:focus, #warnings button.focus' +
                                                           '{ color: #EEE }' +
    '#warnings h3::before, #bookmarks li > a::before, #bookmarks li > span::before, #preview_text_menu_item span::before, #sorting div span::before, #sorting div span::after, body.has_hidden_sidebar #handle, #dir_list tr:empty, #dir_list .audio td.icon, #dir_list .video td.icon, tr.invisible, body.hide_ignored .ignore, .split_btn::after, #content_pane.has_grid #content_grid::after, #title span::before' +
                                                           '{ content: "" }' +
    '#content_pane.has_image:not(.has_grid) #title::after, #content_pane.has_zoom_image:not(.has_grid) #title::after'+
                                                           '{ content: attr(data-after) }' +
    '#content_pane.has_font #title::before                  { content: "Font: " }' + // font and image grid
    '#content_pane.has_grid:not(.has_ignored) #title::before{ content: "Fonts and Images from: " }' + // font and image grid
    'body:not(.has_images) #content_pane.has_grid:not(.has_ignored) #title::before, #content_pane.has_grid #title.font_grid::before' +
                                                           '{ content: "Fonts from: " }' + // font grid
    '#glyph_viewer_info div::before                         { content: "Glyph " }' +
    '#content_pane.has_ignored:not(.has_grid) #title::before{ content: "Ignored content: " }' + // .ignored
    'body:not(.has_fonts) #content_pane.has_grid:not(.has_ignored) #title::before, #content_pane.has_grid #title.image_grid::before' +
                                                           '{ content: "Images from: " }' + // image grid
    '#content_pane.has_dir:not(.has_grid) #title::before    { content: "Index of: " }' + // .dir
    'body:not(.has_playlist) #sidebar_title th:before       { content: "INDEX OF"; }' +
    '#content_pane.has_audio #content_audio_title td::before, body #content_pane.has_video #title::before' +
                                                           '{ content: "Playing: " }' + // .audio, .video
    'body.has_playlist #sidebar_title th:before             { content: "PLAYLIST"; }' +
    'body#top.edited #warnings.unloading h3::before         { content: "Text Editor: " }' +
    'body#top.edited #text_editor_row a:after               { content: " (edited)"; }' +
    'body.edited.has_text #title::after, body.iframe_edited:not(.has_text) #content_pane.has_iframe #title::after' +
                                                           '{ content: " (edited)"; }' + // .ignored
    'body.show_numbers #tbody                               { counter-reset: row; }' +
    'body.show_numbers #tbody tr td.name a::before          { counter-increment: row;  content:counter(row);}' +
    '#sidebar_title th, #sort_menu .disabled span, #dir_list .disabled'+
                                                           '{ cursor: default; }' +
    '#sidebar_menus td:hover, #parents_dir_menu div, #bookmarks_menu div, .menu label, #grid_btn, #sorting .toggle_UI_pref, #toggle_info, .split_btn span' +
                                                           '{ cursor: pointer; }' +
    '#handle                                                { cursor: col-resize; }' +
    '#content_pane:not(.has_zoom_image) #content_image img  { cursor: zoom-in; }' +
    '#content_pane.has_zoom_image #content_image img        { cursor: zoom-out; }' +
    '#sidebar_menus ul, #show_details span, body.has_playlist #grid_btn, body.has_playlist #sidebar_buttons td > label, #grid_btn .menu, body:not(.has_media) #sorting .name input, #bookmarks li#theme span span, #preview_text::before, #source_text::before, #sidebar_buttons td.up::before, body:not(.show_details) #sorting .details.sorting, #dir_list tr::before, #tbody tr td:not(.name), #text_editor_row, body.has_hidden_sidebar #handle, body.has_hidden_sidebar #sidebar, #dir_list tr:empty, #dir_list tr.audio td.icon, #dir_list tr.video td.icon, tr.invisible, body.hide_ignored #tbody tr.ignore, #content_title::before, #content_pane #content_audio_title, .split_btn, #content_pane #content_audio, #content_pane #content_text, #content_pane .content, #content_pane.has_grid .content, #content_pane:not(.has_hidden_grid) #content_grid, #content_pane.has_grid.has_zoom_image #content_image, #font_specimen, #font_viewer, body.has_text .content:not(#content_text), body.theme_light #theme_dark, body.theme_dark #theme_light, body.use_custom_icons #dir_list img, #dir_list tr.file.audio a img, #dir_list tr.file.video a img, #warnings, #warnings p, #warnings button, #clear_warning, #overlay, #glyph_viewer, #font_info tbody' +
                                                           '{ display: none; }' +
    'body.is_error #sorting, body.is_error #sidebar_buttons, body.is_error #text_editor_row, body.is_error #content_pane.has_iframe #content_iframe.has_content' +
                                                           '{ display: none !important; }' +
    '#sidebar li, #parent_dir_menu, #parent_dir_menu a, #parents_dir_menu + ul li a, #bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #bookmarks_menu + ul > li:hover > ul, #bookmarks_menu + ul > li > ul:hover, .menu label, body.show_details #show_details span:last-of-type, body:not(.show_details) #show_details span:first-of-type, #sort_by_default, #dir_list tbody a, #dir_list tfoot tr, #content_header, #content_pane.has_font:not(.has_grid) #content_font, #content_pane.has_font:not(.has_grid) #content_font:not(.has_font_viewer) #font_specimen, #content_pane.has_font:not(.has_grid) #content_font.has_font_viewer #font_viewer,  #content_pane.has_pdf:not(.has_grid) #content_pdf, body.has_text #content_pane:not(.has_grid) #content_text, #content_pane.has_video:not(.has_grid) #content_video, body:not(.has_text) #content_pane.has_iframe:not(.has_grid) #content_iframe, #content_pane.has_dir:not(.has_grid) #content_iframe, #content_pane.has_grid #content_grid.has_grid, #content_pane.has_grid #content_grid.has_font_grid, #content_pane.has_grid .nav_btn, #content_pane.has_font .nav_btn, .font_grid_item a, .image_grid_item a, #checkbox_div label, body.theme_dark #theme_dark, body.theme_light #theme_light, body:not(.has_hidden_sidebar) #dir_list .name, body.has_warning #warnings, body.has_warning #warnings.unloading p#warning_unsaved, body.has_warning #warnings.clear #warning_clear, body.has_warning #warnings.local p#warning_local, body.has_warning #overlay' +
                                                           '{ display: block; }' +
    '#parents_dir_menu div, body.has_images.has_fonts #grid_btn:hover ul.menu, #font_info:hover tbody' +
                                                           '{ display:block !important; }' +
    '#parents_dir_menu div, #bookmarks li > a::before, #bookmarks li > span::before, #bookmarks li#theme > span::before, body.theme_dark #bookmarks #theme_dark, body:not(.theme_dark) #bookmarks #theme_light, body.preview_text #preview_text::before, body.source_text #source_text::before, #sorting div span::before, #enable_text_editing::before, #sorting div span::after, body.show_details #dir_list td.details:not(.name):not(.ext), body.show_numbers #tbody tr td.name a::before, #title, #checkbox_div, #audio_container, #prev_track, #next_track, #close_audio, #warnings h3::before, body.has_warning #warnings.unloading #warning_ignore_btn, body.has_warning #warnings.unloading #warning_cancel_btn, body.has_warning #warnings.unloading #warning_save_btn, body.has_warning #warnings.clear #warning_clear_btn, body.has_warning #warnings.clear #warning_cancel_btn, body.has_warning #warnings.local #warning_ok_btn, #glyph_viewer_info div' +
                                                           '{ display: inline-block; }' +
    'body:not(.is_gecko) #dir_list tr td.name span, #content_pane.has_image:not(.has_grid) #content_container, #content_pane.has_video:not(.has_grid) #content_container, #content_pane.has_image:not(.has_grid) #content_image, #content_pane.has_zoom_image #content_image, #font_info tbody tr' +
                                                           '{ display: flex; }' +
    '#content_pane.has_grid .split_btn, #content_pane.has_image .split_btn, #content_pane.has_zoom_image .split_btn, #content_pane.has_font .split_btn, .split_btn span' +
                                                           '{ display: inline-flex; }' +
    'body.is_gecko #dir_list tr td.name span                { display: flow-root; }' +
    'body.has_text #text_editor_row, body.show_details #text_editor_row, body.has_hidden_text #text_editor_row, #content_pane.has_audio #content_audio_title, #content_pane.has_audio #content_audio' +
                                                           '{ display: table-row !important; }' +
    '#bookmarks_menu div, #content_pane, #content_pane.has_audio #content_audio td' +
                                                           '{ display: table-cell; }' +
    '#sorting > div                                         { display: grid; grid-gap:0; grid-template-columns: 1fr 1fr 1fr 1fr; }' +
    '#sort_by_name                                          { grid-column: 1 / span 2; }' +
    '#sort_by_default                                       { grid-column: 3 / span 2; }' +
        // display grid: dir_list rows and cells
    '#dir_list #tbody tr:not(.invisible), body.show_invisibles #tbody tr.invisible, body.show_details #dir_list tr td.details' +
                                                           '{ display: grid; grid-gap:0; grid-template-columns:  minmax(auto,7rem) 1fr minmax(auto,8rem); }' +
        'td.name                                            { grid-column: 1 / span 3; }' +
        'td.size                                            { grid-column: 1; grid-row: 2; }' +
        'td.date                                            { grid-column: 2; grid-row: 2; }' +
        'td.kind                                            { grid-column: 3; grid-row: 2; }' +
    // display grid: content pane grids
    '#content_pane.has_grid #content_grid                   { display: grid !important; grid-gap:0; grid-template-columns: repeat(auto-fill, minmax('+ ( $settings.grid_image_size + 16) +'px, auto)); grid-auto-rows: minmax(min-content, max-content); }' +
    '#content_grid .image_grid_item                         { grid-column: auto; display:flex; align-items: center; justify-content: center; }' +
    '#content_grid .font_grid_item                          { grid-column: 1 / -1; }' +
     // glyphs container
    '#content_font div#glyphs_container                     { display:grid; grid-gap:0; grid-template-columns:repeat(auto-fill, minmax(120px,auto)); }' +
    'body.theme_dark #bookmarks li > span::before, body.theme_dark #grid_btn, body.theme_dark #parent_dir_menu, body.theme_dark #bookmarks_menu, body.theme_dark #toggle_sidebar, body.theme_dark #toggle_info, body.theme_dark .glyph_container canvas, body.theme_dark #glyph_viewer:not(#glyph_viewer_info), body.theme_dark #glyph_viewer #glyph_viewer_info, body.theme_dark #sorting span::before, body.theme_dark #sorting span::after, body.is_gecko.theme_dark #prev_track, body.is_gecko.theme_dark #next_track, body.is_gecko.theme_dark #close_audio, body.is_safari.theme_dark #prev_track, body.is_safari.theme_dark #next_track, body.is_safari.theme_dark #close_audio ' +
                                                           '{ filter:invert(1); }' +
    '.menu input, #dir_list tr td.name a::before, #title_buttons_left button, #checkbox_div label, #prev_track, #next_track, #scale, #close_btn, #save_svg, #warnings h3::before, #warnings h3::before' +
                                                           '{ float: left; }' +
    'html, body, :root                                      { font-family:'+ $settings.UI_font +'; }' +
    'body, :root, #content_text                             { font-size: '+ $settings.UI_font_size +'; }' +
    '#sidebar, #sidebar_header, #dir_list, #tfoot, #content_header, #content_header table, #warnings, #font_info td, #font_info th, #glyph_viewer_info' +
                                                           '{ font-size: 0.875rem; }' +
    '#content_grid, .font_grid_item p, #error_message h1, #error_message h2' +
                                                           '{ font-size: 1rem; }' +
    '#content_grid .font_grid_item h2                       { font-size: '+ $settings.grid_font_size * 4 +'em; }' +
    '#content_font                                          { font-size: '+ $settings.grid_font_size +'em; }' +
    '.lorem.first:first-line                                { font-size: '+ $settings.grid_font_size * 1.33 +'em; }' +
    'td.name, td.name a::before, td.size, td.date           { font-variant-numeric: tabular-nums; }'+
    '.lorem.first:first-line                                { font-variant: small-caps }' +
    '#sidebar_title th, h1, h2, h3, h4, h5, h6, #font_info th'+
                                                           '{ font-weight: normal }' +
    '#dir_list .selected a, body.has_text #text_editor_row, body.edited:not(.has_hidden_text) #text_editor_row, #font_info td:first-of-type' +
                                                           '{ font-weight: bold }' +
    'html, body, :root, #parent_dir_menu a, #dir_list, #toggle_info, #main_content, #content_pane, #content_pdf, #content_text, #content_iframe, #content_grid img[src$=".svg"]' +
                                                           '{ height: 100%; }' +
    '#sidebar_header, #parents_dir_menu, #parents_dir_menu div, #content_pane:not(.has_zoom_image) #content_image img, #content_grid img' +
                                                           '{ height: auto; }' +
    '.menu input                                            { height: 0; }' +
    '#sorting div span::after                               { height: 8px; }' +
    '#bookmarks .toggle_UI_pref span::before, #theme::before, #sort_menu span::before, #preview_text_menu_item span::before, #sorting div span::before, #enable_text_editing::before'+
                                                           '{ height: 9px; }' +
    '#bookmarks li.bookmarks a::before                      { height: 12px; }' +
    '#toggle_sidebar, #toggle_info                          { height: 14px; }' +
    '#grid_btn, button, #prev_next_btns span, #scale span   { height: 18px; }' +
    '#warnings h3::before                                   { height: 24px; }' +
    '#audio                                                 { height: 32px; }' +
    '#main_content                                          { height: '+ window.innerHeight +'px; }' +
    '#content_pane:not(.has_zoom_image) #content_image img  { max-height: calc(100% - 4em); }' +
    '#font_info tbody                                       { max-height: '+ (window.innerHeight * 0.75) +'px; }' +
    '!#content_pane.has_zoom_image #content_image img       { max-height: none; }' +
    '#content_grid img                                      { max-height: '+ ($settings.grid_image_size) +'px; }' +
    '#title                                                 { min-height: 18px; }' +
    '#sidebar                                               { min-height: 100%; }' +
    '#parents_dir_menu div, #content_header td button, #content_font'+
                                                           '{ hyphens: none; }' +
    'html, body, :root, .hamburger h3, .lorem               { hyphens: auto; }' +
    '#content_container                                     { justify-content: center; }' +
    '.lorem.first:first-line, .font_grid_item p, #font_info th'+
                                                           '{ letter-spacing: 0.1em; text-indent:0.1em; }' +
    '#sidebar_title th                                      { letter-spacing: 0.5em; text-indent:0.5em; }' +
    '.image_grid_item a, button                             { line-height: 0; }' +
    '.split_btn span, .font_grid_item p                     { line-height: 1; }' +
    '#dir_list tr a, #title                                 { line-height: 1.4; }' +
    '#warnings h3                                           { line-height: 2; }' +
    '#sidebar ul, #grid_btn .menu li                        { list-style-type: none; }' +
    'html, body, :root, #sidebar ul, #parent_dir_menu, #parent_dir_menu, #parents_dir_menu, #parents_dir_menu + ul li a, #bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #bookmarks_menu, #grid_btn, #dir_list tbody a, #content_font .hamburger *, #content_font canvas, #content_grid p, #content_grid  h2, #content_text, #warnings h3' +
                                                           '{ margin: 0; }' +
    '#content_image, #content_image img                     { margin-left: auto; margin-right: auto; }' +
    '.image_grid_item + .font_grid_item                     { margin-top: -1px; }' +
    '#checkbox_div label input, #show_details, body.is_error #tbody h1'+
                                                           '{ margin-top: 0; }' +
    'body.has_audio #dir_list input                         { margin-top: 1px; }' +
    '#increase                                              { margin-right: -4px; }' +
    'th input, tr.media input, #scale                       { margin-right: 8px; }' +
    '#show_details                                          { margin-right: 0.5em; }' +
    '#warning_ignore_btn                                    { margin-right: 2em; }' +
    '#checkbox_div                                          { margin-right: calc(-6em - 4px); }' +
    '#bookmarks li a::before                                { margin-bottom: -2px; }' +
    '#show_details                                          { margin-bottom: 0; }' +
    'body.has_audio #dir_list input                         { margin-bottom: 1px; }' +
    '#content_grid.has_image_grid                           { margin-bottom: 1rem; }' +
    '#decrease                                              { margin-left: -4px; }' +
    'th input                                               { margin-left: 2px; }' +
    'tr.media input                                         { margin-left: 7px; }' +
    '#prev_next_btns                                        { margin-left: 8px; }' +
    '#show_details, #warnings button                        { margin-left: 0.5em; }' +
    '#warnings                                              { margin-left: -12em; }' +
    '#dir_list tbody tr                                     { margin-inline-start: 0; }' +
    '#sidebar ul                                            { -webkit-margin-before: 0em !important; -webkit-margin-after: 0em !important; -webkit-padding-start:0em; }' +
    '#open_font                                             { opacity: 0.0; }' +
    '#content_pane.has_ignored::before, #close_audio::after { opacity: 0.3; }' +
    '#close_audio:hover::after                              { opacity: 0.6; }' +
    '#sidebar_menus td:last-of-type:hover > div, #bookmarks_menu_container #bookmarks_menu, #parent_dir_menu, #toggle_sidebar, #grid_btn, #toggle_info, body.use_custom_icons #dir_list tr.file.ignore a.icon::before, .split_btn span' +
                                                           '{ opacity: 0.7; }' +
    '#grid_btn:hover, #parent_dir_menu:hover, #bookmarks_menu_container:hover #bookmarks_menu, #prev_next_btns span:hover, #toggle_sidebar:hover, #grid_btn:hover, #toggle_info:hover, .split_btn span:hover' +
                                                           '{ opacity: 1.0; }' +
    '#grid_btn, #dir_list tbody, #dir_list tbody a, #audio:focus, #content_grid .font_grid_item, #content_font, #warnings button:focus, #content_video' +
                                                           '{ outline: none; }' +
    'html, body, :root, #parents_dir_menu div, #bookmarks_menu, #dir_list, #dir_list tbody a, #dir_list .details.kind, #main_content, #close_audio, .hamburger h1, .hamburger h2, .hamburger h4' +
                                                           '{ overflow: hidden; }' +
    '#dir_list tbody, #next_track, #prev_track, #content_container, #content_font, #content_grid, #font_info tbody' +
                                                           '{ overflow: auto; }' +
    '#sidebar, #content_font                                { overflow-wrap: break-word; }' +
    'html, body, :root, #main_content > thead th, #sidebar_wrapper, #sidebar ul, #sidebar_menus > td, #parent_dir_menu, #parent_dir_menu, #parent_dir_menu a, #parents_dir_menu, #bookmarks_menu, #grid_btn, #dir_list .details a, #tfoot, #title_buttons_left button, #content_pane, #reload_btn, #close_btn, #audio_container > div, #content_pdf, #content_iframe, #content_text, audio::-webkit-media-controls-panel' +
                                                           '{ padding: 0; }' +
    'div#glyphs_container, div.glyph_container, #glyph_viewer, #glyph_viewer_info div'+
                                                           '{ padding: 0 !important; }' +
    '#show_details, #prev_next_btns, #scale                 { padding-top: 0; }' +
    '#sidebar_title th, #parents_dir_menu div, #parents_dir_menu + ul li a, #grid_btn .menu li, #dir_list tbody a, #stats, #title_buttons_left, #title_buttons_right, #title, body #content_audio_title td, #content_audio td, #content_font div#glyph_viewer_info, #font_info td' +
                                                           '{ padding-top: 4px; }' +
    '#sidebar_header tbody tr:last-of-type td, #bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #bookmarks_menu + ul li div span, .menu label, #sorting .toggle_UI_pref, #sidebar_buttons td, #text_editor_row th, .image_grid_item, .hamburger h4' +
                                                           '{ padding-top: 6px; }' +
    '#content_grid .font_grid_item, .font_grid_item p, #content_font div.lorem' +
                                                           '{ padding-top: 0.5rem; }' +
    '#error_message, #warnings                              { padding-top: 1rem; }' +
    'body:not(.has_text) #content_pane.has_image:not(.has_grid) #content_container, #content_font div.specimen' +
                                                           '{ padding-top: 2rem; }' +
    '#sidebar_header tbody tr:last-of-type td               { padding-right: 0; }' +
    'div.glyph_container div.glyph_info                     { padding-right: 2px; }' +
    '#sidebar_title th, #scale                              { padding-right: 4px; }' +
    '#parents_dir_menu div, #grid_btn .menu li, #stats, #title_buttons_left, #title_buttons_right, #content_audio td, #audio_container, #content_font div#glyph_viewer_info, #font_info td, .image_grid_item' +
                                                           '{ padding-right: 6px; }' +
    '#bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #bookmarks_menu + ul li div span, .menu label, body.show_numbers #tbody tr td.name a::before, #dir_list tbody a' +
                                                           '{ padding-right: 8px; }' +
    '#parents_dir_menu + ul li a, #dir_list td.details, #title, #content_audio_title td'+
                                                           '{ padding-right: 12px; }' +
    '#content_audio_title td:before                         { padding-right: 18px; }' +
    '#grid_btn .menu                                        { padding-right: 24px; }' +
    '#error_message, #warnings                              { padding-right: 1rem; }' +
    '.font_grid_item p, .font_grid_item a                   { padding-right: 2rem; }' +
    'body:not(.has_text) #content_pane.has_image:not(.has_grid) #content_container, #font_specimen' +
                                                           '{ padding-right: 2.5rem; }' +
    '#show_details, #prev_next_btns, #scale                 { padding-bottom: 0; }' +
    'body.is_dirs_on_top #dir_list tbody tr.sorted:not(:last-of-type), div.glyph_container div.glyph_info' +
                                                           '{ padding-bottom: 2px; }' +
    '#sorting, #title, body #content_audio_title td, #title_buttons_left, #title_buttons_right' +
                                                           '{ padding-bottom: 3px;}' +
    '#sidebar_title th, #parents_dir_menu div, #parents_dir_menu + ul li a, #grid_btn .menu li, #dir_list tbody a, #sidebar .details, #content_font div#glyph_viewer_info, #font_info td' +
                                                           '{ padding-bottom: 4px; }' +
    '#sidebar_header tbody tr:last-of-type td, #parents_dir_menu + ul li:last-of-type a, #bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #bookmarks_menu + ul li div span, .menu label, body:not(.show_details) #sorting, #text_editor_row th, #dir_list tfoot td, #content_audio td, .image_grid_item' +
                                                           '{ padding-bottom: 6px; }' +
    '.hamburger h4                                          { padding-bottom: 9px; }' +
    '.specimen, .font_grid_item p, .font_grid_item a        { padding-bottom: 0.5rem; }' +
    '#error_message, #warnings                              { padding-bottom: 1rem; }' +
    'body:not(.has_text) #content_pane.has_image:not(.has_grid) #content_container, #content_font > div.specimen, #content_font .lorem:last-of-type' +
                                                           '{ padding-bottom: 2rem; }' +
    '#dir_list #tbody td.name a.icon, #dir_list td.details, #grid_btn .menu, #sidebar_header tbody tr:last-of-type td, #prev_next_btns' +
                                                           '{ padding-left: 0px; }' +
    'div.glyph_container div.glyph_info                     { padding-left: 2px; }' +
    '#sidebar_title th, #bookmarks ul li a, #dir_list .audio a, #dir_list .video a, #checkbox_div, #scale' +
                                                           '{ padding-left: 4px; }' +
    '#parents_dir_menu div, #dir_list th#name, #dir_list td.icon, #dir_list .icon + td.name a, #dir_list tfoot td:not(#toggle_info), #checkbox_div #parents_dir_menu div, #grid_btn .menu li, #title_buttons_left, #title_buttons_right, #content_audio td, #audio_container, #content_font div#glyph_viewer_info, #font_info td, .image_grid_item' +
                                                           '{ padding-left: 6px; }' +
    '#parents_dir_menu + ul a, #title, #content_audio_title td'+
                                                           '{ padding-left: 12px; }' +
    '#text_editor_row a                                     { padding-left: 18px; }' +
    '.menu label, body.has_hidden_sidebar #title_buttons_left'+
                                                           '{ padding-left: 24px; }' +
    '#dir_list #tbody tr:not(.media) a span                 { padding-left: 27px; -webkit-padding-start: 27px; }' +
    '#bookmarks .bookmarks ul li a                          { padding-left: 28px; }' +
    '#dir_list #tbody td.details.size, tr.media a.icon      { padding-left: 30px; }' +
    '#error_message, #warnings                              { padding-left: 1rem; }' +
    '.font_grid_item p, .font_grid_item a                   { padding-left: 2rem; }' +
    'body:not(.has_text) #content_pane.has_image:not(.has_grid) #content_container, #font_specimen' +
                                                           '{ padding-left: 2.5rem; }' +
    '#dir_list td.name a                                    { -webkit-padding-start: 0; }' +
    '#dir_list .icon + td.name a                            { -webkit-padding-start: 1em; }' +
    '#sidebar_wrapper, #sidebar_header, #sidebar_buttons, #sidebar_menus td:first-of-type, #grid_btn, #dir_list, body.show_numbers #tbody tr td.name a::before, #dir_list tr.ignore a, #dir_list tr.ignore.app a, #dir_list tr.ignore td.details, #bookmarks_menu + ul > li.has_submenu, #content_pane, #content_header, #content_text, .glyph_container, #content_pdf, #content_iframe, #close_audio, #content_grid div img, #content_text, .split_btn, #content_pane.has_zoom_image #content_image, #content_image img' +
                                                           '{ position: relative; }' +
    '#sidebar ul, #handle, #parent_dir_menu, #toggle_sidebar, #toggle_info, body.has_hidden_sidebar #sidebar_wrapper, #dir_list tbody, #close_audio::after, .split_btn::after, #content_container, #content_grid, #warnings, #overlay, #content_pane.has_grid #content_grid::after, .glyph_info' +
                                                           '{ position: absolute; }' +
    '#tfoot, #glyph_viewer, #font_info, #content_pane.has_image #content_image'+
                                                           '{ position: fixed; }' +
    '#parent_dir_menu, #overlay, #glyph_viewer, #content_pane.has_zoom_image #content_image, #content_image'+
                                                           '{ top: 0; right: 0; bottom: 0; left: 0; }' +
    '#dir_list, #handle, #content_pane.has_grid #content_grid::after, .split_btn::after'+
                                                           '{ top: 0; bottom: 0; }' +
    '#sidebar ul, #tbody, .glyph_info, #tfoot               { left: 0; right: 0; }' +
    '#tbody, #toggle_info, #warnings                        { top: 0 !important; }' +
    '#bookmarks_menu + ul > li > ul, #grid_btn .menu        { top: -1px !important; }' +
    'body.has_hidden_sidebar #sidebar_wrapper               { top: 2px; }' +
    '#toggle_sidebar                                        { top: 4px; }' +
    '#grid_btn .menu, #content_grid, #content_pane.has_grid #content_grid::after, #toggle_info'+
                                                           '{ right: 0; }' +
    '#handle                                                { right: -4px; }' +
    '#toggle_sidebar                                        { right: 4px; }' +
    '#dir_list tbody, #tfoot, #content_container, .glyph_info, #font_info'+
                                                           '{ bottom: 0; }' +
    'body.has_hidden_sidebar #toggle_sidebar, #content_grid { left: 0; }' +
    '#grid_btn ul.menu                                      { left: unset; }' +
    'body.has_hidden_sidebar #sidebar_wrapper               { left: 3px; }' +
    'body.show_numbers #tbody tr td.name a::before          { left: 6px; }' +
    '#warnings, .split_btn::after                           { left: 50%; }' +
    '#bookmarks_menu + ul > li > ul                         { left: 100%; }' +
    '#sidebar ul, #dir_list tbody, #sort_by_name, #sort_by_size, #text_editor_row, #dir_list tbody .name, #dir_list tr.details, #title_buttons_left, #warnings' +
                                                           '{ text-align: left; }' +
    '#parent_dir_menu a, #parents_dir_menu, #parents_dir_menu div, #bookmarks_menu div, #content_header, #content_title, #content_audio_title, #content_audio td, .glyph_container, #glyph_viewer_info, #content_image' +
                                                           '{ text-align: center; }' +
    '#grid_btn .menu li, body.show_numbers #tbody tr td.name a::before, #sort_by_default, #sort_by_ext, #dir_list .size, #dir_list .date, #dir_list .kind, #title_buttons_right, #warnings div, .playlist_time, #font_info td:first-of-type' +
                                                           '{ text-align: right; }' +
    'a, a:hover                                             { text-decoration: none !important; }' +
    '#bookmarks .bookmarks ul li a                          { text-indent: -24px; }' +
    '#dir_list .details.kind                                { text-overflow: ellipsis; }' +
    '#dir_list, #content_pane                               { transform: scale(1); }' + // needed to establish #dir_list as containing block for thead and tfoot position fixed.
    'body.has_hidden_sidebar #toggle_sidebar, #sorting div.up span::after, #prev_track, #toggle_info' +
                                                           '{ transform:rotate(180deg) !important; }' +
    '#sidebar_header, #content_pane:not(.has_zoom_image) #content_image' +
                                                           '{ user-select:none; -webkit-user-select:none; }' +
    '#content_pane, #title_buttons_left, #title_buttons_right, #title'+
                                                           '{ vertical-align:top; }' +
    '#content_pane:not(.has_grid) #content_grid             { visibility:hidden; }' +
    '#sidebar_header tbody tr:last-of-type td, #parents_dir_menu div, #parents_dir_menu + ul li a, #bookmarks_menu + ul li a, #bookmarks_menu + ul li > span, #dir_list tbody a, .specimen, .lorem' +
                                                           '{ white-space: normal; }' +
    '#sorting span, #tbody td:not(.name), #grid_btn .menu li, .hamburger h1, .hamburger h2, .hamburger h4' +
                                                           '{ white-space: pre; }' +
    'html, body, :root, table, #parent_dir_menu a, #tbody, #tbody tr, #bookmarks_menu + ul > li > ul, #grid_btn .menu li, #content_container, #content_header, #content_grid, #content_text, #content_font svg, #content_pdf, #content_iframe, #content_grid img[src$=".svg"]' +
                                                           '{ width: 100%; }' +
    '#sidebar_menus td:nth-of-type(2), #dir_list .date, #title, #content_pane:not(.has_zoom_image) #content_image img, #content_grid img' +
                                                           '{ width: auto; }' +
    '.split_btn span                                        { width: 2em; }' +
    '#content_pane.has_grid #content_grid::after, .split_btn::after' +
                                                           '{ width: 1px; }' +
    '#handle                                                { width: 8px; }' +
    '#sorting div span::before, #sorting div span::after, #toggle_sidebar, #toggle_info' +
                                                           '{ width: 18px; }' +
    '#sidebar_menus td:nth-of-type(odd), #bookmarks li a::before, #bookmarks li > span::before, #sort_menu span::before, #preview_text_menu_item span::before, #grid_btn'+
                                                           '{ width: 24px; }' +
    '#warnings h3::before                                   { width: 32px; }' +
    '#prev_track, #next_track, #close_audio                 { width: 2rem; }' +
    '#content_pane:not(.has_image) #title_buttons_left, #content_pane:not(.has_image) #title_buttons_right, #content_pane:not(.has_zoom_image) #title_buttons_left, #content_pane:not(.has_zoom_image) #title_buttons_right' +
                                                           '{ width: 4rem; }' +
    '#bookmarks_menu div, #checkbox_div                     { width: 6em; }' +
    '#content_pane.has_image #title_buttons_left, #content_pane.has_image #title_buttons_right, #content_pane.has_zoom_image #title_buttons_left, #content_pane.has_zoom_image #title_buttons_right, #content_pane.has_grid #title_buttons_left, #content_pane.has_grid #title_buttons_right, #content_pane.has_font #title_buttons_left, #content_pane.has_font #title_buttons_right' +
                                                           '{ width: 9.5em; }' +
    '#warnings                                              { width: 26em; }' +
    'body.has_hidden_sidebar #sidebar_wrapper, .menu input  { width: 0 !important; }' +
    '#reload_btn, #close_btn                                { width: 52px; }' +
    '#font_info td:first-of-type                            { width: 33.33%; }' +
    '#font_info td:last-of-type                             { width: 66.66%; }' +
    'body.has_hidden_sidebar #content_pane, #font_info      { width: 100% !important; }' +
    'body:not(.has_hidden_sidebar) #sidebar_wrapper         { width:'+ getQuery('width').toString() +'%; }' +
    'body:not(.has_hidden_sidebar) #content_pane            { width:'+ (100 - getQuery('width')).toString() +'%; }' +
    '#content_video                                         { width: calc(100% - 2rem); }' +
    'html, body, :root                                      { max-width: 100%; }' +
    '#content_pane:not(.has_zoom_image) #content_image img  { max-width: calc(100% - 5rem); }' +
    '!#content_pane.has_zoom_image #content_image img       { max-width: none; }' +
    '#sidebar_menus td:nth-of-type(odd)                     { max-width: 24px; }' +
    '#content_grid img                                      { max-width:'+ ($settings.grid_image_size).toString() +'px; }' +
    'body.show_numbers #tbody tr td.name a::before          { min-width: 17px; }' +
    'body:not(.has_hidden_sidebar) #sidebar_menus td:nth-of-type(odd)'+
                                                           '{ min-width: 24px; }' +
    'body:not(.has_hidden_sidebar) #dir_list                { min-width: 100px; }' +
    'body:not(.has_hidden_sidebar) #sidebar_wrapper         { min-width: 220px; }' +
    '#sidebar_wrapper, #content_pane                        { will-change: width }' +
    '#content_header td button                              { word-break: none; }' +
    '#title                                                 { word-break: break-word; }' +
    '#content_pane                                          { z-index: 0; }' +
    '#handle, #sidebar_wrapper, #glyph_viewer, #font_info   { z-index: 1; }' +
    '#parents_dir_menu + ul, #content_header                { z-index: 2; }' +
    '#sidebar_header                                        { z-index: 3; }' +
    '#toggle_sidebar, #grid_btn                             { z-index: 9997; }' +
    '#overlay, #bookmarks                                   { z-index: 9998; }' +
    '#warnings                                              { z-index: 9999; }' +
    'body.has_hidden_sidebar #sidebar_header                { z-index:unset; }'
    ;
    // Gecko Styles:
	const $gecko_style_rules =
        'html, body.is_gecko                                { border: solid 1px gray !important; }' +
        'body.is_gecko button                               { padding:revert; }' +
        'body.is_gecko #grid_btn .menu                      { top:-7px; left:-120px; }' +
        'body.is_gecko thead                                { font-size:100%; }' +
        'body.is_gecko #dir_list .dir::before               { position:absolute; }' +
        'body.is_gecko.use_default_icons:not(.is_converted_list) #dir_list .file .name .icon'+
                                                           '{ padding-left:4px; background:none; }' +
        'body.is_gecko.use_default_icons #dir_list .file .name .icon img'+
                                                           '{ margin-right:6px; height:14px; }' +
        'body.is_gecko #tbody > tr > td:not(:first-of-type) { float:left }' +
        'body.is_gecko #content_audio_title td              { padding-top: 6px; }' +
        'body.is_gecko #content_audio_title td              { padding-bottom: 0; }' +
        'body.is_gecko #audio, body.is_gecko #audio_container { background-color: transparent; }'
    ;
	var $text_editing_style_rules =
        'html, body, #iframe_body                           { margin:0; padding:0; }' +
        // toolbar
        '#toolbar                                           { margin:0; padding:0; height:32px; display:block; position:relative; left:0; right:0; z-index:100; background:#EEE; border:0; border-bottom: solid 1px #999; font-family:'+ $settings.UI_font +'; font-size:'+ parseFloat($settings.UI_font_size) * 0.875 + $settings.UI_font_size.replace(/\d*/,'') +'; -webkit-user-select: none; -moz-user-select: none; user-select:none; }' +
        '#toolbar li                                        { margin:4px; padding:4px; width:3.5em; display:block; opacity:0.5; list-style-type:none; cursor:pointer; }' +
        '#toolbar li:hover, .preview_text:not(.split) #toolbar li#show_preview, body.source_text #show_source, .split_view #toolbar li#toggle_split, .edited #save_btn'+
                                                           '{ opacity:1; }' +
        '#toolbar li#toggle_split                           { float:left; width:16px; height: 16px; margin: 4px 0 4px 4px; background:url("data:image/svg+xml;utf8,<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'  width=\'16px\' height=\'16px\' viewBox=\'0 0 16 16\' enable-background=\'new 0 0 16 16\' xml:space=\'preserve\'><path fill=\'%23333333\' d=\'M0,0v16h16V0H0z M15,15H8.5V1H15V15z M7.5,15H1V1h6.5V15z\'/></svg>") center no-repeat; }' +
        '#toolbar li#sync_scroll                            { width:8em; float:left; opacity:1; }' +
        '#toolbar li#sync_scroll input                      { float:left; }' +
        '#toolbar li#sync_scroll label                      { width:8em; display:block; font-size:inherit; line-height:1.5; }' +
        '#toolbar li#clear_text                             { height:16px; float:right; text-align:center; }' +
        '#toolbar li#save_btn                               { float:right; width:20px; height:16px; background: url("data:image/svg+xml;utf8,<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'  width=\'16px\' height=\'16px\' viewBox=\'0 0 16 16\' enable-background=\'new 0 0 16 16\' xml:space=\'preserve\'><g> <path fill=\'%23333333\' d=\'M16,0v10.02h-1.33V1.33H1.33v8.69H0V0H16z\'/> <path fill=\'%23333333\' d=\'M8.47,16h-0.7l-3.08-3.08l0.94-0.94l1.83,1.83V4.28h1.33v9.53l1.81-1.82l0.94,0.93L8.47,16z\'/></g></svg>") 8px 4px no-repeat; position:relative; }' +
        '#toolbar li#show_source                            { float:left; width:16px; height: 16px; margin: 4px 0 4px 12px; background:url("data:image/svg+xml;utf8,<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'  width=\'42px\' height=\'16px\' viewBox=\'0 0 42 16\' enable-background=\'new 0 0 42 16\' xml:space=\'preserve\'><g> <path fill=\'%23333333\' d=\'M0.08,7.02L5.94,3.9l0.43,0.78L1.18,7.42l5.19,2.74l-0.43,0.78L0.08,7.82V7.02z\'/> <path fill=\'%23333333\' d=\'M7.84,16.01H6.82L13.78,0h1.02L7.84,16.01z\'/> <path fill=\'%23444444\' d=\'M21.75,7.87l-5.86,3.12l-0.43-0.78l5.19-2.74l-5.19-2.74l0.43-0.78l5.86,3.12V7.87z\'/> <path fill=\'%23333333\' d=\'M30.98,2.65h-3.63V1.58h8.55v1.07h-3.63v9.65h-1.28V2.65z\'/> <path fill=\'%23333333\' d=\'M36.38,4.71h1.3l0.42-2h0.8v2h2.45v0.99h-2.45v4.63c0,0.74,0.27,1.15,0.96,1.15c0.43,0,1.09-0.21,1.39-0.35  l0.18,0.95c-0.42,0.26-1.18,0.45-1.81,0.45c-1.36,0-1.94-0.7-1.94-2.19V5.71h-1.3V4.71z\'/></g></svg>") left 5px no-repeat; }' +
        '#toolbar li#show_preview                           { float:left; width:16px; height: 16px; margin: 4px 0 4px 4px; background:url("data:image/svg+xml;utf8,<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'  width=\'42px\' height=\'16px\' viewBox=\'0 0 42 16\' enable-background=\'new 0 0 42 16\' xml:space=\'preserve\'><g> <path fill=\'%23333333\' d=\'M0.08,7.02L5.94,3.9l0.43,0.78L1.18,7.42l5.19,2.74l-0.43,0.78L0.08,7.82V7.02z\'/> <path fill=\'%23333333\' d=\'M7.84,16.01H6.82L13.78,0h1.02L7.84,16.01z\'/> <path fill=\'%23444444\' d=\'M21.75,7.87l-5.86,3.12l-0.43-0.78l5.19-2.74l-5.19-2.74l0.43-0.78l5.86,3.12V7.87z\'/> <path fill=\'%23333333\' d=\'M30.98,2.65h-3.63V1.58h8.55v1.07h-3.63v9.65h-1.28V2.65z\'/> <path fill=\'%23333333\' d=\'M36.38,4.71h1.3l0.42-2h0.8v2h2.45v0.99h-2.45v4.63c0,0.74,0.27,1.15,0.96,1.15c0.43,0,1.09-0.21,1.39-0.35  l0.18,0.95c-0.42,0.26-1.18,0.45-1.81,0.45c-1.36,0-1.94-0.7-1.94-2.19V5.71h-1.3V4.71z\'/></g></svg>") -24px 5px no-repeat; }' +
        '.edited #toolbar li#save_btn                       { background: url("data:image/svg+xml;utf8,<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'  width=\'16px\' height=\'16px\' viewBox=\'0 0 16 16\' enable-background=\'new 0 0 16 16\' xml:space=\'preserve\'><g> <path fill=\'%23DD2222\' d=\'M16,0v10.02h-1.33V1.33H1.33v8.69H0V0H16z\'/> <path fill=\'%23DD2222\' d=\'M8.47,16h-0.7l-3.08-3.08l0.94-0.94l1.83,1.83V4.28h1.33v9.53l1.81-1.82l0.94,0.93L8.47,16z\'/></g></svg>") 8px 4px no-repeat; position:relative; }' +
        '#toolbar li#save_btn div                           { display:none; position:relative; top:-9px; left:-24px; color:#999; text-align:right; }' +
        '#toolbar li#save_btn:hover div                     { display:block; }' +
        '#toolbar li#save_btn span                          { width:6rem; padding:4px 6px; background: #EEE; float:right; display:block; border:solid 1px #999; position:relative; z-index:1; }' +
        '#toolbar li#save_btn span:first-of-type            { border-bottom-width:0px; }' +
        '#toolbar li#save_btn span:hover                    { color:#444; }' +
        // resize handle
        '.split_view #text_editing_handle                   { width:9px; position:absolute; top:0; bottom:0; left:calc(50% - 4px); cursor:col-resize; z-index:11; }' +
        '#text_editing_handle                               { z-index:-1; }' +
        // source
        '#content_source                                    { margin:0; padding: 14px; width:100%; height:calc(100% - 32px); display:block; line-height:1.2; box-sizing:border-box; z-index:1; border:0; overflow-y:scroll;  background:#EEE; resize:none; font-family:monospace; font-size:'+ parseFloat($settings.UI_font_size) + $settings.UI_font_size.replace(/\d*/,'') +'; }' +
        '#content_source, #content_preview                  { position:absolute; top:32px; right:0; bottom:0; left:0; }' +
        '#content_source:focus                              { outline:none; background:#FFF; box-shadow: inset 0 0 4px #888; }' +
        // preview
        '#content_preview                                   { margin:0; padding: 14px; box-sizing:border-box; z-index:1; border:0; overflow-y:scroll; background:#FFF; font-size:'+ parseFloat($settings.UI_font_size) + $settings.UI_font_size.replace(/\d*/,'') +'; }' +
        // split views
        '.preview_text:not(.split_view) #content_source, .source_text:not(.split_view) #content_preview, li#save_btn div, .comment'+
                                                           '{ display:none; }' +
        '.split_view #content_preview                       { border-left:solid 1px #999; }' +
        '.split_view #content_source                        { width:50%; }' +
        '.split_view #content_preview                       { left:50%; }' +
        // preview styles
        '#content_preview pre                               { border:solid 1px #CCC; border-radius:3px; white-space:pre-wrap; word-break:break-word; font-size:'+ parseFloat($settings.UI_font_size) + $settings.UI_font_size.replace(/\d*/,'') +'; }' +
        '#content_preview .no_list                          { list-style:none; }' +
        '#content_preview > .no_list                        { padding:0; }' +
        '#content_preview .text-align-center                { text-align:center; }' +
        '#content_preview th, #content_preview td           { vertical-align:top; }' +
        '#content_preview blockquote                        { margin-top:1em; margin-bottom:1em; color: #555; }' +
        '#content_preview blockquote + blockquote           { margin-top:0; }' +
        '.markdown-body input[type="checkbox"]              { margin-top:0.375em; margin-right:6px; float:left; }' +
        'h1 .uplink,h2 .uplink,h3 .uplink,h4 .uplink,h5 .uplink,h6 .uplink'+
                                                           '{ margin:0; padding:0; display:inline-block; font-size:0.875em; cursor:pointer; transition: opacity 0.25s; opacity:0; }' +
        'h1:hover .uplink,h2:hover .uplink,h3:hover .uplink,h4:hover .uplink,h5:hover .uplink,h6:hover .uplink'+
                                                           '{ transition: opacity 0.25s; opacity:0.5; }' +
        '#content_preview table                             { font-size:inherit; }' +
        '#content_preview table th                          { background-color:#EEE; }' +
        '.markdown-body::before, .markdown-body::after      { display:none !important; background:transparent; }' +
        // edited warning
        '#iframe_body #warnings p, #iframe_body #warnings button { display:none; }' +
        '#iframe_body #warnings                             { width:22em; margin-left:-12.5em; padding:1rem; font-size:0.75rem; border-radius:0 0 3px 3px; display:none; position:absolute; top:0; left:50%; z-index:9999; background:#EEE; box-shadow: 0px 2px 12px 0 #111; }' +
        '#iframe_body #warnings h3                          { margin:0; font-weight:normal; }' +
        '#iframe_body #warnings div                         { text-align:right; }' +
        '#iframe_body #warnings button                      { margin-left:0.5em; }' +
        '#iframe_body #warnings #warning_ignore_btn         { margin-right:2em; }' +
        '#iframe_body.has_warning #warnings, #iframe_body.has_warning #warnings.unsaved p#warning_unsaved, #iframe_body.has_warning #warnings.clear p#warning_clear'+
                                                           '{ display:block; }' +
        '#iframe_body.has_warning #warnings.clear #warning_clear_btn, #iframe_body.has_warning #warnings.clear #warning_cancel_btn, #iframe_body.has_warning #warnings.unloading p#warning_unsaved, #iframe_body.has_warning #warnings.unloading #warning_ignore_btn, #iframe_body.has_warning #warnings.unloading #warning_cancel_btn, #iframe_body.has_warning #warnings.unloading #warning_save_btn'+
                                                           '{ display:inline-block; }' +
        // disabled text editing
        '#iframe_body.enable_text_editing #toolbar, #iframe_body.enable_text_editing #preview_text, #iframe_body.enable_text_editing #text_editing_handle'+
                                                           '{ display:none; }' +
        '#iframe_body.enable_text_editing #content_source.disabled'+
                                                           '{ top:0; background:white; }'
    ;
	var $iframe_styles =
        '#iframe_body a.up, #iframe_body #dir_list          { background: transparent; }' +
        '#iframe_body :root, html, body                     { background-color: #BBB; }' +
        '#iframe_body #thead, #tbody tr                     { background-color: rgba(221,221,221,0.5); }' +
        '#iframe_body #thead tr#parent                      { background-color: rgba(144,144,144,0.33); }' +
        '#iframe_body #tbody tr:nth-of-type(odd)            { background-color: rgba(221,221,221,1); }' +
        '#iframe_body #tbody tr:not(.media):hover           { background-color: rgba(172,202,235,0.75) !important; }' +
        '#iframe_body #tbody tr.media:hover                 { background-color: rgba(116,190,190,0.5) !important; }' +
        '#iframe_body #dir_list tr td.name a::before        { content:""; width:14px; height:14px; margin-right:4px; bottom:-1px; background-position:center; background-repeat:no-repeat; background-size:contain; }' +
         CSS_UI_Icon_Rules('#iframe_body') + // background icons
        '#iframe_body #dir_list.sort_by_default #sort_by_default span::before, #iframe_body #dir_list.sort_by_name #sort_by_name span::before, #iframe_body #dir_list.sort_by_size #sort_by_size span::before, #iframe_body #dir_list.sort_by_date #sort_by_date span::before, #iframe_body #dir_list.sort_by_kind #sort_by_kind span::before, #iframe_body #dir_list.sort_by_ext #sort_by_ext span::before'+
                                                           '{ background-image:'+ SVG_UI_Icon('check_mark') +'; background-repeat: no-repeat; background-size:10px; background-position: center; }' +
        '#iframe_body #dir_list.sort_by_default #sort_by_default span::after, #iframe_body #dir_list.sort_by_name #sort_by_name span::after, #iframe_body #dir_list.sort_by_size #sort_by_size span::after, #iframe_body #dir_list.sort_by_date #sort_by_date span::after, #iframe_body #dir_list.sort_by_kind #sort_by_kind span::after, #iframe_body #dir_list.sort_by_ext #sort_by_ext span::after'+
                                                           '{ background-image:'+ SVG_UI_Icon('chevron_up') +'; background-repeat: no-repeat; background-size:10px; background-position: center; }' +
        '#iframe_body .sorting.down span::after             { transform:rotate(180deg) }' +
        ':root, html, #iframe_body                          { border:0 !important; }' + // border
        'html, #iframe_body                                 { border-radius:0; }' +
        '#iframe_body #dir_list                             { border-collapse:collapse; }' +
        '#iframe_body #dir_list thead th                    { border-bottom:solid 1px #999; }' +
        '#iframe_body, iframe_body td.name, iframe_body td.details'+
                                                           '{ box-sizing:border-box; }' + // box-sizing
        '#iframe_body a                                     { color:#111111; }' + // color
        '#iframe_body a:hover                               { color:#000000; }' +
        '#iframe_body tr.ignore, #iframe_body tr.ignore a   { color:grey; }' +
        '.sorting span::before,.sorting span::after         { content:""; width:16px; height:8px; display:inline-block; position:relative; }' +// content
        '#iframe_body tbody                                 { counter-reset: row; }' + // counter
        '#iframe_body.show_numbers tr td.name::before       { counter-increment: row;  content:counter(row); margin-right:6px; min-width:1.25em; text-align:right;}' +
        '#iframe_body #dir_list td.name::before, #iframe_body #dir_list a::before, td.size, td.date'+
                                                           '{font-variant-numeric: tabular-nums; }'+
        '#iframe_body #dir_list th.sorting                  { cursor: pointer; }' + // cursor
        '#iframe_body #dir_list tr::before, #iframe_body #dir_list td.name input, #iframe_body td.ext'+
                                                           '{ display:none; }' + // display
        '#iframe_body a                                     { display:block; }' +
        '#parent + tr                                       { display: grid; grid-gap:0; grid-template-columns: 50% 50%; }' +
        '#iframe_body #dir_list #tbody tr, #sorting_row     { display: grid; grid-gap:0; grid-template-columns: minmax(200px,100%) minmax(auto,6em) minmax(auto,14em) minmax(auto,7em); }' +
        '#iframe_body td.name, #iframe_body #sort_by_name, #iframe_body #sort_by_ext'+
                                                           '{ grid-column: 1; }' +
        '#iframe_body td.size, #iframe_body #sort_by_default, #iframe_body #sort_by_size'+
                                                           '{ grid-column: 2; }' +
        '#iframe_body td.date, #iframe_body #sort_by_date   { grid-column: 3; }' +
        '#iframe_body td.kind, #iframe_body #sort_by_kind   { grid-column: 4; }' +
        '#iframe_body #dir_list td.name::before, #iframe_body #dir_list a::before'+
                                                           '{ float:left; }' + // float
        '#iframe_body                                       { font-family:'+ $settings.UI_font +'; }' + // fonts
        '#iframe_body                                       { font-size:'+ parseFloat($settings.UI_font_size) * 0.875 + $settings.UI_font_size.replace(/\d*/,'') +'; }' +
        '#iframe_body #dir_list, #iframe_body #thead        { font-size: 1em; }' +
        'td.name, td.name a::before, td.size, td.date       { font-variant-numeric: tabular-nums; }'+
        '#iframe_body, #iframe_body #dir_list               { height:100%; }' + // height
        '#iframe_body #content_source                       { height:inherit; }' +
        '#iframe_body #thead                                { height:2em; max-height:2em; }' +
        '#iframe_body #tbody tr                             { line-height:1.5; }' + // line-height
        'html, body, #iframe_body                           { margin:0; }' + // margin
        '#iframe_body .dir::before, #iframe_body .file > img{ margin-inline-end: 6px; }' +
        '#iframe_body #dir_list tr, #iframe_body #tbody tr:hover { outline:0; }' + // outline
        '#iframe_body, #iframe_body #dir_list, .details.date, .details.kind'+
                                                           '{ overflow:hidden; text-overflow: ellipsis; }' + // overflow
        '#iframe_body #dir_list #tbody                      { overflow:auto; }' +
        'html, :root, #iframe_body, body                    { padding:0; }' + // padding
        '#iframe_body #tbody tr td, #iframe_body #thead tr th { padding-top:3px; }' +
        '#iframe_body #tbody tr td                          { padding-right: 6px; }' +
        '#iframe_body #tbody tr td, #iframe_body #thead tr th { padding-bottom:3px; }' +
        '#parent th, #iframe_body #tbody tr td.details.kind { padding-right: 1em; }' +
        '#iframe_body td.details                            { padding-left: 6px; }' +
        '#parent th, #tbody tr td.name                      { padding-left:1em; }' +
        '#iframe_body #dir_list, #iframe_body #dir_list tr td.name a::before'+
                                                           '{ position:relative; }' + // position
        '#iframe_body, #iframe_body #dir_list #tbody        { position:absolute; right:0; bottom:0; left:0; }' +
        '#iframe_body th                                    { text-align:center; }' + // text-align
        '#iframe_body th:last-of-type, #iframe_body td.details { text-align:right; }' +
        '#iframe_body th:first-of-type                      { text-align:left; }' +
        '#iframe_body a, #iframe_body a:hover, #iframe_body td:hover'+
                                                           '{ text-decoration:none !important; }' + // text-decoration
        '#iframe_body a.icon                                { text-indent:2px; }' + // text-indent
        '#iframe_body #thead                                { user-select:none; -webkit-user-select:none; }' +
        '#iframe_body td.details                            { vertical-align:top; }' +
        'html, #iframe_body, #iframe_body #dir_list, #iframe_body #dir_list tr'+
                                                           '{ width:100%; max-width:100%; min-width:100%; }' +
        '#iframe_body #dir_list td:not(:first-child)        { width:unset; }' +
        '#iframe_body td:not(.name) { white-space:pre; }'
    ;

    // ADD STYLES
	const $font_styles = document.createElement('style');
	const $font_grid_styles = document.createElement('style');

	function addStyles(el) {
		el.find('style, link[rel="stylesheet"], link[href$="css"]').remove(); // remove any existing stylesheets
		el.append('<style>'+ $main_style_rules +'</style>');
		el.append('<style>'+ $gecko_style_rules +'</style>');
		el.append($font_styles); // empty until font is previewed
		el.append($font_grid_styles); // empty until font grid is made
		el.append('<style>'+ $text_editing_style_rules +'</style>');
		el.append('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css"></link>');
	}
	// ***** END STYLES ***** //

    // ***** INDEX PREP ***** //
    //
    function getIndexType() {
        // Try to determine index type from parent directory link container,
        // with fallbacks for indexes that don't have parent directories,
        // or for parent directory links that aren't siblings or ancestors of the index itself.
        let parentLinkParent; // Possible elements: pre, li, td, th, div -- used to determine index type
        // Try to find parent directory link:
        let parentLink = $('a:contains("Parent Directory"), a:contains("parent directory"), a[href="../"], a[href="/"], a[href^="?"], img[alt*="PARENTDIR"]');
        if ( parentLink.length === 0 ) {
            parentLinkParent = $('body').find('> ul li, > pre, > table:last-of-type tr td');
        } else {
            parentLinkParent = parentLink.parent(); // use original found parentLink
        }
        // If no parentLinkParent found, type = error; else return parent node name
        let nodeName = ( parentLinkParent[0] !== undefined ? parentLinkParent[0].nodeName.toLowerCase() : '');
        if ( parentLinkParent.length === 0 ) {
            nodeName = 'error';
        } else if ( $protocol.startsWith('file') ) {
            if ( navigator.userAgent.indexOf('Firefox') > 0 ) {
                nodeName = 'gecko';
            }
        }
        let types = {'gecko':'gecko','li':'list','pre':'pre','th':'table','td':'table','div':'default','error':'error'};
        let type = types[nodeName];

        if ( type === 'table' ) {
            parentLinkParent.closest('table').addClass('PARENTTABLE');
        }
        if ( type === 'list' ) {
            parentLink.closest('ul').addClass('PARENTLIST');
        }
        return type;
    }

    // Return Index items, Index type, remove parent directory link, and add body class.
    function getIndexItems(el) {
        const type = getIndexType();
        let items;

        switch(type) {
            case 'gecko':
                $(el).addClass('is_converted_gecko');
                items = $('body').find('> table > tbody');
                break;
            case 'list':
                $(el).addClass('is_converted_list');
                items = $('body').find('> ul');
                break;
            case 'pre':
                $(el).addClass('is_converted_pre');
                items = $('body').find('> pre').html();
                break;
            case 'table':
            case 'td':
                $(el).addClass('is_converted_table');
                if ( $('table.PARENTTABLE > tbody').length === 1 ) {
                    items = $('table.PARENTTABLE > tbody');
                } else {
                    items = $('table.PARENTTABLE'); // tables without tbody
                }
                break;
            case 'default': // local chrome default
                $(el).addClass('is_default');
                items = $('body').find('> table').find('> tbody');
                break;
            case 'error': // error
                $(el).addClass('is_error');
                items = $('body').html();
                break;
        }
        return [items,type];
    }

	// Index Prep: convert rows and return array of rows, with link, size, date-modified
	function convertIndexItems(type,items) {
		let converted = [];
		switch(type) {
            case 'gecko':
                converted = convertGeckoType(items);
                break;
            case 'list':
                converted = convertListType(items);
                break;
            case 'pre':
                converted = convertPreType(items);
                break;
            case 'table':
            case 'default': // local chrome indexes
                converted = convertTableType(type,items);
                break;
            case 'error':
                converted = convertErrorType(items);
                break;
        }
        return converted;
	}
	// Index Prep: convert list type function
	function convertGeckoType(items) {
		let preppedIndex = [];
        const rows = Array.from(items.find('> tr'));
		for ( let row of rows ) {
			let preppedRow = [];
            let cellContents = '';
            let cells = Array.from( $(row).find('> td') );
            let link = ($(cells).find('a').attr('href'));
            for ( let cell of cells ) {
                cellContents = cell.innerText;
                cellContents = ( cellContents !== undefined ? cellContents.trim() : '');
                preppedRow.push(cellContents);
            }
            preppedRow[1] = preppedRow[1].replace(' KB','000'); // convert reported size in KB to total bytes
            preppedRow[2] = preppedRow[2] + ' '+ preppedRow[3];
            preppedRow = preppedRow.slice(1,-1);
            if ( link.length > 0 && link !== '/' && link !== '../' ) {
                preppedRow.unshift(link);
            }
            if ( preppedRow.length > 0 ) { preppedIndex.push(preppedRow); }
        }
        return preppedIndex;
	}
	// Index Prep: convert list type function
	function convertListType(items) {
		  let preppedIndex = [];
		const rows = Array.from(items.find('li'));
        for ( let row of rows ) {
            if ( row.innerHTML.indexOf('Parent Directory') === -1 ) {
                let preppedRow = [];
                let link = $(row).find('a').attr('href');
                    row = row.innerHTML.replace(/<a .+?<\/a>\s*/,'');
                let cells = row.split(' ');
                for ( let cell of cells ) {
                    if ( cell.trim().length > 0 ) {
                        preppedRow.push(cell);
                    }
                }
                if ( link.length > 0 && link !== '/' && link !== '../' ) {
                    preppedRow.unshift(link);
                }
                if ( preppedRow.length > 0 ) {
                    preppedIndex.push(preppedRow);
                }
            }
        }
        return preppedIndex;
	}
	// Index Prep: convert pre type function
	function convertPreType(items) {
        let preppedIndex = [];
        items = items.replace(/<a /g,'  <a ').replace(/<\/a>/g,'</a>  ') // ensure two spaces after file links
                     .replace(/\[\s*?\]/g,'[]'); // remove empty 'alt=[   ]'
        const rows = items.split('\n');
        const spaces = /\s{2,}/; // assumes pre type only uses spaces between "columns"

        for ( let row of rows ) {
            let preppedRow = [];
                row = row.replace(/(<a[^>]+?>).+?<\/a>/g,'$1'); // remove link display name because some have 2+ spaces, leading to incorrect split for cells array
            let cells = row.split(spaces);
            let link;
            for ( let cell of cells ) {
                if ( cell.trim().length > 0 ) {
                    if ( cell.indexOf('href="') > 0 && cell.search(/href="[?|\/"]|Parent Directory/) === -1 ) {
                        link = $(cell).attr('href');
                    } else {
                        if ( cell.search(/href="|<img |<hr>/) === -1 ) {
                            preppedRow.push(cell);
                        }
                    }
                }
            }
            if ( link !== undefined ) { preppedRow.unshift(link); } // add link to front of preppedRow
            if ( preppedRow.length > 1 ) { preppedIndex.push(preppedRow); }
        }
		return preppedIndex;
	}
	// Index Prep: convert table type function
	function convertTableType(type,items) { // for local chrome indexes and server-generated table-type indexes
		  let preppedIndex = [];
        const rows = Array.from(items.find('> tr:not(.PARENT)'));
        for ( let row of rows ) {
            if (row.innerText.search(/Parent Directory/) === -1 ) {
                let preppedRow = [];
                let cells = Array.from( $(row).find('td') );
                let link = $(cells).find('a').attr('href');
                for ( let cell of cells ) {
                    cell = cell.innerHTML.trim();
                    if ( cell.length > 0 && cell.search(/^&nbsp;$|href="|<img /m) === -1 ) {
                        preppedRow.push( cell );
                    }
                }
                if ( link !== undefined ) { preppedRow.unshift(link); }
                if ( preppedRow.length > 1 ) { preppedIndex.push(preppedRow); } // preppedRow.length > 2 in order to omit parent directory row
            }
        }
		return preppedIndex;
	}
	// Index Prep: convert error pages (page not found, etc.)
	function convertErrorType(items) {
		items = items.replace(/ style="[^"]*?"/g,'').replace(/<hr>/g,'');
		items = '<div id="error_message"><div id="error_message_icon"></div>'+ items +'</div>';
		return items;
	}

    // Index Prep: Build new Index from prepped rows
	function buildNewIndex(preppedIndex,sort) {
		let newIndexItems = [];
        let i = 0;
		for ( let row of preppedIndex ) {
			// Get row attrs and text
			const rowLink =       row[0] !== undefined ? row[0].replace(/&amp;/g,'&') : '';//.replace(//,''); // decode some reserved characters
			const rowName =       getItemName(rowLink).replace(/^\s/m,'\&nbsp;').replace(/^\//m,'').replace(/([-_——])/g,'$1<wbr>'); // display name, with word breaks added after unbreakable chars
			const rowSortName =   getItemName(rowLink).replace(/^\//m,'').replace('/','').toLocaleLowerCase();
			const sizesAndDates = getItemSizeAndDate(row);
			const rowSize =       sizesAndDates[0];
			const rowSortSize =   sizesAndDates[1];
			const rowDate =       sizesAndDates[2];
			const rowSortDate =   sizesAndDates[3];
			const rowExt =        getItemExt(rowLink);
			const rowSortKind =   getItemKind(rowExt);
			const rowKind =       rowSortKind.slice(0,1).toUpperCase() + rowSortKind.slice(1);
			const rowClasses =    getItemClasses(rowName,rowSortKind,rowExt);
            // Assemble row elements
              let newRow =   $('<tr></tr>').attr('id','rowid-'+ i).addClass(rowClasses).attr('data-kind',rowSortKind).attr('data-ext',rowExt);
			const checkbox = ( rowClasses.indexOf('media') > 0 ? $('<input type="checkbox" tabindex="-1" checked="true" />') : '' );
            const nameSpan = $('<span></span>').append(checkbox, rowName);
			const cellLink = $('<a></a>').addClass('icon').attr('href',rowLink).append(nameSpan);
			const cellName = $('<td></td>').addClass('name').attr('data-name',rowSortName).append(cellLink);
			const cellSize = $('<td></td>').addClass('size details').attr('data-size',rowSortSize).append(rowSize);
			const cellDate = $('<td></td>').addClass('date details').attr('data-date',rowSortDate).append(rowDate);
			const cellKind = $('<td></td>').addClass('kind details').attr('data-kind',rowSortKind).append(rowKind);
			const cellExt =  $('<td></td>').addClass('ext details').attr('data-ext',rowExt);
			// Assemble row
			      newRow.append(cellName, cellSize, cellDate, cellKind, cellExt);
			      newIndexItems.push(newRow[0]);
                  i++;
		}
        if ( sort === undefined ) { sort = getQuery('sort_by'); }
		let sortedIndexItems = sortDirList($(newIndexItems), 'sort_by_'+ sort, 1); // initial sort
		return sortedIndexItems;
	}
	// Index Prep: get row name
	function getItemName(link) {
          let name;
          try { name = decodeURIComponentSafe(link); }
        catch (error) { name = link.replace(/%20/g,' ').replace(/\s{2,}/,' '); }

		if ( name.split('/').length > 2 ) { // get name only if x = full path
			let arr = name.split('/');
			if ( name.startsWith('/') && name.endsWith('/') ) { // dirs
				name = arr[arr.length - 2] + '/';
			} else {
				name = arr[arr.length - 1]; // files
			}
		}
		return name;
	}
	// Index Prep: get row classes
	function getItemClasses(name,kind,ext) {
		let itemClasses = [];
		    itemClasses.push(kind);
		if ( ext.search(/dir|app/) === -1 ) {
			itemClasses.push('file');
		}
		if ( ext === 'app' ) {
            if ( $settings.apps_as_dirs === false ) {
                itemClasses.push('file');
            } else {
                itemClasses.push('dir');
            }
		}
		if ( name.endsWith('symlink') || name.endsWith('alias') || name.endsWith('symbolic link') ) {
			itemClasses.push('alias');
		}
		if ( name.indexOf('.') === 0 ) {
			itemClasses.push('invisible');
		}
		if ( !JSON.stringify($row_types).match( escapeStr(ext) ) ) { // else classify as "other" if extension is not in $row_types.
			itemClasses.push('other'); //itemType = 'Other'; itemKind = 'other';
		} else if ( kind === '' ) {
			//            itemClasses.push('code'); //itemType = 'Code'; itemKind = 'code';
		} else {
			itemClasses.push(ext);
		}
		if ( $row_settings.ignore.includes( ext ) ) {
			itemClasses.push('ignore');
		}
		if ( $row_settings.exclude.includes( ext ) ) {
			itemClasses.push('exclude');
		}
		if ( kind === 'audio' || kind === 'video' ) {
			itemClasses.push('media');
		}
		itemClasses = Array.from(new Set(itemClasses)); // remove dupe classes
		return itemClasses.join(' ');
	}
	// Index Prep: get formatted row size and date
    function getItemSizeAndDate(cells) {
        let sizesAndDates = [];
        let rowDisplaySize, rowSortSize, rowDisplayDate, rowSortDate;
        if ( cells.length > 1 ) {
            if ( cells[1].search(/[-:\/]/) !== -1 ) { // test for typical date/time separators.
                rowDisplayDate = cells[1];
                rowDisplaySize = cells[2];
            } else {
                rowDisplayDate = cells[2];
                rowDisplaySize = cells[1];
            }
        }
        // size
        let sizeUnits = /[BYTES|B|K|KB|MB|GB|TB|PB|EB|ZB|YB]/;
        if ( rowDisplaySize === undefined || rowDisplaySize === '' || rowDisplaySize === '-' || rowDisplaySize === ',' ) {
            rowDisplaySize = '&mdash;'; rowSortSize = '0'; // if no size supplied, use these defaults
        } else {
            rowSortSize = getItemSortSize(rowDisplaySize);
            rowDisplaySize = ( rowDisplaySize.toUpperCase().endsWith('B') ? rowDisplaySize : rowDisplaySize + 'B');
            if ( !rowDisplaySize.toUpperCase().match(sizeUnits) ) { // if provided size is only numeric
                rowDisplaySize = formatBytes(rowDisplaySize,1);
            } else {
                rowDisplaySize = rowDisplaySize.replace('K','k').replace(/(\d+)\s*([A-z])/,'$1 $2');
            }
        }
        // date
        if ( rowDisplayDate === undefined || rowDisplayDate === '' || rowDisplayDate === '-' ) {
            rowDisplayDate = '&mdash;'; rowSortDate = '0';
        } else {
            rowSortDate = getItemDate(rowDisplayDate);
        }
        sizesAndDates.push(rowDisplaySize,rowSortSize,rowDisplayDate,rowSortDate);
        return sizesAndDates;
    }
	// Index Prep: get row size for sorting
	function getItemSortSize(val) {
        let sortSize;
        let values = val.replace(/(\d+)\s*([A-z])/,'$1 $2').split(' ');
        let size = values[0];
        let unit = values[1];
        if ( unit !== undefined ) { unit = unit.toUpperCase(); }
        const factor = { '':1, B:1, K:1000, KB:1000, M:1000000, MB:1000000, G:1000000000, GB:1000000000, T:1000000000000, TB:1000000000000,  P:1000000000000000, PB:1000000000000000, E:1000000000000000000, EB:1000000000000000000, Z:1000000000000000000000, ZB:1000000000000000000000 }; // unit to file size
        sortSize = size * factor[unit]; // convert byte size to multiplication factor
		return sortSize;
	}
    // convert numeric sizes to display format
    function formatBytes(val, decimals) {
        if (val === 0) return '0 Bytes';
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(val) / Math.log(k));
        return parseFloat((val / Math.pow(k, i)).toFixed(dm)) +' '+ sizes[i];
    }
    // process date
	function processDate(match,p1,p2,p3) { //date formats: 2017-10-09 13:12 || 2015-07-25T02:02:57.000Z || 12-Mon-2017 21:11
		const mo = 'JanFebMarAprMayJunJulAugSepOctNovDec'.indexOf(p2)/3 + 1; // e.g., convert month into number, or use number
		return p3 +'-'+ mo +'-'+ p1;
	}
	// Index Prep: get row date    2015-07-25T02:22:00.000Z
	function getItemDate(val) {
		let sortDate = val.replace(/^(\d{2})-(\w{3})-(\d{4})/m, processDate) // convert Month to number
                          .replace(/\b(\d{1})[-:\/]/g,'0$1/') // add leading 0 for single digit numbers
                          .replace(/(\d{2})\/(\d{2})\/(\d{2}),/,'$3$1$2') // reorder MM/DD/YY dates
                          .replace(/-|:|\s+|\//g,''); // remove spacing characters
		return sortDate;
	}
	// Index Prep: get row kind
	function getItemKind(ext) {
		let kind = '';
		if ( ext === 'dir' || ext === 'app' ) {
			kind = ext;
		} else {
			for ( let types in $row_types ) {
				if ( $row_types[types].includes( ext ) ) {
					kind = types;
					return kind;
				}
			}
		}
		if ( kind === '' ) { kind = 'other'; }
		return kind;
	}
	// Index Prep: get row extension
	function getItemExt(link) {
		let ext = '';
		if ( link.endsWith('app/') || link.endsWith('exe') ) {
			ext = 'app';
		} else if ( link.endsWith('/') ) {
			ext = 'dir';
		} else if ( link.indexOf('.') < 0 ) { // if no '.' in link, ...
			ext = link.slice(link.lastIndexOf('/') + 1).toLowerCase();
		} else { // find the last . and get the remaining characters
			ext = link.slice(link.lastIndexOf('.') + 1).toLowerCase();
		}
		return ext;
	}
	// END INDEX PREP
	// ***** MAKE NEW INDEX ***** //
	function makeNewIndex(el,sort) {
        const indexItems = getIndexItems(el);
        const items = indexItems[0];
        const type = indexItems[1];
        const convertedIndex = convertIndexItems( type, items ); // = array of rows: ["link","date","size"]
		if ( type === 'error' ) {
			return [convertedIndex];
		} else {
			let newIndex = buildNewIndex( convertedIndex, sort );
			return [newIndex];
		}
	}
	function appendNewIndex(body_top) { // setUpUI();
        const newIndex = makeNewIndex(body_top);
        $dir_list_body.empty().append( newIndex);
        $dir_list.find('#stats').html(getIndexStats($dir_list.find('#tbody tr')));
    }
	// get and set index stats
	function getIndexStats(el) {
         const total = el.length;
         const dirs = el.filter('.dir').length;
         const files = el.filter('.file').length;
         const stats = total +' items: '+ dirs +' directories, '+ files +' files';
        return stats;
    }
	// ***** END DIR_LIST SETUP ***** //

    // ***** UI SETUP ***** //
	// Build UI: Append all assembled elements to $body
	function buildUI() {
		if ( window.self === window.top ) { // if it's an iframe...
			$('head').prepend('<meta charset="utf-8">');
            let prefix = 'data:image/png;base64,';
//            let favicon = 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABAAgMAAADXB5lNAAAACVBMVEUmRckzmf+ZzP9yAsYbAAAAAXRSTlMAQObYZgAAADhJREFUeAFjoAYIBQEMAQd0gQB0gRB0gVAMAQd0gQB0gRB0AQSgkUDUKiSwFFlgVGBUgE6pcJAAANNZhFSKf6iqAAAAAElFTkSuQmCC';
            let favicon = 'iVBORw0KGgoAAAANSUhEUgAAAIAAAACAAgMAAAC+UIlYAAAACVBMVEUmRcmZzP8zmf8pVcWPAAAAAXRSTlMAQObYZgAAAFBJREFUeF7tyqERwDAMBEE3mX5UiqDmqwwziTPHjG7xrmzrLFtRaApDIRiKQlMYCsFQFJrCUAiGotAU5hTA1WB4fhkMBsOJwWAwgHvB8CHpBcTbpxy4RZNvAAAAAElFTkSuQmCC';
            if ( $location.startsWith('file') ) { $('head').prepend('<link href="'+ prefix + favicon +'" rel="icon" sizes="16x16" />'); }
            $('head #title').removeAttr('id'); // not sure where this id is being added, but it must be removed...
			$('body').attr('id','top').attr('lang','en').find('script').remove();
            addStyles( $('head') );
            appendNewIndex($('body'));
            $('body').empty().append($main_content);
		} else {
			$('body').attr('id','iframe_body');
		}
    }
	buildUI();

    // Define additional UI Element refs
	const $body =         $('body#top');
    const $iframe_body =  $('body#iframe_body');
	const $iFrame_head =  $iframe_body.prev('head');
	const $dir_list_row = $dir_list_body.find('> tr');
	const $audio_files =  $dir_list_body.find('.audio');
	const $font_files =   $dir_list_body.find('.font');
	const $image_files =  $dir_list_body.find('.image');
	const $media_files =  $dir_list_body.find('.media');
	const $video_files =  $dir_list_body.find('.video');
    function $selected_file() { return $dir_list_body.find('.selected'); }
	function $playing_file() { return $dir_list_body.find('.playing'); }

    // UI Setup: build UI and add body classes and other initial settings
	function setupUIprefs() {
		for ( let key in $settings ) {
			if ( getQuery(key) === 'true' ) {
				$body.addClass(key);
			} else { // non-boolean settings and others
				if ( key === 'theme' ) { $body.addClass( 'theme_'+ getQuery('theme') ); }
				if ( key === 'sort_by' ) {
					$body.addClass( 'sort_by_'+ getQuery(key) );
					$('#sorting').find('th[id="sort_by_'+ getQuery(key) +'"]').addClass('up');
				}
				if ( key === 'default_text_view' ) {
					if ( getQuery(key) === 'source_text' ) { $body.addClass('source_text'); } else { $body.addClass('preview_text'); }
				}
				if ( getQuery('toggle_sidebar') === 'true' ) { $body.addClass( 'has_hidden_sidebar' ); }
			}
		}
		if ( navigator.vendor.indexOf('Google') > -1 ) { $body.addClass('is_chrome'); }
		if ( navigator.userAgent.indexOf('Firefox') > -1 ) { $body.addClass('is_gecko'); }
        if ( navigator.vendor.indexOf('Apple') === 0 ) { $body.addClass('is_safari'); }
		if ( $audio_files.length > 0 ) { $body.add($dir_list).addClass('has_audio has_media'); }
		if ( $font_files.length > 0 ) { $body.addClass('has_fonts'); }
		if ( $image_files.length > 0 ) { $body.addClass('has_images'); }
		if ( $video_files.length > 0 ) { $body.add($dir_list).addClass('has_video has_media'); }
		// UI Setup: show invisibles
		if ( navigator.platform.indexOf('Win') > -1 || $location.indexOf('file:') < 0 ) {
			$('#show_invisibles').closest('label').hide();
		} else if ( $body.hasClass('show_invisibles') ) {
			$('#show_invisibles').attr('checked','checked');
		}
	}
    // Get DOMTokenList of body classes
    function getClassList(id) { return document.getElementById(id).classList; }
    //
	function setUpUI() {
        if ( window.self === window.top) {
            setupUIprefs();
            initMedia();
            autoSelectFile();
            autoLoadCoverArt();
            setContentTitle();
            setContentHeight();
        } else {
            setUpIframeUI( getQuery('enable_text_editing') );
        }
        document.title = 'Index of: '+ $location;
	}
	setUpUI();

	// SET UI TO DEFAULT SETTINGS: remove queries;
	function defaultSettings() {
		let $location = window.location.href;
            $location = $location.slice(0,$location.lastIndexOf('?'));
		window.location.assign($location);
	}
	$('#default_settings').on('click', function(e) {
        e.preventDefault();
		e.stopPropagation();
        $('#bookmarks').hide();
		if (window.confirm( 'Are you sure you want to reset all your temporary UI settings to the defaults in your user_settings?\nThis action cannot be undone.' ) ) {
			defaultSettings();
		}
	});
	// EXPORT SETTINGS
	function saveSettings(filename, data) {
		const blob = new Blob([data], {type: 'text/html'});
		const elem = window.document.createElement('a');
              elem.href = window.URL.createObjectURL(blob);
              elem.download = filename;
        document.body.appendChild(elem);
              elem.click();
        document.body.removeChild(elem);
        URL.revokeObjectURL(blob);
	}
	$('#export_settings').on('click',function(e) {
		e.preventDefault();
		e.stopPropagation();
        $('#bookmarks').hide();
		const $settings_string = ( JSON.stringify($settings,null,'\t'));
		saveSettings('settings.txt',$settings_string);
    });

	// Click Menu Link (with warning)
	function setLocation(link) { window.location = link; }
	$('#parent_dir_menu,#parents_dir_menu + .menu,#bookmarks .bookmark').on('click','a',function(e) {
		e.preventDefault();
		if ( $(this).attr('href').indexOf('file://') > -1 && $protocol !== 'file:' ) {
			$body.addClass('has_warning').find('#warnings').addClass('local');
		} else {
			showWarning( 'setLocation', thisLink($(this)) );
		}
	});
	// Show Menus
	function showMenus(el) {
		let $position = $(el).position();
		$(el).find('> ul').css({'top':$position.top + $(el).innerHeight() + 'px'}).toggle().parent('td').siblings('td').find('.menu').hide();
	}
	$('#parents_dir_menu').add('#bookmarks_menu').parent('td').on('click',function(e) {
		e.stopPropagation();
		showMenus(this);
	});
	// Hide Menus
	$(document).on('click', function() { $('.menu').hide(); });

	// Toggle UI Preferences
	function toggleUIpref(prefID) {
		let prefClass = prefID;
		if ( prefID === 'split_view' ) {
            sendMessage('iframe','split_view');
        }
		if ( prefID.startsWith('sort_by') ) {
            $body.removeClass('sort_by_default sort_by_name sort_by_size sort_by_date sort_by_kind sort_by_ext');
            $('#bookmarks').hide(); // don't hide menus after click?
        }
		if ( prefID.startsWith('theme') ) {
            prefID = ( $body.hasClass('theme_dark') ? 'theme_dark' : 'theme_light' );
            prefClass = 'theme_dark theme_light';
        }
		if ( prefID.endsWith('text') ) {
            prefClass = 'preview_text source_text';
            sendMessage('iframe','default_text_view');
        }
		toggleQuery(prefID);
		$body.toggleClass(prefClass);
		setContentHeight();
        scrollThis('tbody','selected',false); // true = instant scroll
		if ( prefID === 'enable_text_editing' ) {
            $('.selected.text, .selected.markdown').click();
        }
	}
	// Click Toggle UI Pref elements
	$('.toggle_UI_pref').on('click',function(e) {
		if ( !$(this).is('input') ) {
			e.preventDefault(); // allow checkboxes to be checked
		}
		toggleUIpref( $(this).attr('id') );
	});

	// Toggle Sidebar
	function toggleSidebar() {
		$body.toggleClass('has_hidden_sidebar');
		if ( $body.hasClass('has_hidden_sidebar') ) { setQuery('toggle_sidebar','true'); } else { removeQuery('toggle_sidebar'); }
		setContentHeight();
		scrollThis('tbody','selected',true); // true = instant scroll
	}
	$('#toggle_sidebar').on('click', function() {
		toggleSidebar();
	});

	// RESIZE Sidebar/Content Pane
	function resizeSidebar(f) {
		f.stopPropagation();
        const $sidebar_wrapper = $('#sidebar_wrapper');
		const $startX = f.pageX;
          let $window_width = window.innerWidth;
          let $sidebar_width = $sidebar_wrapper.width();
        $('#overlay').css({'display':'block','z-index':'1'});
		$('#handle').css({'z-index':'9999'});
		$body.css({'-webkit-user-select':'none','-moz-user-select':'none','user-select':'none'});

		$(document).on('mousemove',function(e) {
			e.stopPropagation();
			e.preventDefault();
			const $deltaX = e.pageX - $startX;
			if ( e.pageX > 230 && e.pageX < $window_width - 200 ) {
				$sidebar_wrapper.css({'width':$sidebar_width + $deltaX + 'px'});
				$content_pane.css({'width':($window_width - $sidebar_width) - $deltaX + 'px'});
			}
			setContentHeight();
            scrollThis('tbody','selected',false); // true = instant scroll
		});
		$(document).on('mouseup',function() {
			$('#overlay').css({'display':'none','z-index':'unset'});
			$('#handle').css({'z-index':'unset'});
			$body.css({'-webkit-user-select':'unset','-moz-user-select':'unset','user-select':'unset'});
			$(document).off('mousemove');
			$sidebar_width = $sidebar_wrapper.width();
			setQuery('width',$sidebar_width);
		});
	}
	$('#handle').on('mousedown', function(f) {
		f.stopPropagation();
		resizeSidebar(f);
	});

	// ***** BASIC UI FUNCTIONS ***** //
	// Get dir_list item row
	function thisRow(x) {
		return $(x).closest('#dir_list > tbody > tr').length > 0 ? $(x).closest('#dir_list > tbody > tr') : $(x).closest('#dir_list > li');
	}
	function thisID(x) {
		return thisRow(x).attr('id');
	}
	// Get row link
	function thisLink(x) {
		return $(x).find('a').length > 0 ? $(x).find('a').attr('href') : $(x).attr('href');
	}
	// Get row name
	function thisText(x) {
		return $(x).find('a span').length > 0 ? decodeURIComponentSafe( $(x).find('a span').text().toLocaleLowerCase() ) : decodeURIComponentSafe( $(x).text().toLocaleLowerCase() );
	}
	// get row text
	function thisExt(x) {
		let $this_name = thisText(x);
		return $this_name.endsWith('app/') ? 'app' : $this_name.endsWith('/') ? '/' : $this_name.lastIndexOf('.') === -1 ? undefined : $this_name.toLocaleLowerCase().slice( $this_name.lastIndexOf('.') + 1 );
	}
	function getElById(id) {
		return $(document.getElementById(id) );
	}

	// SET CONTENT HEIGHT
	function setContentHeight() {
        let $title = $('#title');
        // accommodate multi-line title names in preview pane
		if ( $title.outerWidth() > ( $('#content_title').innerWidth() - 2 * $('#title_buttons_left').outerWidth() ) ) {
            $title.css({'margin-top':'2em'});
        } else {
            $title.css({'margin-top':'0'});
        }
		let $window_height = window.innerHeight;
		let $content_header_height = $('#content_header').outerHeight();

        $('#sidebar, #main_content, #content_pane').css({'height':$window_height });
        $dir_list.css({'height':$window_height - $('#sidebar_header').outerHeight(), 'max-height':$window_height - $('#sidebar_header').outerHeight() });
        $dir_list_body.css({'bottom': $dir_list.find('tfoot').outerHeight(),'height': $dir_list.innerHeight() - $dir_list.find('tfoot').outerHeight(),'max-height': $dir_list.innerHeight() - $dir_list.find('tfoot').outerHeight() });
        $('#iframe_body').find('#tbody').css({'top':$('#iframe_body').find('#thead').height() + 1 +'px'});
        $content_font.css({'padding-bottom': $('#font_info th').outerHeight() +'px' });

        $('#prev_track, #next_track, #close_audio').css({'height':$('#audio').height() }); // set height of audio controls
        $('#content_container, #glyph_viewer').css({'top':$content_header_height +'px' });
        $('#content_pane.has_image #content_image').css({'top':$('#content_header').height() });
        setDimensions($('tr.image.selected'));
    }
	window.addEventListener('resize', setContentHeight );

	// SET CONTENT TITLE
	function setContentTitle(kind) {
        let $title = $('#title span');
		let $title_text = '';
		if ( $playing_file().hasClass('audio') ) { // set audio player title
			$('#content_audio_title').find('td').empty().text( $playing_file().find('td.name a').text() );
		}
		if ( $content_pane.hasClass('has_grid') ) { // set main title for other content
			$title_text = $('#parents_dir_menu').find('> div').html().split('<wbr>').reverse()[1];
		} else if ( $('#toggle_info').hasClass('selected') ) {
            $title_text = 'Source of: '+ $current_dir_path;
		} else if ( $body.hasClass('has_text') ) {
			$title_text = 'Text Editor';
		} else if ( $selected_file().hasClass('audio') ) {
			return;
		} else if ( !$selected_file().hasClass('audio') || $content_pane.hasClass('has_hidden_text') ) {
			$title_text = $selected_file().not('.audio').find('td.name a span').text(); // Assemble title
		}
		$title.removeClass().empty().html($title_text);
        if ( kind !== undefined && !['audio','dir','font','image','pdf','video'].includes(kind) ) {
            $title.addClass('has_'+ kind);
        }
		if ( $title.outerWidth() > ( $('#content_title').innerWidth() - 2 * $('#title_buttons_left').outerWidth() ) ) { $title.css({'margin-top':'2em'}); } else { $title.css({'margin-top':'0'}); }
	}
	// Get Image Dimensions
	function getDimensions(link, callback) {
        if ( link !== undefined ) {
            let img = new Image();
            img.src = link;
            img.onload = function() { callback( this.width, this.height ); };
        }
	}
	function setDimensions(row) {
		if ( $content_pane.hasClass('has_image') || $content_pane.hasClass('has_zoom_image') ) {
            getDimensions( thisLink(row), function( width, height ) {
                $('#title').attr('data-after',' (' + width + 'px × ' + height + 'px) ('+ ( ($content_image.find('img').width()/width)*100 ).toFixed(1) +'%)');
            });
        } else {
			$('#title').removeAttr('data-after'); // remove image dimensions
        }
	}
	// Scroll Selected Items
	function scrollThis(elID,className,bool) {
		let $behavior = 'smooth';
		if ( bool !== undefined ) { $behavior = 'instant'; }
		let $block = ( $body.hasClass('is_gecko') ? 'start' : 'nearest' );
		if ( document.getElementsByClassName(className).length !== undefined && document.getElementsByClassName(className).length > 0 ) {
			document.getElementById(elID).getElementsByClassName(className)[0].scrollIntoView({ behavior:$behavior, block:$block, inline:'nearest' });
		}
		setContentHeight();
	}

	// ***** SORTING ***** //
	function sortIndex(els,id,sortDirection) { // id = sort type
          let sorted = [];
		const newSort = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); // needs to be above makeNewIndex()
        sorted = els.removeClass('sorted').sort((a, b) => {
                let aName, bName;
            if ( $('body').hasClass('has_playlist') ) {
                aName = $(a).attr('id');
                bName = $(b).attr('id');
            } else {
                aName = $(a).find('td.name').data('name');
                bName = $(b).find('td.name').data('name');
            }
            let aData = $(a).find('td[data-'+ id +']').data(id);
            let bData = $(b).find('td[data-'+ id +']').data(id);
            if ( sortDirection === 1 ) { // sort by detail data value, then by name (i.e., if data values are the same, sort by name)
                if ( newSort.compare(aData, bData) === 0 ) {
                    return newSort.compare(aName, bName);
                } else {
                    return newSort.compare(aData, bData);
                }
            } else { // reverse sort
                if ( newSort.compare(bData, aData) === 0 ) {
                    return newSort.compare(bName, aName);
                } else {
                    return newSort.compare(bData, aData);
                }
            }
        });
        sorted = sorted.sort((a, b) => { // add sorted style (rules between different rows)
            if ( id === 'kind' || id === 'ext' && sortDirection === 1 ) {
                if ( $(a).find('td[data-'+ id +']').data(id) !== $(b).find('td[data-'+ id +']').data(id) ) { $(a).addClass('sorted'); }
            }
            if ( id === 'kind' || id === 'ext' && sortDirection === -1 ) {
                if ( $(b).find('td[data-'+ id +']').data(id) !== $(a).find('td[data-'+ id +']').data(id) ) { $(a).addClass('sorted'); }
            }

        });
        return sorted;
	}
	// Sort the Dir List on click
	function sortDirList(rows, id, sortDirection) {
		const $sort_all = rows;
		const $sort_dirs = $sort_all.filter('.dir:not(.app)');
		const $sort_files = $sort_all.filter('.file,.app');
		const $sort_id = id.slice(8);// === 'default' ? 'name' : id;
          let $sorted = [];

		if ( $sort_id === 'default' || ( $sort_id !== 'name' && $settings.dirs_on_top === true )) {
            const $sorted_dirs = sortIndex($sort_dirs, $sort_id, sortDirection);
            const $sorted_files = sortIndex( $sort_files, $sort_id, sortDirection );
            if (sortDirection === 1) {
				$sorted = $.merge($sorted_dirs,$sorted_files);
			} else {
				$sorted = $.merge($sorted_files,$sorted_dirs);
			}
		} else {
			$sorted = sortIndex( $sort_all, $sort_id, sortDirection );
		}
		return $sorted;
	}
	// Sort on click
	function clickSort(id) {
		const el = $(getElById(id)); // id from th sort item = 'sort_by_xxx'
          let sortDirection = ( el.hasClass('up') ? -1 : 1 ); // Only reverse sort order after clicking a sort column once.
		// SORT EM!
          let rows = ( $body.hasClass('has_playlist') ? $('#tbody').find('tr') : $dir_list_row );
		const $sorted_index = sortDirList( rows, id, sortDirection );
		$dir_list_body.empty().append($sorted_index);
		$('div[id="'+ id +'"]').toggleClass('up').siblings().removeClass('up');
		if ( $content_grid.hasClass('has_font_grid') ) { $('#show_font_grid').click(); }
		if ( $content_grid.hasClass('has_image_grid') ) { $('#show_image_grid').click(); }
		if ( $content_grid.hasClass('has_grid') ) { $('#grid_btn').click(); }
		setContentHeight();
        scrollThis('tbody','selected',false); // true = instant scroll
	}
	// Sort on clicking dir_list sort item
	$('#sorting').on('click','div.sorting:not(.disabled)',function(e) {
		e.preventDefault();
		e.stopPropagation();
		clickSort( $(this).attr('id') );
	});
	// Sort Menu: click the list header that contains the selected menu text.
	$('#sort_menu').on('click','li:not(.disabled)',function(e) {
		e.preventDefault();
		e.stopPropagation();
		$('#sorting div[id="sort_by_'+ $(this).attr('id') +'"]').click(); // click corresponding sidebar sort item
	});
	// ***** END SORTING ***** //
	// ***** END BASIC UI FUNCTIONS ***** //

	// ***** CONTENT PANE ***** //
	// SELECT ROW on click and set classes for $content_pane
	function selectThis(rowID) {
        $('#toggle_info').removeClass('selected');
        let row = $(getElById(rowID));
		const $grid_selected = $content_grid.find('> div[data-id="'+ rowID +'"]');
		if ( $content_pane.hasClass('has_grid') || $content_pane.hasClass('has_hidden_grid') ) { // Select corresponding grid item
			row.addClass('selected').siblings().removeClass('selected hovered');
			$grid_selected.addClass('selected').siblings().removeClass('selected');
        } else { // remove classes from rows, but leave .audio with playing
            if ( row.attr('id') === 'toggle_info' ) {
                row.toggleClass('selected loaded');
                $dir_list.find('#tbody .selected').removeClass('selected');
            } else {
                row.addClass('selected').siblings().removeClass('selected hovered');
            }
		}
    }

	//***** SHOW CONTENT *****//
	function showAudio(rowID) {
		let row = getElById(rowID);
        if ( $content_video.hasClass('has_content') ) { $('#title span').empty(); }
		closeMedia('video');
        if ( row.hasClass('audio') ) { row.addClass('playing selected').siblings('.media').removeClass('playing selected'); }
		$audio_player.attr('src', thisLink( row ) );
		$content_pane.addClass('has_audio');
        $('#content_audio_title').find('td').empty().text( $playing_file().find('td.name a').text() );
		setContentHeight();
	}

    // showTextEditor();

    // Show Grid
	function showGrid() {
		$content_pane.removeClass('has_hidden_grid').addClass('has_grid');
        if ( $body.hasClass('has_text') ) { $body.toggleClass('has_text has_hidden_text'); }
		closeMedia('video');
		setContentTitle();
		setContentHeight();
		selectThis( $selected_file().attr('id') );
	}
	// Show Hidden Editor or Grid
	function showHiddenEditorOrGrid() {
        if ( $content_pane.hasClass('has_hidden_grid') && !$body.hasClass('has_hidden_text') || $content_pane.hasClass('has_hidden_grid') && $body.hasClass('has_hidden_text') ) {
            $content_pane.toggleClass('has_grid has_hidden_grid'); // show grid preferentially
        } else if ( !$content_pane.hasClass('has_hidden_grid') && $body.hasClass('has_hidden_text') ) {
            $body.toggleClass('has_text has_hidden_text');
        }
    }
	// Hide Editor or Grid
	function hideEditorOrGrid() {
		if ( $body.hasClass('has_text') ) { $body.toggleClass('has_text has_hidden_text'); }
		if ( $content_pane.hasClass('has_grid') ) { $content_pane.toggleClass('has_grid has_hidden_grid'); }
	}
    // showIndexSource();

	// Show Font (and create font items)
	function showFont(row,bool,sheet) { // bool = true if for show font grid, sheet defined at fontGridItems()
        $content_font.addClass('has_font').removeClass('has_font_viewer');
          let fontStyles = $font_styles.sheet;
		const $font_family = thisText(row);
		const $font_url = thisLink(row);
        const $font_grid_item_el = $('<div class="font_grid_item" data-id="'+ $(row).attr('id') +'"></div>');
		if ( bool === false ) {
			if ( fontStyles.cssRules.length > 0 ) { fontStyles.deleteRule(0); } // delete previous @font-face rule
			fontStyles.insertRule('@font-face { font-family: "'+ $font_family +'"; src: url("'+ $font_url +'"); }');
			$content_font.css({ 'font-family':'"'+ $font_family +'"' }); // set content font style
		} else {
              let grid_item = $font_grid_item_el.clone();
			const $display_name = $font_family;
			sheet.insertRule('@font-face { font-family: "'+ $font_family +'"; src: url("'+ $font_url +'"); }');
			grid_item.append('<p>'+ $display_name.toUpperCase() +'</p><h2 style=\'font-family: "'+ $font_family +'"\'; ><a href="'+ $font_url +'">'+ $display_name.slice(0,$font_family.lastIndexOf('.')) +'</a></h2>' );
			return grid_item;
		}
	}

    // OPEN FONT
    /// opentype.js font parsing
    $('#open_font_label').on('click',function(e) { $('.menu').hide(); });
    // Open font
    $('#bookmarks').on('change','#open_font',function(e) {
        openFont(e);
    });
    function openFont(evt) {
        if (window.File && window.FileReader && window.FileList && window.Blob && window.opentype ) {
            let files = evt.target.files[0];
            let reader = new FileReader();
                reader.readAsArrayBuffer(files);
            reader.onload = function(file) {
                closeOtherContent();
                closeGrid();
                hideEditorOrGrid();
                $content_pane.addClass('has_font');
                $content_font.addClass('has_content has_font_viewer').removeClass('has_font');
                parseFont(reader.result);
                return true;
            };
            $('#open_font').val(''); // reset input to allow same font to be reopened immediately after closing.
        } else {
            alert('File APIs are not fully supported in this browser or opentype.js is not available.');
        }
    }
    // Parse font
    function parseFont(fontblob) {
            let font = window.opentype.parse(fontblob);
                getFontInfo(font);
            let $glyphs_container = $('#glyphs_container');
                $glyphs_container.empty();
            let $glyph_container =  $('<div class="glyph_container"></div>');
            let $glyph_canvas =     $('<canvas class="glyph" width="120" height="120"></canvas>');
            let $glyph_info =       $('<div class="glyph_info" style="font-size:0.75rem"></div>');
            let $glyph_viewer =     $('#glyph_viewer');
                $glyph_viewer.data('data-font-name',font.names.fullName.en);
            let glyphs = font.glyphs;
        $content_font.data('data-glyphs',glyphs); // add glyphs data to $content_font
            // Draw glyphs
            for ( let i = 0; i < glyphs.length; i++ ) {
                let glyph = glyphs.glyphs[i];
                // GLyph width
                let boundingBox = glyph.getBoundingBox();
                let glyphWidth = boundingBox.x2 - boundingBox.x1;
                let contextX = (60 - glyphWidth/24);
                // Add glyph info and append elements
                let glyphUnicode = ( glyph.unicode !== undefined ? '#'+ glyph.unicode : glyph.unicode );
                let glyphContainer = $glyph_container.clone();
                let glyphCanvas = $glyph_canvas.clone();
                let glyphInfo = $glyph_info.clone();
                    glyphInfo.text(glyph.index +': '+ glyph.name +', '+ glyphUnicode);
                    glyphContainer.append( glyphCanvas.clone().attr('id','glyph_'+ glyph.index ) ).append(glyphInfo);
                    $glyphs_container.append( glyphContainer );
                // Draw glyph
                let thisGlyph = document.getElementById('glyph_'+ glyph.index);
                    $(thisGlyph).data('contextX',contextX);
                let context = thisGlyph.getContext('2d');
                    glyph.draw(context, contextX, 84, 72);
            }
            $('#title').removeAttr('data-after').find('span').empty().html(font.names.fullName.en);
            setContentHeight();
    }
    // Get font info
    function getFontInfo(font) {
        let $font_names = font.names;
        let $font_info = $('<table id="font_info"><thead><tr><th colspan=2>FONT INFO: '+ font.names.fullName.en.toUpperCase() +'</th></tr></thead><tbody></tbody></table>');
        for (let name in $font_names) {
            let value = $font_names[name].en;
            if ( name.endsWith('URL') ) {
                let href = value;
                if ( !value.startsWith('http') ) {
                    href = 'http://'+ value;
                }
                value = '<a href="'+ href +'" target="_blank">'+ value +'</a>';
            }
            $font_info.find('tbody').append('<tr><td>'+ name +': </td><td>'+ value +'</td></tr>');
        }
        let numGlyphs = font.numGlyphs; // glyph count
            $font_info.find('tbody').append('<tr><td>numGlyphs: </td><td>'+ numGlyphs +'</td></tr>');
            $content_font.find('#font_viewer').prepend($font_info);
    }
    // Show glyph viewer
    $content_font.on('click','.glyph',function(e) {
        e.stopPropagation();
        let id = $(this).attr('id');
        $(this).parent('div').addClass('selected').siblings().removeClass('selected');
        showGlyph( id );
    });
    function showGlyph(id) {
        let $glyph_viewer = $('#glyph_viewer');
        let glyphX = $('#'+ id).data('contextX');
            id = id.slice(id.lastIndexOf('_') + 1);
        let glyphs = $content_font.data('data-glyphs'); // get glyphs
        let glyph = glyphs.get(id);
        let glyphName = glyph.name;
        let glyphPath = glyph.getPath(glyphX,84,72);
        let glyphSVG = glyphPath.toSVG().replace(/"/g,'\'');
        // set the background SVG image:
        let SVGprefix = 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' x=\'0px\' y=\'0px\' width=\'120px\' height=\'120px\' viewBox=\'0 0 120 120\' style=\'enable-background:new 0 0 120 120;\' xml:space=\'preserve\' ><g>';
            $glyph_viewer.show().css({'background-image': SVGprefix + glyphSVG +'</g></svg>")'});
            $glyph_viewer.data('data-raw-svg',glyphSVG).data('data-glyph-name',glyphName).find('#glyph_viewer_info div').text(id +': '+ glyphName +', #'+ glyph.unicode ); // for saving SVG
            $content_font.addClass('has_glyph');
            setContentHeight();
    }
    // Save glyph svg
    $content_font.on('click','#save_svg',function(e) {
        e.stopPropagation();
        saveGlyph();
    });
    function saveGlyph() {
        let filename = $('#glyph_viewer').data('data-font-name') +'—'+ $('#glyph_viewer').data('data-glyph-name') +'.svg';
        let data_prefix = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="120px" height="120px" viewBox="0 0 120 120" style="enable-background:new 0 0 120 120;" xml:space="preserve" ><g>';
        let data_suffix = '</g></svg>';
        let data = data_prefix +  $('#glyph_viewer').data('data-raw-svg') + data_suffix;
		let blob = new Blob([data], {type: 'image/svg+xml'});
		let downloadEl = window.document.createElement('a');
		    downloadEl.href = window.URL.createObjectURL(blob);
		    downloadEl.download = filename;
		document.body.appendChild(downloadEl);
		    downloadEl.click();
		document.body.removeChild(downloadEl);
		URL.revokeObjectURL(blob);
    }

    // Set Content Pane classes
	function setContentClasses(content_el) {
		if ( content_el === 'audio' ) {
			$content_pane.addClass('has_audio');
		} else {
			hideEditorOrGrid();
			$content_pane.addClass( 'has_'+ content_el ); // remove classes, excluding grid and text classes; add content class
		}
	}
	// Set Content Element Sources and row classes
    function setContentSources(row,link,kind,content_el) {
        switch(kind) {
            case 'audio':
                $audio_player.attr('src',link);
                break;
            case 'font':
                showFont(row,false);
                break;
            case 'code':
            case 'markdown':
            case 'text':
                link = thisLink(row) +'?split_view='+ getQuery('split_view') +'&default_text_view='+ getQuery('default_text_view');
                if ( !$body.hasClass('enable_text_editing') ) { link += '&enable_text_editing=false'; } else { link += '&enable_text_editing=true'; }
                break;
            case 'dir':
                $content_pane.toggleClass('has_iframe has_dir')
                link = link + '?sort_by=' + getQuery('sort_by') +'&show_numbers='+ getQuery('show_numbers') +'&use_custom_icons='+ getQuery('use_custom_icons');
                break;
            case 'info':
                link = $location + '?sort_by=' + getQuery('sort_by') +'&show_numbers='+ getQuery('show_numbers') +'&view_source=true';
                break;
            case 'pdf':
                link = link + '?#view=fitB&scrollbar=1&toolbar=1&navpanes=1';
                break;
        }
        if ( kind === 'video' ) { row.addClass('playing'); } else { row.addClass('loaded'); }
        // fix for pdfs not being loaded after setting src attribute (hide and then show)
		if ( kind === 'pdf' ) {
            $content_pdf.hide().addClass('has_content').attr('src','').attr('src',link).show().removeAttr('srcdoc');
        } else if ( kind === 'image' ) {
            $('#content_'+ content_el).addClass('has_content').find('img').attr('src',link);
        } else {
            $('#content_'+ content_el).addClass('has_content').attr('src',link).removeAttr('srcdoc');
        }
	}
	// Show Content
	function showContent(id) { // show any content excluding grids on row click
		let row = getElById(id);
		if ( row.length === -1 ) { return; } // needed for left/right arrow nav when there are no valid items (i.e. images or fonts)
		let kind = row.attr('data-kind');
		let link = thisLink(row);
        let content_el = ( row.hasClass('ignore') && $body.hasClass('ignore_ignored_files') ? 'ignored' : !['audio','font','image','pdf','video'].includes(kind) || kind === 'dir' || kind === 'info' ? 'iframe' : kind ); // load dirs and any other kind of content except audio, font, image, pdf, or video into iframe
        if ( row.hasClass('audio') ) {
			showAudio( id );
        } else {
            closeOtherContent(row);
            setContentClasses(content_el);
            setContentSources(row,link,kind,content_el);
            setContentTitle(kind);
            setContentHeight();
            row.siblings().removeClass('loaded');
        }
	}

	//***** CLOSE CONTENT (Close button or Cmd/Ctrl + W) *****//
	// Close Audio/Video
	function closeMedia(type) { // type === audio || video
		let $mediaEl = ( type === 'audio' ? $audio_player : $content_video );
            $mediaEl.trigger('pause').attr('src','');
		$content_pane.removeClass('has_'+ type);
		$('.media.playing, .media.loaded').removeClass('playing loaded');
		if ( type === 'audio' ) {
            $('#content_audio_title td').empty();
        }
		if ( type === 'video' ) {
            $('#content_video').removeClass('has_content');
        }
		setContentHeight();
	}
	// Close Audio button click
	$('#close_audio').on('click',function(e) {
		e.stopPropagation();
		closeMedia('audio');
		$('.audio.selected').removeClass('selected');
        if ( $('.loaded').length === 1 ) { $('.loaded').addClass('selected'); }
	});
    // Close Playlist
    function closePlaylist() {
        $body.removeClass('has_playlist');
        $('head').find('title').text('Index of: '+ $location); // change window title back to default
        $('#parents_dir_menu').find('> div').empty().html($current_dir_path);
        clickSort(getQuery('sort_by'));
        $dir_list.find('#stats').html(getIndexStats($dir_list.find('#tbody tr')));
        if ( $('#tbody').find('.audio').length < 1 ) { $body.removeClass('has_audio'); }
    }
	// Close Text Editor
    function closeTextEditor() {
        if ( $body.hasClass('edited') ) {
            showWarning('closeContent');
        } else {
            $body.removeClass('has_text');
            if ( $content_pane.hasClass('has_hidden_grid') ) { $content_pane.toggleClass('has_grid has_hidden_grid'); }
        }
    }
    // Close Grid
	function closeGrid() {
		$content_pane.removeClass('has_grid');
		$content_grid.empty().removeClass().attr('style','').find('.image_grid_item, img').attr('style','');
        if ( $body.hasClass('has_hidden_text') ) { $body.toggleClass('has_text has_hidden_text'); }
	}
    // Close index source preview
	function closeIndexSource() {
        $('#toggle_info').removeClass('selected loaded');
        $content_pane.removeClass('has_iframe').find('#content_iframe').removeClass('has_content').removeAttr('src');
        if ( $('.loaded:not(.audio)').length === 1 || $('.playing').length > 0 ) {
            $('.loaded:not(.audio)').click();
            $('.playing').addClass('selected');
        }
        if ( $content_pane.hasClass('has_hidden_grid') ) { showGrid(); }
        setContentTitle();
    }
	// Close .content elements (not #content_audio, #content_text, or #content_grid) when opening new content
	function closeOtherContent(row) {
        if ( $content_pane.hasClass('has_pdf') ) { $('head').find('title').text('Index of: '+ $location); } // change window title back to default
		// close audio/video when opening video/audio
		if ( row !== undefined ) {
            if ( row.hasClass('video') ) {
                closeMedia('audio');
            } else if ( row.hasClass('audio') ) {
                closeMedia('video');
            }
            if ( ( $content_pane.hasClass('has_grid') || $content_pane.hasClass('has_hidden_grid') ) && !row.hasClass('image') && !row.hasClass('font') && !row.hasClass('audio') ) {
                closeGrid();
                $('#grid_btn').removeClass('has_grid');
            }
		}
		// close other content
        if ( $('.content.has_content').length || $content_pane.hasClass('has_ignored') ) {
			let $contentID = $('.content.has_content').attr('id');
			switch($contentID) { // specific cases
                case 'content_font':
                    $content_font.attr('style','').find('#font_viewer').remove().end().append(ContentFontViewer());
                    break;
                case 'content_image':
                    $content_image.removeAttr('style').find('img').removeAttr('style'); // reset image: comment out to retain image scale after loading other content
                    break;
                case 'content_video':
                    closeMedia('video');
                    break;
            }
            // remove content classes and source attribute
            $content_pane.removeClass('has_font has_image has_zoom_image has_pdf has_video has_iframe has_dir has_ignored')
                         .find('.content').removeClass('has_content has_font has_font_viewer').removeAttr('src')
                         .find('img').removeAttr('src');
            showHiddenEditorOrGrid();
        }
    }
    // Close Button: close any visible content
	function closeContent() {
        window.stop();
		if ( $('#toggle_info').hasClass('selected') ) {
            closeIndexSource();
        } else if ( $body.hasClass('has_text') ) {
            closeTextEditor();
        } else if ( ( $content_pane.hasClass('has_hidden_grid has_image') || $content_pane.hasClass('has_hidden_grid has_zoom_image') ) && $content_grid.hasClass('has_image_grid') ) {
			$('.loaded').removeClass('loaded');
			$content_pane.toggleClass('has_hidden_grid has_grid').removeClass('has_image has_zoom_image').find('#content_image').removeClass('has_content').find('img').removeAttr('src');
            scrollThis('content_grid','selected');
        } else if ( $content_pane.hasClass('has_grid') ) { // close grid (i.e., don't just hide)
			closeGrid();
            $('#grid_btn').removeClass('has_grid');
        } else if ($content_font.hasClass('has_glyph') ) {
            $('#glyph_viewer').hide().attr('style','');
            $content_font.addClass('has_content').removeClass('has_glyph');
            scrollThis('glyphs_container','selected');
		} else if ( ['has_font','has_image','has_zoom_image','has_pdf','has_video','has_iframe','has_dir','has_ignored'].some( c => $content_pane.attr('class').split(' ').indexOf( c ) >= 0 ) && !$body.hasClass('iframe_edited') ) {
			$('tr.selected:not(.audio)').removeClass('selected');
			$('.loaded').removeClass('loaded');
            $('#title').removeAttr('data-after').find('span').empty();
			closeOtherContent();
        } else if ( $body.hasClass('iframe_edited') ) { // warn if iframe edited
			showWarning('closeContent');
		} else if ( $content_pane.hasClass('has_audio') ) { // close audio last of all
            closeMedia('audio');
            $('.selected.audio').removeClass('selected');
        } else if ( $body.hasClass('has_playlist') ) {
            closePlaylist();
        }
		if ( $('#font_info').length !== 1 ) { setContentTitle(); }
		setContentHeight();
	}
	$('#close_btn').on('click', function(e) {
		e.preventDefault();
		closeContent(); // close content unless body.edited or body.iframe_edited
	});

	//***** RESET CONTENT (Reset button or Cmd/Ctrl + R) *****//
	function resetContent() {
		if ( $content_pane.attr('class') === '' )       { window.location = window.location.href; } // reload page
		if ( $content_pane.hasClass('has_audio') )      { $audio_player.prop('currentTime', 0).trigger('pause'); }
		if ( $content_pane.hasClass('has_grid') )       { $('#grid_btn').click(); }
		if ( $content_pane.hasClass('has_font') )       { $content_font.css({'font-size':'1em'}); }
		if ( $content_pane.hasClass('has_image') || $content_pane.hasClass('has_zoom_image') ) { $content_pane.removeClass('has_zoom_image').addClass('has_image').find('#content_image').removeAttr('style').find('img').removeAttr('style'); }
		if ( $content_pane.hasClass('has_video') )      { $content_video.prop('currentTime',0).trigger('pause'); }
		if ( $content_pane.hasClass('has_iframe') || $content_pane.hasClass('has_dir') ) { $selected_file().find('a').click(); }
		setContentHeight();
	}
	$('#reload_btn').on('click', function(e) {
		e.preventDefault();
		showWarning('resetContent');
	});

	//**********************//
	//***** NAVIGATION *****//
	function firstRowID(className) {
		return ( $('#tbody').find(':visible:not(.unchecked)').filter(className).length ? $('#tbody').find('tr:visible:not(.unchecked)').filter(className).first().attr('id') : null );
	}
	function prevRowID(className) {
        let row;
        if ( ['.audio','.video','.media'].includes(className) ) { row = $playing_file(); } else { row = $selected_file(); }
		return ( !row.length || !row.prevAll(':visible:not(.unchecked)').filter(className).length ) ? $('#tbody').find('tr:visible').filter(className).last().attr('id') : row.prevAll(':visible:not(.unchecked)').filter(className).first().attr('id');
	}
	function nextRowID(className) { // if nothing selected, or if no next row with classname, return first row with classname, else return next row with classname
        let row;
        if ( ['.audio','.video','.media'].includes(className) ) { row = $playing_file(); } else { row = $selected_file(); }
		return ( !row.length || !row.nextAll(':visible:not(.unchecked)').filter(className).length ) ? $('#tbody').find('tr:visible').filter(className).first().attr('id') : row.nextAll(':visible:not(.unchecked)').filter(className).first().attr('id');
	}
	// function lastRowID(className) {
	// return ( $('#tbody').find(':visible:not(.unchecked)').filter(className).length ? $('#tbody').find('tr:visible:not(.unchecked)').filter(className).last().attr('id') : null );
	// }
	function selectRowID(className,key) {
		let id = '';
		if ( key === 'ArrowUp' ) { id = prevRowID('.dir,.file'); }
		if ( key === 'ArrowLeft' ) { id = prevRowID(className); }
		if ( key === 'ArrowRight' ) { id = nextRowID(className); }
		if ( key === 'ArrowDown' ) { id = nextRowID('.dir,.file'); }
		return id;
	}
	// NAVIGATION: select GRID items by left/right arrow keys @ arrowNavigation();
	function gridNavigation(key) {
		let id; // = grid item data-id = corresponding dir_list item id.
        let rowLength = 0; // $content_grid.hasClass('has_grid') || $('#content_font').hasClass('has_font_grid')
        if ( $('#content_grid').hasClass('has_image_grid') ) { rowLength = (Math.round( $('#content_grid').innerWidth() / $('.image_grid_item').outerWidth()) - 1 ) ;}
        switch(key) {
            case 'ArrowDown':
                if ( $('#content_grid .selected').nextAll().eq(rowLength).length === 1 ) { id = $('#content_grid .selected').nextAll().eq(rowLength).attr('data-id'); } else { id = $('#content_grid > div').first().attr('data-id'); }
                break;
            case 'ArrowUp':
                if ( $('#content_grid .selected').prevAll().eq(rowLength).length === 1 ) { id = $('#content_grid .selected').prevAll().eq(rowLength).attr('data-id'); } else { id = $('#content_grid > div').last().attr('data-id'); }
                break;
            case 'ArrowLeft':
                if ( $('#content_grid .selected').prev().length === 1 ) { id = $('#content_grid .selected').prev().attr('data-id'); } else { id = $('#content_grid > div').last().attr('data-id'); }
                break;
            case 'ArrowRight':
                if ( $('#content_grid .selected').next().length === 1 ) { id = $('#content_grid .selected').next().attr('data-id'); } else { id = $('#content_grid > div').first().attr('data-id'); }
                break;
        }
        if ( $content_pane.hasClass('has_hidden_grid') ) {
            $('#content_grid > div[data-id="'+ id +'"]').click();
        } else {
            selectThis(id);
        }
    }
	// NAVIGATION: FONTS and IMAGES by prev/next buttons
	$content_pane.on( 'click','#prev_btn, #next_btn', function(e) {
		e.stopPropagation();
		e.preventDefault();
		let key = $(this).attr('id') === 'prev_btn' ? 'ArrowLeft' : 'ArrowRight';
        if ( $('#content_font').hasClass('has_font_viewer') ) {
            glyphNavigation(key);
        } else {
            clickRow( selectRowID('.font,.image',key));
        }
	});
    // glyph navigation
    function glyphNavigation(key) {
        let rowLength = Math.round( $('#glyphs_container').innerWidth() / $('.glyph_container').outerWidth() - 1 );
        if ( $('#glyphs_container > .glyph_container.selected').length === 0 ) {
            if ( key === 'ArrowRight' || key === 'ArrowDown' ) { $('.glyph_container').first().addClass('selected').siblings().removeClass('selected'); }
            if ( key === 'ArrowLeft' || key === 'ArrowUp' ) { $('.glyph_container').last().addClass('selected').siblings().removeClass('selected'); }
        } else if ( $('#glyphs_container > .glyph_container.selected').length === 1 ) {
            if ( key === 'ArrowRight' ) { $('.glyph_container.selected').nextAll('.glyph_container').first().addClass('selected').siblings().removeClass('selected'); }
            if ( key === 'ArrowLeft' ) { $('.glyph_container.selected').prevAll('.glyph_container').first().addClass('selected').siblings().removeClass('selected'); }
            if ( key === 'ArrowDown' ) { if ( $('.glyph_container.selected').nextAll('.glyph_container').eq(rowLength).length === 1 ) { $('.glyph_container.selected').nextAll('.glyph_container').eq(rowLength).addClass('selected').siblings().removeClass('selected'); } else { $('.glyph_container').last().addClass('selected').siblings().removeClass('selected'); } }
            if ( key === 'ArrowUp' ) { if ( $('.glyph_container.selected').prevAll('.glyph_container').eq(rowLength).length === 1 ) { $('.glyph_container.selected').prevAll('.glyph_container').eq(rowLength).addClass('selected').siblings().removeClass('selected'); } else { $('.glyph_container').first().addClass('selected').siblings().removeClass('selected'); } }
        }
        if ( $('#content_font').hasClass('has_glyph') ) { $('.glyph_container.selected .glyph').click(); } // show the selected glyph
    }
	// NAVIGATION: MEDIA tracks by arrow left/right @ leftRightArrowNavigation() & button click; // handle shuffle or loop play, as well as normal continuous playback after end of track with ArrowRight
	function playPrevNextTrack(key) {
        if ( $('.playing').length === 0 ) { // Arrow L/R selects first/last audio file if nothing selected
            clickRow( selectRowID('.media',key) );
			playMedia('play');
        } else if ( $('.playing').length === 1 ) {
			let mediaClass = ( $('.playing').hasClass('audio') ? '.audio' : '.video' );
            // If shuffle play...
			if ( $body.hasClass('shuffle_audio') ) {
				let trackRowID = $audio_player.data('shufflelist').pop();
				if ( trackRowID !== undefined ) { // if shuffle list is not empty...
					showAudio( trackRowID ); // load audio...
					playMedia('play'); // and play
				} else if ( trackRowID === undefined ) { // if end of shufflelist...
					if ( $body.hasClass('loop_audio') ) { // and if loop audio, update the shufflelist and play
						updateShuffleList();
						playMedia('play');
					} else { // else load the first track
						showAudio( firstRowID( mediaClass ));
					}
				}
            // else if there is another media file selected, play it next
            } else if ( $(mediaClass).filter('.selected').length === 1 && !$('.media.selected').hasClass('playing') ) {
                showAudio( $('.media.selected').attr('id') );
                playMedia('play');
            } else {
                if ( $body.hasClass('loop_audio') || nextRowID( mediaClass ) !== firstRowID( mediaClass ) ) {
                    showAudio( selectRowID( mediaClass,key ) );
                    playMedia('play');
                } else {
                    showAudio( selectRowID( mediaClass,key ) );
                }
            }
        }
    }
        // NAVIGATION: Audio by prev/next audio buttons
	$('.prev_next_track_btn').on('click',function() {
		let key = ( $(this).attr('id') === 'prev_track' ? 'ArrowLeft' : 'ArrowRight' );
		playPrevNextTrack(key);
	});
	// NAVIGATION: Prev/Next Audio or Prev/Next File of same data-kind by arrow left/right
	function leftRightArrowNavigation(className,key) {
		if ( $('.selected').hasClass('audio') && $('.playing').length === 1 ) {
            playPrevNextTrack(key);
		} else if ( $('#toggle_info').hasClass('selected') ) { // if previewing directory source
            if ( $('#tbody .loaded').length > 0 ) { clickRow( $('#tbody .loaded').attr('id') ); } else { clickRow( selectRowID('.dir,.file',key) ); }
        } else {
			if ( $('.selected').length === 0 ) { // else select first/last row
                clickRow( selectRowID('.dir,.file',key) );
			} else { // else select prev/next row of same data-kind
				clickRow( selectRowID('.'+ $('.loaded,.video.playing').attr('data-kind'),key) );
			}
            if (className === 'video') { playMedia('play'); }
		}
	}
    function upDownArrowNavigation(key) {
        let row = $(document.getElementById(selectRowID('.dir,.file',key)));
        if ( row.hasClass('audio') && $('.audio.playing').length === 1 ) { // just select audio file if another audio is playing
            selectThis( row.attr('id') );
		} else if ( $('#toggle_info').hasClass('selected') ) {
            if ( $('#tbody .loaded').length > 0 ) {
                clickRow( $('#tbody .loaded').attr('id') );
            } else {
                clickRow( selectRowID('.dir,.file:visible',key) );
            }
        } else {
            clickRow( selectRowID('.dir,.file',key) );
		}
    }
	// NAVIGATE directory index items by arrow up/down or left/right keys, with/without grid @ indexNavigation()
	function arrowNavigation(className,key) {
        if ( $content_pane.hasClass('has_grid') || $content_pane.hasClass('has_hidden_grid') ) { // Grid navigation: L/R arrow selects images and fonts only
            gridNavigation(key);
            if ( !$content_pane.hasClass('has_hidden_grid') ) { scrollThis('content_grid','selected'); }
		} else if ( $('#content_font').hasClass('has_font_viewer') ) { // if previewing font glyphs
            glyphNavigation(key);
            scrollThis('content_container','selected');
        } else if ( key === 'ArrowUp' || key === 'ArrowDown' ) {
            upDownArrowNavigation(key);
            scrollThis('tbody','selected');
		} else { // key === 'ArrowLeft" || key === 'ArrowRight'
            leftRightArrowNavigation(className,key);
            scrollThis('tbody','selected');
		}
	}
    // NAVIGATION: Main navigation by arrow keys
	function indexNavigation(key) {
		let className = ( $('.selected[data-kind]') === undefined ? $dir_list.find('tbody tr:visible').first().attr('data-kind') : $('.selected[data-kind]').attr('data-kind') );
		arrowNavigation(className,key);
	}

	// NAVIGATE items by typed string
	var str = '';
	function timeoutID() {
		return window.setTimeout( function() { str = ''; }, 1500 );
	}
	function alphaNav(e) { // Select Dir_List row by typed string; Todo: select next row by nearest letter
		let timer = timeoutID();
		if ( typeof timer === 'number' ) {
			window.clearTimeout( timer );
			timer = 0; // id
		}
		timeoutID();
		str += e.key;
		str = str.toLowerCase();
		if ( $('#dir_list').find('td.name[data-name^="'+ str +'"]').length ) {
			$('#dir_list').find('td.name[data-name^="'+ str +'"]').first().find('a').click();
            scrollThis('tbody','selected');
			// } else {
			// null; // replace this with some sort of fuzzy match function? TBD
		}
	}
	//***** END NAVIGATION *****//

	//***** CLICK TO SELECT/SHOW CONTENT *****//

	// CLICK element by id
	function clickThis(id) {
		let el = $(document.getElementById(id));
		if ( el.find('a').length > 0 ) { el.find('a').click(); } else { el.click(); }
	}
	// CLICK Row
	function clickRow(id) {
		selectThis(id);
		showContent(id);
	}
	$body.find('#tbody').on('click','tr', function(e) {
		e.preventDefault();
		e.stopPropagation();
        if ( $(this).hasClass('playing') ) {
            playPauseMedia();
        } else {
            showWarning( 'clickRow', $(this).attr('id') );
        }
	});
    // Show current dir source in $content_iframe
    $('#toggle_info').on('click',function(e) {
		e.stopPropagation();
        if ( $(this).hasClass('selected') ) {
            $('#close_btn').click();
        } else {
            showWarning( 'clickRow', $(this).attr('id') );
        }
    });

    // DOUBLE-CLICK Row to open directory
	function doubleClickRow(id) { // row.dir only
        let row = getElById(id);
		let $query_str = decodeURIComponentSafe(window.location.search);
		if ( $query_str === '' ) { $query_str = '?'; }
		const $current_index = row.prevAll('.dir:visible').length;
		if ( $query_str.indexOf('history') !== -1 ) {
			$query_str = $query_str.replace(/&selected=\d+/,'').replace(/&history=/,'&history='+ $current_index +'+');
		} else {
			$query_str = $query_str.replace(/&selected=\d+/,'') + '&history='+ $current_index;
		}
		window.location = row.find('a').attr('href') + $query_str;
	}
	$('#tbody').find('tr.dir').on('dblclick', function(e) {
		e.preventDefault();
		e.stopPropagation();
		showWarning( 'doubleClickRow', $(this).attr('id') );
	});
	// CLICK grid item
	$content_grid.on('click','div', function(e) {
		e.preventDefault();
        let id = $(this).attr('data-id');
        $(this).addClass('selected').siblings().removeClass('selected');
        getElById(id).click();
	});

	// HOVER Grid Item
	$content_grid.on('mouseenter','> div:not(.selected)',function() {
		thisRow($dir_list.find('a[href*="'+ thisLink(this) +'"]')).addClass('hovered');
	}).on('mouseleave','> div:not(.selected)',function() {
		thisRow($dir_list.find('a[href*="'+ thisLink(this) +'"]')).removeClass('hovered');
	});
	// HOVER Dir_list_row and highlight corresponding grid item
	$dir_list_row.hover(function() {
		if ( $content_grid.is(':visible') ) {
			$content_grid.find('[href*="'+ thisLink(this) +'"]').closest('div').addClass('hovered');
		}
	}, function() {
		if ( $content_grid.is(':visible') ) {
			$content_grid.find('.hovered').removeClass('hovered');
		}
	});

	//***** AUTOLOAD CONTENT: index files or files from the file shortcut list *****//
	function autoSelectFile() {
		let $query_prefs = getQueryPrefs();
		let $UI_pref_selected = ( $query_prefs.get('selected') === null ? '' : $query_prefs.get('selected') );
		if ( getQuery('file') !== undefined && getQuery('file').length > 0 && window.top == window.self ) { // load individual files
			clickRow( $dir_list.find('a[href*="'+ getQuery('file') +'"]').closest('tr').attr('id') );
			removeQuery('file');
		} else if ( $UI_pref_selected !== '' ) {
			clickRow( $dir_list.find('tr.dir:visible').eq($UI_pref_selected).attr('id') );
        } else if ( $body.hasClass('autoload_index_files') && $dir_list.find( 'a[href*="/index."]').length > 0 ) { // else load index file
			clickRow( $dir_list.find('a[href*="/index."]').closest('tr').attr('id') );
		} else if ( !$body.hasClass('has_media') ) { // else select first non-media item
//			clickRow( $dir_list.find('#tbody tr:visible:not(.media):not(.invisible):not(.ignored)').first(0).attr('id') );
		}
		if ( $body.hasClass('autoload_media') && $body.hasClass('has_media') ) { // else if audio and images, load cover art
			clickRow( firstRowID('.audio,.video') );
			if ( $playing_file() ) { scrollThis('tbody','playing'); }
		}
		if ( $selected_file() ) { scrollThis('tbody','selected'); }
	}

	// Autoload Cover Art
	function getImageNames() {
		let image_names = [];
		$image_files.each(function() {
			let name = $(this).find('td.name').attr('data-name');
			name = name.slice(0,name.lastIndexOf('.'));
			image_names.push( name );
		});
		return image_names;
	}
	function getCoverArtID() {
		const cover_names = ['cover','front'];
		const image_names = getImageNames();
		for ( let cover_name of cover_names ) {
			if ( image_names.includes(cover_name) ) { // file name = a cover name
				return $image_files.eq( image_names.indexOf(cover_name) ).attr('id');
			} else if ( image_names.some( name => name.startsWith(cover_name)) ) { // file name starts with a cover name
				return $image_files.find('td.name[data-name^="'+ cover_name +'"]').closest('tr').attr('id');
			} else if ( image_names.some( name => name.indexOf(cover_name) > 0 ) ) { // file name includes a cover name
				return $image_files.find('td.name[data-name*="'+ cover_name +'"]').closest('tr').attr('id');
			} else { // else use first image
				return $image_files.first().attr('id');
			}
		}
	}
	function autoLoadCoverArt() { // autoload cover art for audio if dir contains audio and images, and audio is loaded and non-image content is not loaded
        let bodyClasses = getClassList('top');
        if ( bodyClasses.contains( 'has_audio','has_images','autoload_media' ) && !getElById( firstRowID('.media') ).hasClass('video') ) {
			let $coverID = getCoverArtID();
			if ( $coverID !== undefined ) {
				let row = getElById($coverID);
				showContent($coverID);
				row.addClass('loaded');
                $('#title span').html(row.find('.name').attr('data-name'));
                setDimensions($('.loaded.image'));
            }
		}
	}

	//***** KEYBOARD EVENTS *****//
	$body.on('keydown',$dir_list,function(e) {
		const $selected = ( $('#content_font').hasClass('has_font_viewer') ? $('.glyph_container.selected .glyph') : $selected_file() );

		if ( $('#content_source').is(':focus') || $('#content_font div').is(':focus') && e.key !== 'Escape' ) {
			return;
		}
		// Disable all keydown events except return and tab when warning is shown
		if ( $('body').hasClass('has_warning') ) {
			if (e.key !== 'Enter' && e.key !== 'Tab' && e.key !== 'Shift' ) {
				e.preventDefault();
				return false;
			}
			if ( e.key === 'Enter' ) {
				e.preventDefault();
				e.stopPropagation();
				$('#warnings').find('button.focus').click();
			}
			if ( e.key === 'Tab' ) {
				e.preventDefault();
				e.stopPropagation();
				if ( $('#warnings').find('button.focus').length === 0 || $('#warnings').find('button.focus').prev('button').length === 0 ) {
					$('#warnings').find('button').last('button').focus().addClass('focus').siblings().removeClass('focus').blur();
				} else {
					$('#warnings').find('button.focus').prev('button').focus().addClass('focus').siblings().removeClass('focus').blur();
				}
			}
		}

		$(':focus').blur(); // Need this to able to select grid items after clicking close button (or other buttons).

		switch ( e.key ) {
		case 'ArrowUp':
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) { // Cmd/Ctrl + up arrow = go to parent directory
				if ( $('#parents_dir_menu + ul a').length < 1 ) {
					return;
				} else {
					showWarning( 'clickThis', $('#parent_dir_menu').attr('id') );
				}
				break;
			}
			if ( $('*[contentEditable="true"]').is(':focus') ) { // Allow arrow navigation within content_editable elements
				return;
			}
			e.preventDefault();
			showWarning( 'indexNavigation', 'ArrowUp' );
			break;
		case 'ArrowDown':
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey && $selected.hasClass('app') && $settings.apps_as_dirs === false ) { // Ignore Cmd/Ctrl + arrow or if focused element is content editable or open dir
				return;
			} else if ( $('*[contentEditable="true"]' ).is(':focus') ) {
				return;
			} else if ( (e.ctrl || e.metaKey) && $selected.hasClass('dir') ) {
				$selected.find('a').trigger('dblclick');
				break;
			}
			e.preventDefault();
			showWarning( 'indexNavigation', 'ArrowDown' );
			break;
		case 'ArrowLeft':
			if ( (e.ctrl || e.metaKey) || (e.ctrl && e.metaKey) ) {
				return;
			} else if ( $('*[contentEditable="true"]').is(':focus') ) { // Ignore Cmd/Ctrl + arrow or if focused element is content editable
				return;
			}
			if ( (e.altKey && e.shiftKey) || e.altKey && !e.metaKey && !e.ctrlKey ) { // Skip audio 30s/10s: Opt-Shift-Arrow/Opt-Arrow
				mediaSkip(e);
				return;
			} else {
				showWarning( 'indexNavigation','ArrowLeft' );
			}
			break;
		case 'ArrowRight':
			if ( e.metaKey && !e.altKey && !e.shiftKey && $selected.hasClass('dir') ) { // Open dir with Cmd/Ctrl + Right Arrow
				$selected.find('a').trigger('dblclick');
				return;
			}
			if ( (e.ctrl || e.metaKey) || (e.ctrl && e.metaKey) ) { // Ignore Cmd/Ctrl + arrow or if focused element is content editable
				return;
			} else if ( $('*[contentEditable="true"]').is(':focus') || $selected.hasClass('dir ignore') ) {
				return;
			}
			if ( (e.altKey && e.shiftKey) || e.altKey && !e.metaKey && !e.ctrlKey ) { // Skip audio 30s/10s: Opt-Shift-Arrow/Opt-Arrow
				mediaSkip(e);
				return;
			} else {
				showWarning( 'indexNavigation','ArrowRight' );
			}
			break;
		case ' ': // space
			if ( $content_pane.hasClass('has_audio') || $content_pane.hasClass('has_video') ) { // Play/pause media (space bar)
				e.preventDefault();
				playPauseMedia();
			} else {
				alphaNav(e);
			}
			break;
		case 'Enter': // Open directories (or ignore)
			if ( $selected.hasClass('app') && $settings.apps_as_dirs === false ) {
				break;
			} else {
				if ( $selected.hasClass('dir') ) {
					$selected.find('a').trigger('dblclick');
				} else if ( $selected.hasClass('playing') || $selected.hasClass('video') ) { // content_audio or content_video
					playPauseMedia();
				} else {
                    $selected.click();
				}
			}
			break;
			// Alphabetical navigation
		case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
		case 'a': case 'b': case 'c':                     case 'f':           case 'h':           case 'j': case 'k': case 'l': case 'm': case 'n':           case 'p': case 'q':           case 's': case 't': case 'u': case 'v':           case 'x': case 'y': case 'z':
		case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':           case '`': case '~': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')':           case '+': case '[': case ']': case '{': case '}': /*case '\\':*/ case '|': case '/': case '.': case ',': case '?': case '–': case '—': case '\'': case '"': case '“': case '”': case '‘': case '’': case '…': case 'π':
		case '∫': case '∂': case 'ƒ': case '©': case '˙': case '∆': case '˚': case 'µ': case '®': case 'ß': case '†': case '√': case '∑': case '≈': case '¥': case 'Ω': case '¡': case '™': case '£': case '¢': case '∞': case '§': case '¶': case '•': case 'ª': case 'º': case '≠':
		case '⁄': case '€': case '‹': case '›': case 'fl': case '‡': case '°': case '·': case '‚': case '±': case '¯': case '˘': case '¿':
		case 'ı': case '': case '´': case '˝': case 'ˆ': case '': case '˜': case '‰': case 'ˇ': case '¨': case '◊': case '„': case '˛': case '¸':
			//            case 'α': case 'β': case 'γ': case 'δ': case 'ε': case 'ζ': case 'η': case 'θ': case 'ι': case 'κ': case 'λ': case 'μ': case 'ν': case 'ξ': case 'ο': case 'π': case 'ρ': case 'ς': case 'σ': case 'τ': case 'υ': case 'φ': case 'χ': case 'ψ': case 'ω': case 'ϑ': case 'ϒ': case 'ϖ':
			//            case 'Α': case 'Β': case 'Γ': case 'Δ': case 'Ε': case 'Ζ': case 'Η': case 'Θ': case 'Ι': case 'Κ': case 'Λ': case 'Μ': case 'Ν': case 'Ξ': case 'Ο': case 'Π': case 'Ρ': case 'Σ': case 'Σ': case 'Τ': case 'Υ': case 'Φ': case 'Χ': case 'Ψ': case 'Ω': case 'Θ': case 'ϒ':
			if ( !e.metaKey && !e.ctrlKey && !e.altKey ) {
				alphaNav(e);
			}
			break;
		case 'd': // Cmd/Ctrl + D: Toggle Details
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#show_details').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'e': // Cmd/Ctrl + E: Show Text Editor
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#text_editor_row').find('a').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'g': // Cmd/Ctrl + G: Show image Grid
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#grid_btn').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'i': // Cmd/Ctrl + I: Toggle Invisibles
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#show_invisibles').find('input').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'o': // Cmd/Ctrl + Shift + O: Open selected item in new window
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && e.shiftKey && !e.altKey ) {
				window.open( thisLink($selected_file()) );
			} else {
				alphaNav(e);
			}
			break;
		case 'r': // Cmd/Ctrl + Shift + R: Refresh
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#reload_btn').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'w': // Close content pane if Close button visible with Cmd/Crtl + W
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				if ( $content_pane.attr('class').indexOf('has_') > -1 || $('#toggle_info').hasClass('selected') || $body.hasClass('has_playlist') ) {
					e.preventDefault();
					$('#close_btn').click();
				}
			} else {
				alphaNav(e);
			}
			break;
		case '\\':
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#toggle_split_view').click();
			} else {
				alphaNav(e);
			}
			break;
		case '=':
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#increase').click();
			} else {
				alphaNav(e);
			}
			break;
		case '-':
			if ( (navigator.platform.match('Mac') ? e.metaKey && !e.ctrlKey : e.ctrlKey) && !e.shiftKey && !e.altKey ) {
				e.preventDefault();
				$('#decrease').click();
			} else {
				alphaNav(e);
			}
			break;
		case 'tab':
			break;
		case 'Escape':
			$('*:focus').blur();
			break;
		} // end switch
	});
	// ***** END KEYBOARD EVENTS ***** //

	// ***** GRID SETUP ***** //
	// Create Font Grid Items
	function fontGridItems() {
		let $font_grid_items_arr = [];
		let $font_files = $dir_list_body.find('.font');
		let fontGridStyles = $font_grid_styles.sheet;
		for ( let i = 0; i < $font_files.length; i++ ) {
			let newGridItem = showFont($font_files[i],true,fontGridStyles);
			$font_grid_items_arr.push( newGridItem );
		}
		return $font_grid_items_arr;
	}
	// Create Image Grid Items
	function imageGridItems() {
		let $image_grid_items_arr = [];
		let $image_files = $dir_list_body.find('.image:not(.ignore)');
		for ( let i = 0; i < $image_files.length; i++ ) {
            const id = $image_files.eq(i).attr('id');
			const $this_link = thisLink($image_files[i]);
			const exts = $row_types.image.filter( ext => $.inArray(ext, $row_settings.ignore) == -1 ); // decide which image files can be displayed
			const $title_name = $this_link.slice($this_link.lastIndexOf('/') + 1);
			if ( $.inArray( thisExt($image_files[i]), exts ) > -1 ) { // if this row file ext is in the image extension array
				let item = '<div class="image_grid_item" data-ID="'+ id +'" data-index="'+ i +'"><a href="'+$this_link+'"><img src="'+$this_link+'" title="'+$title_name+'" loading="lazy" /></a></div>';
				$image_grid_items_arr.push( item );
			}
		}
		return $image_grid_items_arr;
	}
	// Make Grids
	function makeGrids(id) {
		closeGrid();
        let $title = $('#title');
		$content_pane.removeClass('has_hidden_grid').addClass('has_grid');
		if ( id === 'show_font_grid' || !$body.hasClass('has_images') ) { // only show font grid
			$title.removeClass().addClass('font_grid');
			$content_grid.addClass('has_font_grid');
			$content_grid.append( fontGridItems() );
		} else if ( id === 'show_image_grid' || !$body.hasClass('has_fonts') ) { // only show image grid
			$title.removeClass().addClass('image_grid');
			$content_grid.addClass('has_image_grid');
			$content_grid.append( imageGridItems() );
		} else { // show grid of both images and fonts
			$title.removeClass();
			if ( $body.hasClass() ) { $content_grid.addClass('has_image_grid'); } else { $content_grid.addClass('has_grid'); }
			$content_grid.append( imageGridItems(), fontGridItems() );
		}
	}
	// Click grid button
	$('#sidebar_header').on('click', '#grid_btn, #show_font_grid, #show_image_grid', function(e) {
		e.stopPropagation();
        // if ( $content_pane.hasClass('has_grid') && $(this).attr('id') === 'grid_btn' ) {
            // closeGrid();
        // } else {
        $('#grid_btn').addClass('has_grid');
        makeGrids($(this).attr('id'));
        showGrid();
        // }
    });

	// ***** SCALE PREVIEWED IMAGES & FONTS ***** //
	// Scale Fonts
	function scaleFonts(e, incr, id) {
		const $em = parseInt(getComputedStyle(document.body).fontSize); // pts/em
		const getFontSize = function(el) { return parseFloat(el.css('font-size')); };
		if ( id === 'decrease' ) { incr = 1/incr; }
		if ( $content_pane.hasClass('has_grid') && ( $content_grid.hasClass('has_font_grid') || $content_grid.hasClass('has_grid') ) ) {
			$content_grid.css({'font-size':( getFontSize($content_grid)/$em * incr ) +'em'});
			return;
		}
		if ( $content_pane.hasClass('has_font') ) {
			$content_font.css({'font-size':( getFontSize($content_font)/$em * incr ) +'em'});
			return;
		}
        scrollThis('content_container','content_font')
	}
    function scaleGridImages(incr,id) {
        if ( id === 'decrease' ) { incr = 1/incr; }
        const $imageGridItem = $('.image_grid_item img');
			let $image_grid_item_width = Number.parseFloat( $imageGridItem.width(),10) * incr;
			let $image_grid_item_height = Number.parseFloat( $imageGridItem.height(),10) * incr;
			let $image_grid_item_maxwidth = Number.parseFloat( $imageGridItem.css('maxWidth'),10) * incr;
			let $image_grid_item_maxheight = Number.parseFloat( $imageGridItem.css('maxHeight'),10) * incr;
			// prevent reducing grid image size on first scale click:
			if ( $image_grid_item_width < $image_grid_item_maxwidth ) { $image_grid_item_width = $image_grid_item_maxwidth; }
			if ( $image_grid_item_height < $image_grid_item_maxheight ) { $image_grid_item_height = $image_grid_item_maxheight; }
			// set grid properties
			$content_grid.css({'grid-template-columns':'repeat(auto-fill, minmax('+ ($image_grid_item_width +16) +'px, auto ) )'});
			$content_grid.find('img').css({'max-width':( $image_grid_item_width ) +'px', 'max-height':( $image_grid_item_height ) +'px'});
			return;
    }
    // Zoom Images on click
    function scaleImages(e,incr,id) {
        const $this_image = $content_image.find('img');
        const $this_link = $this_image.attr('src');
        const $content_container = $('#content_container');
        let CC_width = function() { return Math.round($content_container.width()) };
        let CC_height = function() { return Math.round($content_container.height()) };
        const $this_width = Math.round($this_image.width());
        const $this_height = Math.round($this_image.height());
        // scale grid images
        if ( $content_pane.hasClass('has_grid') && ( $content_grid.hasClass('has_image_grid') || $content_grid.hasClass('has_grid') ) ) {
            scaleGridImages(incr,id);
        } else { // scale single images
            getDimensions( $this_link, function( width, height ) {
                const $this_outer_width = Math.round($this_image.outerWidth(true));
                // scale images by increment
                if ( incr !== undefined && id !== undefined ) {
                    $content_pane.addClass('has_zoom_image').removeClass('has_image'); // remove zoom classes in case window resized after zoom
                    if ( id === 'increase' ) {// && $this_width < width && $this_height < height) {
                        $content_image.add($this_image).css({'width':$this_width * incr, 'height': 'auto', 'max-width':'none', 'max-height':'none' });
                    }
                    if ( id === 'decrease' && ( $this_width >= 1 && $this_height >= 1 ) ) {
                        $content_image.add($this_image).css({'width':$this_width / incr, 'height': 'auto', 'max-width':'none', 'max-height':'none' });
                    }
                    // keep images centered when scaling
                    if ( Math.round($this_image.width()) >= CC_width() ) {
                        $content_container.scrollLeft( ( Math.round( ( $this_image.outerWidth(true) ) - CC_width() ) )/2 ) ;
                    }
                    if ( Math.round($this_image.height()) <= CC_height() ) {
                        $content_image.css({ 'top':( CC_height() - Math.round( $this_image.height() ) )/2 });
                    } else {
                        $content_image.css({ 'top':0 });
                        $content_container.scrollTop( ( Math.round($this_image.outerHeight(true)) - CC_height())/2 ) ;
                    }
                // else zoom single image on click
                } else {
                    $content_image.removeAttr('style').find('img').removeAttr('style');
                    setContentHeight(); // needed to ensure current element positions/dimensions are set (for some reason; w/o, img_offset, etc. are inaccurate)
                    // but don't zoom small images:
                    if ( width <= CC_width() && height <= CC_height() ) {
                        $content_pane.removeClass('has_zoom_image').addClass('has_image');
                        $content_image.css({'top':$('#content_header').height()}).find('img').css({'cursor':'pointer'});
                        return;
                    }

                    const $CC_offset = $content_container.offset();
                    const $img_offset = $this_image.offset();
                    // x,y coordinates of zoom click as percentage of image width/height
                    const percentX = (e.pageX - $img_offset.left)/$this_width;
                    const percentY = (e.pageY - $img_offset.top)/$this_height;
                    // calculate scroll by pixel coordinates of full-size image - click coordinates and content_container offsets
                    const scrollX = (width * percentX) - e.pageX + $CC_offset.left;
                    const scrollY = (height * percentY) - e.pageY + $CC_offset.top;
                    $content_pane.toggleClass('has_image has_zoom_image');
                    if ( width > CC_width() && height < CC_height() || $this_width < CC_width() ) {
                        $content_container.scrollLeft( scrollX );
                        $content_image.css({ 'top':( CC_height() - Math.round( $this_image.height() ) )/2 });
                    }
                    if ( width < CC_width() && height > CC_height() ) {
                        $content_image.css({ 'top': 0 });
                        $content_container.scrollTop( scrollY );
                    }
                    if ( width > CC_width() && height > CC_height() ) {
                        $content_image.css({ 'top': 0 });
                        $content_container.scrollLeft( scrollX ) ;
                        $content_container.scrollTop( scrollY );
                    }
                    if ( $content_pane.hasClass('has_image') ) {
                        $content_image.css({'top':$('#content_header').height() });
                    }
                }
                setDimensions($('.selected.image,.loaded.image'));
            });
        }
    }

    // Soom single image on click
	$content_image.on('click','img', function(e) {
        scaleImages(e);
    });
	// Scale Fonts and Images
	function scalePreviewItems(e,id) { // combine scaling into one function
		scaleImages(e, 1.125, id );
		scaleFonts(e, 1.125, id );
	}
	// Scale Button
	$('#scale').on('click','span',function(e) {
		e.preventDefault();
		e.stopPropagation();
		let id = $(this).attr('id');
		scalePreviewItems(e,id);
	});
	// ***** END SCALE PREVIEW ITEMS ***** //


	// ***** AUDIO CONTENT ***** //
	// Update Playlist
	function updatePlaylist() {
		let playlist = [];
		$audio_files.not('.unchecked').each(function() {
			playlist.push( thisID( $(this) ) );
		});
		return playlist;
	}
	// Randomize Shuffle List
	function shuffleArray(array) {
		for ( let i = array.length - 1; i > 0; i-- ) {
			const j = Math.floor(Math.random() * (i + 1));
			[array[i], array[j]] = [array[j], array[i]];
		}
		return array;
	}
    // Attach Shuffle List data to $audio_player
	function updateShuffleList(id) {
		if ( !$body.hasClass('shuffle_audio') ) {
			return;
		} else if ( id !== undefined ) { // don't include .playing and .unchecked track in shufflelist
			let shuffleList = $audio_player.data('shufflelist');
			if ( $(document.getElementById(id)).hasClass('unchecked') || $(document.getElementById(id)).hasClass('playing') ) {
				shuffleList.splice(shuffleList.indexOf(id), 1);
				$audio_player.data('shufflelist',shuffleList);
			} else {
				shuffleList.push(id);
				shuffleList = shuffleArray( shuffleList );
			}
		} else {
			let shuffleList = shuffleArray( updatePlaylist() );
			$audio_player.data('shufflelist',shuffleList);
		}
    }
	// Check/Uncheck Audio/Video Files
	function toggleChecked(e) {
		e.stopPropagation();
		$(this).blur();
		thisRow(this).toggleClass('unchecked');
		updateShuffleList(thisRow(this).attr('id'));
	}
	$media_files.on('click','input', toggleChecked );
	// Check/Uncheck all Audio/Video Files
	function toggleAllChecked(e) {
		e.stopPropagation();
		$dir_list_row.find('input').trigger('click');
		updateShuffleList();
	}
	$dir_list.find('#play_toggle').on('click', toggleAllChecked );

	// Is Playing
	function isPlaying(el) {
		return (el !== undefined && el.get(0).currentTime > 0 && !el.get(0).paused && !el.get(0).ended); // returns true if all conditions are true
	}
	// Play Media
	function playMedia(task) {
		if ( $playing_file().hasClass('audio') ) { $audio_player.trigger(task); } else { $content_video.trigger(task); }
	}
	// Skip media tracks +/-10/30 seconds
	function mediaSkip(e) {
		const factor = ( e.key === 'ArrowLeft' ? -1 : 1 ); // forward or backward?
		const skip = ( e.altKey && e.shiftKey ? 30 : e.altKey ? 10 : null ); // 30s or 10s?
		const $player = ( $playing_file().hasClass('audio') ? $audio_player : $content_video ); // audio or video?
		const time = $player.prop('currentTime'); // current time
		$player.prop('currentTime', time + factor*(skip)); // set time
	}

	// Play/Pause Audio/Video
	function playPauseMedia() {
		let $player = ( $content_pane.hasClass('has_audio') ? $('#audio') : $('#content_video') );
		if ( isPlaying( $player ) ) { $player.trigger('pause'); } else { $player.trigger('play'); }
	}
	// Play Next Track
	function playPrevNextTrackBtn(el) {
		let key = ( el.attr('id') === 'prev_track' ? 'ArrowLeft' : 'ArrowRight' );
		playPrevNextTrack(key);
	}
	// Prev/Next Track buttons
	$('.prev_next_track_btn').on( 'click', function() { playPrevNextTrackBtn( $(this) ); });

	// Toggle Shuffle Play
	$('#checkbox_div').on('click','#shuffle', function() {
		$body.toggleClass('shuffle_audio');
		updateShuffleList();
		if ( $body.hasClass('shuffle_audio') && $('.playing').length === 0 ) {
			playPrevNextTrack('ArrowRight');
		} else {
			// do nothing: i.e., allow current track to continue playing
		}
	});
	// Toggle Loop Play
	$('#checkbox_div').on('click','#loop', function() {
		$body.toggleClass('loop_audio');
		document.getElementById('audio').toggleAttribute('loop');
	});

	// Initialize Audio
	function initMedia() {
		$('#audio, #content_video').on('ended', function() {
			playPrevNextTrack('ArrowRight');
			scrollThis('tbody','playing');
		});
	}
	// ***** END AUDIO PLAYBACK ***** //

	// ***** IFRAME SETUP ***** //
	// For directory display or editable text files
	// If row is a directory, set up iFrameDirUI(); if it's an editable text document, set up iFrameTextEditingUI().
	function setUpIframeUI(bool) {
		if ( window.self !== window.top ) {
			const $textFiles = $row_types.markdown.concat($row_types.text, $row_types.code); // define which files are editable
			// if selected index item is a directory, set up the directory UI....
			if ( window.location.pathname.endsWith('/') ) {
				iFrameDirUI( $('#iframe_body') );
			}
			if ( JSON.parse(bool) === true && $textFiles.includes( window.location.pathname.slice( window.location.pathname.lastIndexOf('.') + 1 ) ) ) {
				$iFrame_head.append('<style>'+ $text_editing_style_rules +'</style>');
				$iFrame_head.append('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css"></link>');
                let splitClass = ( getQuery('split_view') === 'true' ? 'split_view' : '' );
				let viewClass = getQuery('default_text_view');
                let warnings = '<div id="warnings"><h3>Warning:</h3><p id="warning_unsaved">You have unsaved changes.</p><p id="warning_clear">Are you sure you want to clear all your text?</p><p id="warning_local">Can\'t load local directories or files from non-local web pages. Use your browser\'s bookmarks or enter the URL manually.</p><div><button id="warning_ignore_btn">Don\'t Save</button><button id="warning_cancel_btn" >Cancel</button><button id="warning_clear_btn">Clear</button><button id="warning_save_btn">Save</button><button id="warning_ok_btn">OK</button></div></div>';

				TextEditing( '#iframe_body' );
				$('#iframe_body').removeClass().addClass(splitClass).addClass(viewClass).prepend(warnings);
				$('#content_source').removeClass().prop('disabled',false);
			}
		}
	}
	// IFRAME DIRECTORY Prep
	function iFrameDirUI(el) { // el = iframeBody
		let parentLink = decodeURIComponentSafe(window.location.pathname);
            parentLink = parentLink.split('/').slice(0,-2).join('/') + window.location.search;
        let queryPrefs = window.location.search;
            queryPrefs = queryPrefs.slice(1).split('&');
            queryPrefs = queryPrefs.map(x => x.split('='));
        let prefs = Object.fromEntries(queryPrefs); // convert query array of arrays to object
        let sortPref = prefs.sort_by; // sort determined by parent's current sorting pref
        let numbersPref = prefs.show_numbers;
        let viewSourcePref = prefs.view_source;
        let iconsPref = prefs.use_custom_icons;
        if ( viewSourcePref === 'true' ) {
            return; // show raw directory index
        } else {
            if ( numbersPref === 'true' ) {
                $('#iframe_body').addClass('show_numbers');
            }
            if ( iconsPref === 'true' ) {
                $('#iframe_body').addClass('use_custom_icons');
            }
            $iFrame_head.find('style').remove();
            $iFrame_head.append('<style>'+ $iframe_styles +'</style>');

            const parentLinkCell = '<tr id="parent"><th colspan=4><a href="'+ parentLink +'">Parent Directory</a></th></tr>';
            const sortingRow = '<tr><th class="sorting" id="sort_by_name" colspan="2"><span>Name</span></th><th class="sorting" id="sort_by_default" colspan="2"><span>Default</span></th></tr><tr id="sorting_row"><th class="sorting" id="sort_by_ext"><span>Ext</span></th><th class="sorting" id="sort_by_size"><span>Size</span></th><th class="sorting" id="sort_by_date"><span>Date</span></th><th class="sorting" id="sort_by_kind"><span>Kind</span></th></tr>';
            const preppedIndex = makeNewIndex($('#iframe_body'),sortPref);
            const iFrameTable = $('<table id="dir_list"><thead id="thead">'+ parentLinkCell + sortingRow +'</thead><tbody id="tbody"></tbody></table>');
            // append prepped index
            el.empty().append(iFrameTable).find('tbody').append(preppedIndex);
            $('#iframe_body').find('#tbody').css({'top':$('#iframe_body').find('#thead').height() +'px'});
            $('#iframe_body').data('sort_direction',1).find('#dir_list').addClass('sort_by_'+ sortPref); // initial directory sort
        }
    }

    // IFRAME Directory sorting
    $('#iframe_body').on('click','.sorting', function() {
        const $dir_list_row = $('#iframe_body').find('#tbody').find('tr');
        const id = $(this).attr('id');
        if ( $('#iframe_body').data('sorting') !== id ) { // if clicking sorting item for the first time
            $('#iframe_body').data('sorting',id);
            $('#iframe_body').data('sorting',id).data('sort_direction', 1 );
            $(this).removeClass('down');
        } else { // clicking the same sorting item again -- reverse sort order
            $('#iframe_body').data('sort_direction', $('#iframe_body').data('sort_direction') * -1 );
            $(this).toggleClass('down');
        }
        const sort_direction = $('#iframe_body').data('sort_direction');
		const $sorted_index = sortDirList( $dir_list_row, id, sort_direction );
        $('#iframe_body').find('#dir_list').removeClass().addClass(id).find('#tbody').empty().append($sorted_index);
    });
    // ensure that iframe directory links include query string
    $('#iframe_body').on('click','#dir_list tr.dir a', function(e) {
        e.preventDefault();
        let link = $(this).attr('href') + window.location.search;
        window.location = link;
    });
    //***** TEXT EDITING PANE *****//
	function textEditorUI() { //
		if ( $content_text.children().length === 0 ) { // only add UI once
			$body.addClass('has_text');
			$content_pane.removeClass('has_dir');
			if ( $content_pane.hasClass('has_grid') ) { $content_pane.toggleClass('has_grid has_hidden_grid'); }
			TextEditing('#content_text');
			$content_text.find('#content_preview').html($content_text.find('#content_source').val()); // make sure any source text is also previewed.
			if ( getQuery('split_view') === 'true' || getQuery('default_text_view') === 'source_text' ) { $content_text.find('#content_source').focus(); }
		} else { // show text editor
            if ( !$body.hasClass('has_text') ) {
                $body.addClass('has_text');
            } else if ( $body.hasClass('has_text') || $body.hasClass('has_hidden_text') ) {
                $body.toggleClass('has_text has_hidden_text');
            }
			if ( $content_pane.hasClass('has_grid') ) { $content_pane.toggleClass('has_grid has_hidden_grid'); }
			if ( $content_pane.hasClass('has_hidden_grid ') ) { $content_pane.toggleClass('has_grid has_hidden_grid'); }
		}
		setContentTitle();
		setContentHeight();
	}
	// show text editor pane
	$('#text_editor, #text_editor_row').on('click', function(e) {
		e.preventDefault();
		textEditorUI();
	});

	// Main Text Editing Function
	function TextEditing(id) { // container_el = $content_text or $content_iframe body
        let container_el = $(id);
		const $srctxt = ( container_el.find('> pre').length ? container_el.find('> pre').text() : container_el.html() ); // source text equals file content or nothing

		MDbuildUI(id);

		const $toolbar = container_el.find('#toolbar');
		const $source = container_el.find('#content_source');
		const $preview = container_el.find('#content_preview');
		const $MDhandle = container_el.find('#text_editing_handle');

		MDsetupTextEditingUI(id,$srctxt);
		// Toolbar button functions
		$toolbar.on('click','li,span',function(e) {
			e.stopPropagation();
			MDtoolBarFunctions($(this).attr('id'));
		});
		$(window).on('resize',function() {
			$source.add($preview).add($MDhandle).attr('style','');
		});
		$('body#top').on('input', '#content_source', function() {
			$source.add($preview).css({'height':$('#main_content').height() - $('#content_header').height() - 32 });
		});

		// Resize
		$MDhandle.on('mousedown', function(e) {
			e.stopPropagation();
			MDresizeSplit($MDhandle,$source,$preview);
		});
		// Click labels to toggle checkboxes
		$preview.add($toolbar).on('click','label', function(e) {
			e.stopPropagation();
			$(this).siblings('input').click();
		});
		// Sync scroll
		$source.on('scroll',function() { MDsyncScroll(this); });
		$preview.on('scroll',function() { MDsyncScroll(this); });

		// TEXT EDITING
		// Generate Preview
		const $source_text = ( $source.length === 0 ? '' : $source.val() );
		MDmarkdown( $source_text, $preview );

		// Live preview update, and set edited classes for unsaved warning
		$source.on('input', function() {
			if ( !$('body').hasClass('edited') && $(this).parents('#top').length === 1 ) {
				$('body#top').addClass('edited');
			}
			if ( !$('body').hasClass('edited') && $(this).parents('#iframe_body').length === 1 ) {
				$('body#iframeBody').addClass('edited');
				sendMessage('top','iframe_edited','','');
			}
			MDlivePreview($source,$preview);
		});
		// Checklists
		MDsetChecklistClass();
		// Live checkboxes
		$preview.on('click','.checklist input',function(e) {
			e.stopPropagation();
			MDliveCheckBoxes($(this),$source,$preview);
		});
		// Preview TOC click navigation
		$preview.on('click','.table-of-contents a',function(e) {
			e.preventDefault();
			MDtocClick($(this),$preview);
		});
		$preview.on('click','.uplink',function(e) {
			e.stopPropagation();
			MDheaderClick($preview);
		});
	}
	///// END MAIN MD FUNCTION

	// MARKDOWN Functions
	// MD Build UI
	function MDbuildUI(id) {
		const toggleSplitBtn = $('<li id="toggle_split" title="Toggle Split"></li>');
		const syncScrollEl = $('<li id="sync_scroll"><input name="sync_scroll" type="checkbox"><label for="sync_scroll">Sync Scroll</label></li>');
		const toggleSrcBtn = $('<li id="show_source" title="Show Source"></li>');
		const togglePreviewBtn = $('<li id="show_preview" title="Show Preview"></li>');
		const clearTextBtn = $('<li id="clear_text" title="Clear Text">Clear</li>');
		const saveBtn = $('<li id="save_btn" title=""><div><span id="save_text"><a target="_blank">Save Source</a></span><span id="save_HTML">Save HTML</span></div></li>');
		const buttonsCont = $('<ul id="toolbar"></ul>');
		      buttonsCont.append(toggleSrcBtn, togglePreviewBtn, toggleSplitBtn, syncScrollEl, saveBtn, clearTextBtn);
		const textEditingUI = '<textarea id="content_source"></textarea><div id="content_preview" class="markdown-body"></div><div id="text_editing_handle"></div>';
		// append the UI to the container_el
		$(id).prepend(buttonsCont).append(textEditingUI);
	}

	// MD Set up UI
	function MDsetupTextEditingUI(id,sourceText) {
		$(id).find('pre').first().remove();
		$(id).find('#content_source').val(sourceText); // set source text from pre
		if ( getQuery('split_view') === 'true' ) { $('body').addClass('split_view'); } else { $('body').removeClass('split_view'); }
		if ( getQuery('default_text_view') === 'preview' ) { $('body').addClass('preview_text').removeClass('source_text'); } else { $('body').addClass('source_text').removeClass('preview_text'); }
		if ( getQuery('sync_scroll') === 'true' ) { $('#sync_scroll input').prop({checked:true}); }
	}
	// MD UI Buttons functions
	function MDtoolBarFunctions(id) {
		let $thisFileName;
		let container_el = $(getElById(id)).closest('body');
		let sourceEl = container_el.find('#content_source');
		let previewEl = container_el.find('#content_preview');
		if ( $body.hasClass('has_text') ) {
			$thisFileName = 'untitled';
		} else {
			$thisFileName = decodeURI(window.location.pathname.slice(window.location.pathname.lastIndexOf('/') + 1));
		}
		const $saveHTMLOpen = '<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css"></link><style></style><script></script></head><body lang="en" class="markdown-body">';
		const $saveHTMLClose = '</body></html>';
		switch (id) {
            case 'toggle_split':
                $('body').toggleClass('split_view').find('#content_source,#content_preview,#text_editing_handle').attr('style','');
                if ( container_el.hasClass('source_text') ) {
                    sourceEl.focus();
                    document.getElementById('content_source').setSelectionRange(0,0);
                }
                break;
            case 'show_source':
                container_el.removeClass('split_view preview_text').addClass('source_text').find('#content_source,#content_preview,#text_editing_handle').attr('style',''); // remove styles in case split has been resized
                sourceEl.css({'width':'100%'}).focus();
                document.getElementById('content_source').setSelectionRange(0,0);
                break;
            case 'show_preview':
                container_el.removeClass('split_view source_text').addClass('preview_text').find('#content_source,#content_preview,#text_editing_handle').attr('style','');
                break;
            case 'clear_text':
                container_el.addClass('has_warning').find('#warnings').removeClass().addClass('clear');
                break;
            case 'save_text':
                saveMD( $thisFileName, sourceEl.val() );
                break;
            case 'save_HTML':
                saveMD( $thisFileName.slice(0,$thisFileName.lastIndexOf('.') + 1) + 'html', $saveHTMLOpen + MDprepHTML(previewEl.html()) + $saveHTMLClose );
                break;
        }
	}
	// MD Custom pre- and post-processing for text.
	function MDaddHeaderIDs(match, p1, p2, p3, offset, string) { // create header ids for TOC
		return '<h'+ p1 +' id="'+ p3.toLowerCase().replace(/\s/g,'-') +'" ' + p2 +'>'+ p3;
	}
	function MDcustomPreProcess(src) {
		return src; // we're not doing anything here just yet...
	}
	function MDcustomPostProcess(html) {
		html = html.replace(/<(p|li|dt|dd)>\-*\s*\[\s*x\s*\]\s*(.+?)<\/(p|li|dt|dd)>$/gm,'<$1 class="checklist"><input type="checkbox" checked><label>$2</label></$3>') // checkboxes in p,li,dt,dd
			.replace(/<(p|li|dt|dd)>-*\s*\[\s{1,}\]\s*(.+?)<\/(p|li|dt|dd)>$/gm,'<$1 class="checklist"><input type="checkbox"><label>$2</label></$3>') // checkboxes
		//                .replace(/<li><p class="checklist">"/g,'<li class="checklist"><p>')
			.replace(/^<h(\d)([^>]*)>([^<]+)/gm, MDaddHeaderIDs) // add header IDs;
			.replace(/<\/h(\d)>/g,'<span class="uplink">&uarr;</span></h$1>');
		return html;
	}
	//MD Render markdown from preprocessed source text
	function MDmarkdown(sourceText,previewEl) {
		const MDit = window.markdownit({linkify:false,typography:false,html:true})
			.use(window.markdownitMultimdTable, {enableMultilineRows: true})
			.use(window.markdownitSub)
			.use(window.markdownitSup)
			.use(window.markdownitFootnote)
			.use(window.markdownitCentertext)
			.use(window.markdownitDeflist)
			.use(window.markdownitTocDoneRight)
        ;
		let MDpreview = MDit.render( MDcustomPreProcess( sourceText ) );
		previewEl.html( MDcustomPostProcess( MDpreview ) ); // set previewed html
	}
	// MD Live preview, add edited warning
	function MDlivePreview(sourceEl,previewEl) {
		MDmarkdown( sourceEl.val(),previewEl );
		MDsetChecklistClass();
	}

	// MD Live Checkboxes prep: find each instance of [ ] or [x] and replace text in index = to clicked checkbox in Preview.
	function MDreplaceAt(str, replacement, position) {
		str = str.substring(0, position) + replacement + str.substring(position + replacement.length);
		return str;
	}
	function MDreplaceNthSubStr(str,substr,replacement,index) {
		let count = 0;
		let found = substr.exec(str);
		while ( found !== null ) {
			if ( count === index ) {
				return MDreplaceAt(str, replacement, found.index );
			} else {
				count++;
				found = substr.exec(str);
			}
		}
	}
	// MD Live Checkboxes
	function MDliveCheckBoxes(checkbox,sourceEl,previewEl) {
		$('.checklist').removeClass('clicked');
		checkbox.closest('p,li,dt,dd').addClass('clicked');
		const thisIndex = previewEl.find('.checklist').index( $('.clicked') );
		const srctext = sourceEl.val();
		const substr = new RegExp(/\[\s*.\s*\]/g);
		const replacement = ( checkbox.is(':checked') ? '[x]' : '[ ]' );
		sourceEl.val( MDreplaceNthSubStr(srctext, substr, replacement, thisIndex) );
	}
	// MD Checkbox list class: Prevent checkbox lists from having list bullets
	function MDsetChecklistClass() {
		$('input[type="checkbox"]').closest('ul').addClass('no_list');
	}

	// MD Resize Split View
	function MDresizeSplit(handle,sourceEl,previewEl) {
		let $sidebarWidth = $('#sidebar').outerWidth();
		let $pageWidth = window.innerWidth;

		$(document).on('mousemove',function(e) {
			e.stopPropagation();
			e.preventDefault();
			let pageX = e.pageX;
			if ( pageX > $sidebarWidth + 100 && pageX < $pageWidth - 100 ) { // min widths
				handle.css({'left': pageX - $sidebarWidth - 4 + 'px'});
				sourceEl.css({'width': pageX - $sidebarWidth + 'px'});
				previewEl.css({'left': sourceEl.outerWidth() + 'px'});
			}
		});
		handle.on('mouseup',function() {
			$(document).off('mousemove');
		});
	}
	// MD UI Sync Scroll
	function MDpercentage(el) { return (el.scrollTop / (el.scrollHeight - el.offsetHeight)); }
	function MDsyncScroll(el1) {
		let el2 = ( el1.getAttribute('id') === 'content_preview' ? document.getElementById('content_source') : document.getElementById('content_preview') );
		if ( document.querySelector('input[name="sync_scroll"').checked ) {
			el2.scrollTo( 0, (MDpercentage(el1) * (el2.scrollHeight - el2.offsetHeight)).toFixed(0) ); // toFixed(0) prevents scrolling feedback loop
		}
	}
	// click TOC anchors
	function MDtocClick(el,previewEl) {
		let thisId = el.attr('href');
		if ( thisId ) {
			previewEl.scrollTop( $(thisId).offset().top - 48 );
		}
	}
	// click Headers to return to TOC or top
	function MDheaderClick(previewEl) {
		if ( previewEl.find('.table-of-contents').length > 0 ) {
			document.getElementsByClassName('table-of-contents')[0].scrollIntoView(true);
		} else {
			document.getElementById('preview').scroll(0,0);
		}
	}
	// MD Clear text source
	function clearText(container_el) {
		if ( window.top !== window.self ) { // if iframe, send message to top (to remove iframe_edited class)
			sendMessage('top','clear');
		}
		container_el.find('#content_source').show().focus().val('');
		container_el.find('#content_preview').empty();
		container_el.removeClass('edited has_warning');
	}
	// MD SAVE SOURCE or HTML
	function MDprepHTML(data) {
		data = data.replace(/<span\sclass="uplink">.<\/span>/g,'');
		return data;
	}
	function saveMD(filename, data) {
		let blob = new Blob([data], {type: 'text/plain'});
		let downloadEl = window.document.createElement('a');
		    downloadEl.href = window.URL.createObjectURL(blob);
		    downloadEl.download = filename;
		document.body.appendChild(downloadEl);
		    downloadEl.click();
		document.body.removeChild(downloadEl);
		URL.revokeObjectURL(blob);
		if ( window.top !== window.self ) { // if iframe, send message to top
			sendMessage('top','clear');
		}
		$('body,#content_source,#content_text').removeClass('edited');
	}
	// list of functions to remember while sending messages and then execute after warning button click
	function doFunction(funcName,args) {
		var funcDictionary = { 'setLocation':setLocation, 'resetContent':resetContent, 'closeContent':closeContent, 'clickThis':clickThis, 'clickRow':clickRow, 'doubleClickRow':doubleClickRow, 'indexNavigation':indexNavigation, 'clearText':clearText, 'null':null };
		return funcName === 'null' ? null : funcDictionary[funcName](args);
	}
	// Show warning after certain user actions if text editor or iframe has edited text; otherwise do the action.
	function showWarning(funcName,args) {
		// Don't show the warning if func = indexNavigation or clickRow; i.e., just hide text editor;
		// In other words, only show warning when changing directories or if iframe content has been edited
		if ( ( $('body').hasClass('edited') && funcName !== 'indexNavigation' && funcName !== 'clickRow' ) || $('body').hasClass('iframe_edited') ) {
			if ( $('body').hasClass('edited') ) { // show warning and text editor (if hidden)
				$body.addClass('has_warning').find('#warnings').removeClass().addClass('unloading');
				$body.removeClass('has_hidden_text').addClass('has_text');
			}
			if ( $('body').hasClass('iframe_edited') ) { // if iframe is edited, send unloading message
				sendMessage('iframe','unloading',funcName,args); // upon receipt of message, iframe will show its warning message, based on the funcName
			}
		} else {
			doFunction(funcName,args);
		}
	}
	// Send a message to iframe or parent
	function sendMessage(target,message,funcName,args) {
		var messageObj = { 'messageContent': message, 'functionName': funcName, 'arguments': args };
		if ( target === 'iframe' ) {
			let contentIFrame = document.getElementById('content_iframe');
			contentIFrame.contentWindow.postMessage( messageObj, '*' );
		}
		if ( target === 'top' ) {
			window.parent.postMessage( messageObj, '*');
		}
	}
	// Receive a message from iframe or parent, do appropriate action
	function receiveMessage(e) {
		if ( e.origin === 'null' || e.origin === $origin ) {
			let $message = e.data.messageContent;
			let funcName = e.data.functionName;
			let args = e.data.arguments;

			if ( $message === 'split_view' ) {
				$iframe_body.toggleClass('split_view');
			}
			if ( $message === 'default_text_view' ) {
				$iframe_body.toggleClass('preview_text source_text').removeClass('split_view');
			}
			// warn iframe that user wants to change iframes
			if ( $message === 'unloading' && !$iframe_body.hasClass('has_warning') ) {
				$iframe_body.addClass('has_warning').find('#warnings').removeClass().addClass('unloading').attr('data-function_name',funcName).attr('data-args',args);
			}
			// let top know iframe text has been edited
			if ( $message === 'iframe_edited' && !$('body#top').hasClass('iframe_edited') ) {
				$('body#top').addClass('iframe_edited');
			}
			if ( $message === 'ignore' || $message === 'clear' ) {
				$('body#top').removeClass('iframe_edited');
				if ( $message === 'ignore' ) { doFunction(funcName,args); }
			}
		}
	}
	window.addEventListener('message',receiveMessage,false);

	// Edited Warning buttons: what to do when the user clicks a warning button
	function editedWarningButtons(id) {
		let btn = $(document.getElementById(id));
		let container_el = btn.closest('body');
		let func = $('#warnings').attr('data-function_name');
		let args = $('#warnings').attr('data-args');
		switch(id) {
		case 'warning_ignore_btn': // do the user initiated func without saving the edited text
			if ( window.self !== window.top ) { // if iframe, send message to top
				sendMessage('top','ignore',func,args);
			}
			container_el.removeClass('edited has_text has_warning');
			clearText(container_el);
			break;
		case 'warning_cancel_btn': // cancel the func
			container_el.removeClass('has_warning').find('#warnings').removeClass();
			break;
		case 'warning_clear_btn': // clear the text editor
			clearText(container_el);
			break;
		case 'warning_save_btn': // save the text
			if ( window.top !== window.self ) { // if iframe, send message to top
				sendMessage('top','clear');
			}
			container_el.removeClass('edited has_warning');
			$('#save_text').click();
			break;
		case 'warning_ok_btn': // clear the text editor
			$('body').removeClass('has_warning').find('#warnings').removeClass('local');
			break;
		}
	}
	$('#warnings').on('click','button',function(e) {
		e.preventDefault();
		editedWarningButtons( $(this).attr('id') );
	});
	// Edited Warning overlay: prevent user clicks on rest of UI
	$('#overlay').on('click mousedown mouseup',function(e) {
		e.preventDefault();
		e.stopPropagation();
		return;
	});

	// END Text Editing

    // EXPERIMENTAL: Open playlist
    $('#open_playlist_label').on('click',function(e) { $('.menu').hide(); });
    // Open font
    $('#bookmarks').on('change','#open_playlist',function(e) {
        openPlaylist(e);
    });
    function convertPlaylist(items) {
        let preppedIndex = '';
        let preppedRow = '';
        let id = 0, rows, info, title, time = '0', display_time = '—', link, kind = '', display_kind, ext;
        items = items.replace(/\s*#EXTM3U.*\n/,'\n').replace(/^\*\n{2,}/gm,'\n');
        if ( items.indexOf('#EXTINF:') !== -1 ) {
            rows = items.split('#EXTINF:');
        } else {
            rows = items.split('\n');
        }
        for ( let row of rows ) {
            if ( row.indexOf('\n') !== -1 && row.trim().length > 0 ) {
                row = row.trim().split('\n');
                info = row[0];
                time = info.slice(0,info.indexOf(','));
                display_time = new Date(time * 1000).toISOString().substr(11, 8);
                title = info.slice(info.indexOf(',') + 1);
                link = row[1];
            } else {
                title = decodeURIComponentSafe(row.slice(row.lastIndexOf('/') + 1));
                link = row;
            }
            ext = link.slice(link.lastIndexOf('.') + 1);

            if ( $row_types.audio.includes( ext ) ) {
                kind = 'audio';
                display_kind = 'Audio';
            } else if ( $row_types.video.includes( ext ) ) {
                kind = 'video';
                display_kind = 'Video';
            }
            if ( kind !== '' ) { // only allow supported media types
                preppedRow = '<tr id="rowid-'+ id +'" class="file media '+ kind +'" data-ext="'+ ext +'"><td class="name" data-name="'+ title +'"><a class="icon" href="'+ link +'"><span><input type="checkbox" tabindex="-1" checked="true">'+ title +'</span></a></td><td class="size details" data-size="'+ time +'">'+ display_time +'</td><td class="date details" data-date="0">—</td><td class="kind details" data-kind="'+ kind +'">'+ display_kind +'</td><td class="ext details" data-ext="'+ ext +'"></td></tr>';
                preppedIndex += preppedRow;
            }
            id++;
        }
        closeGrid();
        closeContent();
        closeOtherContent();
        $dir_list.find('tbody').empty().addClass('playlist').append(preppedIndex);
        $dir_list.find('#stats').html(getIndexStats($dir_list.find('#tbody tr')));
        $body.addClass('has_playlist has_audio');
        if ( $body.hasClass('autoload_media') ) { $('#rowid-1').click(); }
        setContentTitle();
        setContentHeight();
        scrollThis('tbody','selected',false);
    }
    function openPlaylist(evt) {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            var files = evt.target.files;
            var reader = new FileReader();
            reader.onload = function(file) {
                convertPlaylist(file.target.result);
                return true;
            };
            reader.readAsText(files[0]);
            document.title = "Playlist: "+ files[0].name;
            $('#parents_dir_menu').find('> div').empty().html( files[0].name );
            $('#open_playlist').val('');
        } else {
            alert('File APIs are not fully supported in this browser.');
        }
    }

})();
// THE END!