// vim: et:ts=4:sw=4:sts=4:ft=javascript
'use strict';
pandora.addItem = function() {
pandora.api.add(function(result) {
Ox.Request.clearCache('find');
pandora.UI.set({
item: result.data.id,
itemView: 'info'
});
});
};
pandora.addEdit = function() {
// addEdit(isSmart, isFrom) or addEdit(edit) [=duplicate]
pandora.addFolderItem.apply(null, ['edit'].concat(Ox.slice(arguments)));
};
pandora.addFolderItem = function(section) {
// addFolderItem(section, isSmart, isFrom)
// or addFolderItem(section, list) [=duplicate]
var $folderList = pandora.$ui.folderList.personal,
isDuplicate = arguments.length == 2,
isItems = section == 'items',
isSmart, isFrom, list, listData, data,
ui = pandora.user.ui;
pandora.UI.set({showSidebar: true});
if (!isDuplicate) {
isSmart = arguments[1];
isFrom = arguments[2];
data = {
name: Ox._('Untitled'),
status: 'private',
type: !isSmart ? 'static' : 'smart'
};
if (isFrom) {
if (!isSmart) {
data.items = isItems
? ui.listSelection
: ui.edits[ui.edit].selection;
} else {
data.query = ui.find;
}
}
addList();
} else {
list = arguments[1];
listData = pandora.getListData();
data = {
name: listData.name,
status: listData.status,
type: listData.type
};
if (data.type == 'smart') {
data.query = listData.query;
}
pandora.api[isItems ? 'findLists' : 'findEdits']({
query: {conditions: [{key: 'id', value: list, operator: '=='}]},
keys: ['description']
}, function(result) {
data.description = result.data.items[0].description;
if (data.type == 'static') {
var query;
if (isItems) {
query = {
conditions: [{key: 'list', value: list, operator: '=='}],
operator: '&'
};
pandora.api.find({query: query}, function(result) {
if (result.data.items) {
pandora.api.find({
query: query,
keys: ['id'],
sort: [{key: 'id', operator: ''}],
range: [0, result.data.items]
}, function(result) {
var items = result.data.items.map(function(item) {
return item.id;
});
addList(items);
});
} else {
addList();
}
});
} else {
pandora.api.getEdit({id: list}, function(result) {
var items = result.data.clips.map(function(clip) {
return Ox.extend({
item: clip.item
}, clip.annotation ? {
annotation: clip.annotation
} : {
'in': clip['in'],
out: clip.out
});
});
addList(items);
});
}
} else {
addList();
}
});
}
function addList(items) {
pandora.api[isItems ? 'addList' : 'addEdit'](data, function(result) {
var newList = result.data.id;
if (items) {
if (isItems) {
pandora.api.addListItems({
list: newList,
items: items
}, function() {
getPosterFrames(newList);
});
} else {
pandora.api.addClips({
clips: items,
edit: newList
}, function(result) {
getPosterFrames(newList);
});
}
} else {
getPosterFrames(newList);
}
});
}
function getPosterFrames(newList) {
var query,
sortKey = Ox.getObjectById(pandora.site.itemKeys, 'votes')
? 'votes' : 'timesaccessed';
if (!isDuplicate) {
(isItems ? Ox.noop : pandora.api.getEdit)({id: newList}, function(result) {
Ox.print('RESULT::::', result.data)
query = isItems ? {
conditions: [{key: 'list', value: newList, operator: '=='}],
operator: '&'
} : {
conditions: Ox.unique(result.data.clips.map(function(clips) {
return {key: 'id', value: clip.item, operator: '=='};
})),
operator: '|'
};
pandora.api.find({
query: {
conditions: [{key: 'list', value: newList, operator: '=='}],
operator: '&'
},
keys: ['id', 'posterFrame'],
sort: [{key: sortKey, operator: ''}],
range: [0, 4]
}, function(result) {
var posterFrames = result.data.items.map(function(item) {
return {item: item.id, position: item.posterFrame};
});
posterFrames = posterFrames.length == 1
? Ox.repeat([posterFrames[0]], 4)
: posterFrames.length == 2
? [posterFrames[0], posterFrames[1], posterFrames[1], posterFrames[0]]
: posterFrames.length == 3
? [posterFrames[0], posterFrames[1], posterFrames[2], posterFrames[0]]
: posterFrames;
setPosterFrames(newList, posterFrames);
});
});
} else {
pandora.api[isItems ? 'findLists' : 'findEdits']({
query: {
conditions: [{key: 'id', value: list, operator: '=='}],
operator: '&'
},
keys: ['posterFrames']
}, function(result) {
setPosterFrames(newList, result.data.items[0].posterFrames);
});
}
}
function setPosterFrames(newList, posterFrames) {
pandora.api[isItems ? 'editList' : 'editEdit']({
id: newList,
posterFrames: posterFrames
}, function() {
reloadFolder(newList);
});
}
function reloadFolder(newList) {
pandora.$ui.folder[0].options({collapsed: false});
Ox.Request.clearCache(isItems ? 'findLists' : 'findEdits');
$folderList.bindEventOnce({
load: function() {
$folderList.gainFocus()
.options({selected: [newList]})
.editCell(newList, 'name', true);
pandora.UI.set(isItems ? {
find: {
conditions: [{key: 'list', value: newList, operator: '=='}],
operator: '&'
}
} : {
edit: newList
});
}
}).reloadList();
}
};
pandora.addList = function() {
// addList(isSmart, isFrom) or addList(list) [=duplicate]
pandora.addFolderItem.apply(null, ['items'].concat(Ox.slice(arguments)));
};
pandora.addText = function(options) {
var $folderList = pandora.$ui.folderList.personal;
options = options || {};
pandora.api.addText(options, function(result) {
reloadFolder(result.data.id);
});
function reloadFolder(newId) {
pandora.$ui.folder[0].options({collapsed: false});
Ox.Request.clearCache('findTexts');
$folderList.bindEventOnce({
load: function(data) {
$folderList.gainFocus()
.options({selected: [newId]})
.editCell(newId, 'name', true);
pandora.UI.set(pandora.user.ui.section.slice(0, -1), newId);
}
}).reloadList();
}
}
pandora.beforeUnloadWindow = function() {
if (pandora.firefogg)
return Ox._("Encoding is currently running\nDo you want to leave this page?");
//prevent error dialogs on unload
pandora.isUnloading = true;
};
pandora.changeFolderItemStatus = function(id, status, callback) {
var ui = pandora.user.ui,
folderItems = ui.section == 'items' ? 'Lists' : Ox.toTitleCase(ui.section),
folderItem = folderItems.slice(0, -1);
if (status == 'private') {
pandora.api['find' + folderItems]({
query: {conditions: [{key: 'id', value: id, operator: '=='}]},
keys: ['name', 'subscribers']
}, function(result) {
var name = result.data.items[0].name,
subscribers = result.data.items[0].subscribers;
if (subscribers) {
pandora.ui.makeListPrivateDialog(name, subscribers, function(makePrivate) {
if (makePrivate) {
changeListStatus();
} else {
callback({data: {
id: id,
status: 'public'
}});
}
}).open();
} else {
changeFolderItemStatus();
}
});
} else {
changeFolderItemStatus();
}
function changeFolderItemStatus() {
pandora.api['edit' + folderItem]({
id: id,
status: status
}, callback);
}
};
pandora.clickLink = function(e) {
var match = e.target.id.match(/^embed(\d+)$/)
if (match) {
pandora.$ui.textPanel.selectEmbed(parseInt(match[1]));
} else if (
e.target.hostname == document.location.hostname
&& !Ox.startsWith(e.target.pathname, '/static')
&& (window.self == window.top || pandora.isEmbeddableView(e.target.href))
) {
if (pandora.$ui.home && e.target.pathname != '/home') {
pandora.$ui.home.fadeOutScreen();
}
pandora.URL.push(e.target.pathname, true);
} else {
window.open('/url=' + encodeURIComponent(e.target.href), '_blank');
}
};
pandora.createLinks = function($element) {
function isExternalLink(target) {
return target.hostname != document.location.hostname
|| Ox.startsWith(target.pathname, '/static');
}
$element.on({
click: function(e) {
var $target = $(e.target);
if (
$target.is('a')
&& !$($target.parent()).is('.OxEditable')
&& !$($target.parent()).is('.OxEditableContent')
) {
e.preventDefault();
if (isExternalLink(e.target)) {
window.open('/url=' + encodeURIComponent(e.target.href), '_blank');
} else {
pandora.clickLink(e);
}
}
return false;
}
});
};
(function() {
pandora.doHistory = function(action, items, targets, callback) {
items = Ox.makeArray(items);
targets = Ox.makeArray(targets);
if (action == 'copy' || action == 'paste') {
addItems(items, targets[0], addToHistory);
} else if (action == 'cut' || action == 'delete') {
removeItems(items, targets[0], addToHistory);
} else if (action == 'edit') {
editItem(items[1], addToHistory);
} else if (action == 'join' || action == 'split') {
removeItems(items[0], targets[0], function() {
addItems(items[1], targets[0], addToHistory);
});
} else if (action == 'move') {
removeItems(items, targets[0], function() {
addItems(items, targets[1], addToHistory);
});
}
function addToHistory(result, addedItems) {
var actions = {
copy: 'Copying',
cut: 'Cutting',
'delete': 'Deleting',
edit: 'Editing',
join: 'Joining',
move: 'Moving',
paste: 'Pasting',
split: 'Splitting'
},
length = action == 'edit' ? 1
: action == 'join' || action == 'split' ? items[0].length
: items.length,
type = getType(items),
text = Ox._(actions[action]) + ' ' + (
length == 1 ? Ox._(type == 'item' ? pandora.site.itemName.singular : 'Clip')
: length + ' ' + Ox._(type == 'item' ? pandora.site.itemName.plural : 'Clips')
);
pandora.history.add({
action: action,
items: action == 'cut' || action == 'delete' ? [items]
: action == 'copy' || action == 'paste' ? [addedItems]
: action == 'edit' ? items
: action == 'join' || action == 'split' ? [items[0], addedItems]
: [items, addedItems], // move
positions: [],
targets: targets,
text: text
});
callback(result);
}
};
pandora.redoHistory = function(callback) {
var object = pandora.history.redo();
if (object) {
if (object.action == 'copy' || object.action == 'paste') {
addItems(object.items[0], object.targets[0], done);
} else if (object.action == 'cut' || object.action == 'delete') {
removeItems(object.items[0], object.targets[0], done);
} else if (object.action == 'edit') {
editItem(object.items[1], done);
} else if (object.action == 'join' || object.action == 'split') {
removeItems(object.items[0], object.targets[0], function() {
addItems(object.items[1], object.targets[0], done);
});
} else if (object.action == 'move') {
removeItems(object.items[0], object.targets[0], function() {
addItems(object.items[1], object.targets[1], done);
});
}
}
function done() {
doneHistory(object, callback);
}
};
pandora.undoHistory = function(callback) {
var object = pandora.history.undo();
if (object) {
if (object.action == 'copy' || object.action == 'paste') {
removeItems(object.items[0], object.targets[0], done);
} else if (object.action == 'cut' || object.action == 'delete') {
addItems(object.items[0], object.targets[0], done);
} else if (object.action == 'edit') {
editItem(object.items[0], done);
} else if (object.action == 'join' || object.action == 'split') {
removeItems(object.items[1], object.targets[0], function() {
addItems(object.items[0], object.targets[0], done);
});
} else if (object.action == 'move') {
removeItems(object.items[1], object.targets[1], function() {
addItems(object.items[0], object.targets[0], done);
});
}
}
function done() {
doneHistory(object, callback);
}
};
function addItems(items, target, callback) {
var clips, type = getType(items);
if (type == 'item') {
pandora.api.find({
query: {
conditions: [{key: 'list', operator: '==', value: target}],
operator: '&'
},
positions: items
}, function(result) {
var existingItems = Object.keys(result.data.positions),
addedItems = items.filter(function(item) {
return !Ox.contains(existingItems, item);
});
if (addedItems.length) {
pandora.api.addListItems({items: addedItems, list: target}, function(result) {
callback(result, addedItems);
});
} else {
callback(null, []);
}
});
} else {
pandora.api.addClips({
clips: getClipData(items),
edit: target,
index: pandora.user.ui.edits[pandora.user.ui.edit].selection.length
? Ox.getObjectById(
pandora.$ui.editPanel.options('clips'),
pandora.user.ui.edits[pandora.user.ui.edit].selection[0]
).index
: void 0
}, function(result) {
// adding clips creates new ids, so mutate items in history
items.splice.apply(items, [0, items.length].concat(getClipItems(result.data.clips)));
callback(result, items);
});
}
}
function doneHistory(object, callback) {
var list, listData,
type = getType(object.items),
ui = pandora.user.ui;
if (type == 'item' && ui.section == 'items') {
Ox.Request.clearCache('find');
object.targets.filter(function(list) {
return list != ui._list;
}).forEach(function(list) {
listData = pandora.getListData(list);
pandora.api.find({
query: {
conditions: [{key: 'list', value: list, operator: '=='}],
operator: '&'
}
}, function(result) {
pandora.$ui.folderList[listData.folder].value(
list, 'items', result.data.items
);
});
});
if (Ox.contains(object.targets, ui._list)) {
// FIXME: Why is this timeout needed?
setTimeout(pandora.reloadList, 250);
}
} else if (type == 'clip' && ui.section == 'edits') {
// FIXME: update edit list (once it has item count)
if (Ox.contains(object.targets, ui.edit)) {
pandora.$ui.editPanel.updatePanel();
}
}
callback && callback();
}
function editItem(item, callback) {
var clip = getClipData([item])[0],
id = getClipIds([item])[0];
pandora.api.editClip({
id: id,
'in': clip['in'],
out: clip.out
}, callback);
}
function getClipData(items) {
return items.map(function(clip) {
var split = clip.split('/'),
item = split[0],
points = split[1].split('-');
return Ox.extend({
item: item
}, points.length == 1 ? {
annotation: item + '/' + points[0]
} : {
'in': parseFloat(points[0]),
out: parseFloat(points[1])
});
});
}
function getClipIds(items) {
return items.map(function(clip) {
return clip.split('/').pop();
});
}
function getClipItems(clips) {
return clips.map(function(clip) {
return (
clip.annotation || clip.item + '/' + clip['in'] + '-' + clip.out
) + '/' + (clip.id || '');
});
}
function getType(items) {
return Ox.contains(items[0], '/') || Ox.contains(items[0][0], '/') ? 'clip' : 'item';
}
function removeItems(items, target, callback) {
var type = getType(items);
if (type == 'item') {
pandora.api.removeListItems({items: items, list: target}, callback);
} else {
pandora.api.removeClips({ids: getClipIds(items), edit: target}, callback);
}
}
}());
pandora.enableDragAndDrop = function($list, canMove, section) {
section = section || pandora.user.ui.section;
var $tooltip = Ox.Tooltip({
animate: false
}),
drag = {},
scrollInterval;
$list.bindEvent({
draganddropstart: function(data) {
if (section != pandora.user.ui.section) {
pandora.$ui.mainPanel.replaceElement(0,
pandora.$ui.leftPanel = pandora.ui.leftPanel(section)
);
}
drag.action = 'copy';
drag.ids = $list.options('selected'),
drag.item = drag.ids.length == 1
? $list.value(drag.ids[0], 'title') || 1
: drag.ids.length;
drag.source = pandora.getListData(),
drag.targets = {};
//fixme instead of a fixed timeout,
//bind to lists and update if they get new items
setTimeout(function() {
Ox.forEach(pandora.$ui.folderList, function($list) {
$list.addClass('OxDroppable').find('.OxItem').each(function() {
var $item = $(this),
id = $item.data('id'),
data = $list.value(id);
if (drag.targets) {
drag.targets[id] = Ox.extend({
editable: data.user == pandora.user.username
&& data.type == 'static',
selected: $item.is('.OxSelected')
}, data);
if (!drag.targets[id].selected && drag.targets[id].editable) {
$item.addClass('OxDroppable');
}
}
});
});
}, section != pandora.user.ui.section ? 2000 : 0);
$tooltip.options({title: getTitle()}).show(data.event);
canMove && Ox.UI.$window.on({
keydown: keydown,
keyup: keyup
});
},
draganddrop: function(data) {
var event = data.event;
$tooltip.options({
title: getTitle(event)
}).show(event);
if (scrollInterval && !isAtListsTop(event) && !isAtListsBottom(event)) {
clearInterval(scrollInterval);
scrollInterval = 0;
}
},
draganddroppause: function(data) {
var event = data.event, scroll,
$parent, $grandparent, $panel, title;
if (!pandora.user.ui.showSidebar) {
if (event.clientX < 16 && event.clientY >= 44
&& event.clientY < window.innerHeight - 16
) {
pandora.$ui.mainPanel.toggle(0);
}
} else {
$parent = $(event.target).parent();
$grandparent = $parent.parent();
$panel = $parent.is('.OxCollapsePanel') ? $parent
: $grandparent.is('.OxCollapsePanel') ? $grandparent : null;
if ($panel) {
title = $panel.children('.OxBar').children('.OxTitle')
.html().split(' ')[0].toLowerCase();
if (!pandora.user.ui.showFolder.items[title]) {
Ox.UI.elements[$panel.data('oxid')].options({collapsed: false});
}
}
if (!scrollInterval) {
scroll = isAtListsTop(event) ? -16
: isAtListsBottom(event) ? 16 : 0
if (scroll) {
scrollInterval = setInterval(function() {
pandora.$ui.folders.scrollTop(
pandora.$ui.folders.scrollTop() + scroll
);
}, 100);
}
}
}
},
draganddropenter: function(data) {
var $parent = $(data.event.target).parent(),
$item = $parent.is('.OxItem') ? $parent : $parent.parent(),
$list = $item.parent().parent().parent().parent();
if ($list.is('.OxDroppable')) {
$item.addClass('OxDrop');
drag.target = drag.targets[$item.data('id')];
} else {
drag.target = null;
}
},
draganddropleave: function(data) {
var $parent = $(data.event.target).parent(),
$item = $parent.is('.OxItem') ? $parent : $parent.parent();
if ($item.is('.OxDroppable')) {
$item.removeClass('OxDrop');
drag.target = null;
}
},
draganddropend: function(data) {
Ox.Log('', data, drag, '------------');
canMove && Ox.UI.$window.off({
keydown: keydown,
keyup: keyup
});
if (drag.target && drag.target.editable && !drag.target.selected) {
if (drag.action == 'copy' || (
drag.action == 'move' && drag.source.editable
)) {
if (section == 'items') {
var targets = drag.action == 'copy' ? drag.target.id
: [pandora.user.ui._list, drag.target.id];
pandora.doHistory(drag.action, data.ids, targets, function() {
Ox.Request.clearCache('find');
pandora.api.find({
query: {
conditions: [{key: 'list', value: drag.target.id, operator: '=='}],
operator: '&'
}
}, function(result) {
var folder = drag.target.status != 'featured' ? 'personal' : 'featured';
pandora.$ui.folderList[folder].value(
drag.target.id, 'items', result.data.items
);
cleanup(250);
});
drag.action == 'move' && pandora.reloadList();
});
} else if (section == 'edits') {
var targets = drag.action == 'copy' ? drag.target.id
: [pandora.user.ui.edit, drag.target.id];
pandora.doHistory(drag.action, data.ids, targets, function() {
Ox.print('FIXME, reload clipslist on move');
pandora.$ui.editPanel.updatePanel();
cleanup(250);
});
}
}
} else {
cleanup(0);
}
function cleanup(ms) {
drag = {};
clearInterval(scrollInterval);
scrollInterval = 0;
setTimeout(function() {
$('.OxDroppable').removeClass('OxDroppable');
$('.OxDrop').removeClass('OxDrop');
$tooltip.hide();
section != pandora.user.ui.section && setTimeout(function() {
pandora.$ui.mainPanel.replaceElement(0,
pandora.$ui.leftPanel = pandora.ui.leftPanel());
}, 500);
}, ms);
}
}
});
function getTitle() {
var image, text,
itemName = section == 'items' ? {
plural: Ox._(pandora.site.itemName.plural.toLowerCase()),
singular: Ox._(pandora.site.itemName.singular.toLowerCase())
} : {
plural: Ox._('clips'),
singular: Ox._('clip')
},
targetName = section == 'items' ? {
plural: Ox._('lists'),
singular: Ox._('list')
} : {
plural: Ox._('edits'),
singular: Ox._('edit')
};
if (drag.action == 'move' && section == 'edits' && pandora.user.ui.section == 'items') {
image = 'symbolClose';
text = Ox._(
'You can only remove {0}
from {1}.',
[itemName.plural, targetName.plural]
);
} else if (drag.action == 'move' && drag.source.user != pandora.user.username) {
image = 'symbolClose';
text = Ox._(
'You can only remove {0}
from your own {1}.',
[itemName.plural, targetName.plural]
);
} else if (drag.action == 'move' && drag.source.type == 'smart') {
image = 'symbolClose';
text = Ox._(
'You can\'t remove {0}
from smart {1}.',
[itemName.plural, targetName.plural]
);
} else if (drag.target && drag.target.user != pandora.user.username) {
image = 'symbolClose';
text = Ox._(
'You can only {0} {1}
to your own {2}',
[drag.action, itemName.plural, targetName.plural]
);
} else if (drag.target && drag.target.type == 'smart') {
image = 'symbolClose';
text = Ox._(
'You can\'t {0} {1}
to smart {2}',
[drag.action, itemName.plural, targetName.plural]
);
} else {
image = drag.action == 'copy' ? 'symbolAdd' : 'symbolRemove';
text = Ox._(Ox.toTitleCase(drag.action)) + ' ' + (
Ox.isString(drag.item)
? '"' + drag.item + '"'
: drag.item + ' ' + itemName[drag.item == 1 ? 'singular' : 'plural']
) + '
' + (
drag.target && !drag.target.selected
? Ox._(
'to the {0} "{1}"',
[targetName.singular, Ox.encodeHTMLEntities(drag.target.name)]
)
: Ox._(
'to ' + (
(section == 'items' && pandora.user.ui._list)
|| (section == 'edits' && pandora.user.ui.section == 'edits')
? 'another' : (section == 'items' ? 'a' : 'an')
) + ' {0}',
[targetName.singular]
)
);
}
return $('
')
.append(
$('
')
.css({
float: 'left',
width: '16px',
height: '16px',
padding: '2px',
border: '2px solid rgb(' + Ox.Theme.getThemeData().symbolDefaultColor.join(', ') + ')',
borderRadius: '12px',
margin: '3px 2px 2px 2px'
})
.append(
$('
')
.attr({src: Ox.UI.getImageURL(image)})
.css({width: '16px', height: '16px'})
)
)
.append(
$('
')
.css({
float: 'left',
margin: '1px 2px 2px 2px',
fontSize: '11px',
whiteSpace: 'nowrap'
})
.html(text)
);
}
function isAtListsTop(e) {
return pandora.user.ui.showSidebar
&& e.clientX < pandora.user.ui.sidebarSize
&& e.clientY >= 44 && e.clientY < 60;
}
function isAtListsBottom(e) {
var listsBottom = window.innerHeight - pandora.getInfoHeight();
return pandora.user.ui.showSidebar
&& e.clientX < pandora.user.ui.sidebarSize
&& e.clientY >= listsBottom - 16 && e.clientY < listsBottom;
}
function keydown(e) {
if (e.metaKey) {
drag.action = 'move';
$tooltip.options({title: getTitle()}).show();
}
}
function keyup(e) {
if (drag.action == 'move') {
drag.action = 'copy';
$tooltip.options({title: getTitle()}).show();
}
}
};
pandora.enterFullscreen = function() {
pandora.$ui.appPanel.size(0, 0);
pandora.user.ui.showSidebar && pandora.$ui.mainPanel.size(0, 0);
pandora.$ui.rightPanel.size(0, 0).size(2, 0);
!pandora.user.ui.showBrowser && pandora.$ui.contentPanel.css({
top: (-112 - Ox.UI.SCROLLBAR_SIZE) + 'px' // fixme: rightPanel.size(0, 0) doesn't preserve negative top of browser
});
pandora.user.ui.showBrowser && pandora.$ui.contentPanel.size(0, 0);
pandora.$ui.player.options({
height: pandora.$document.height() - 2,
width: pandora.$document.width() - 2
});
};
pandora.exitFullscreen = function() {
pandora.$ui.appPanel.size(0, 20);
pandora.user.ui.showSidebar && pandora.$ui.mainPanel.size(0, pandora.user.ui.sidebarSize);
pandora.$ui.rightPanel.size(0, 24).size(2, 16);
!pandora.user.ui.showBrowser && pandora.$ui.contentPanel.css({
top: 24 + (-112 - Ox.UI.SCROLLBAR_SIZE) + 'px' // fixme: rightPanel.size(0, 0) doesn't preserve negative top of browser
});
pandora.user.ui.showBrowser && pandora.$ui.contentPanel.size(0, 112 + Ox.UI.SCROLLBAR_SIZE);
};
pandora.getAllItemsTitle = function(section) {
section = section || pandora.user.ui.section;
return section == 'items'
? Ox._('All {0}', [Ox._(pandora.site.itemName.plural)])
: Ox._('{0} ' + Ox.toTitleCase(section), [pandora.site.site.name]);
};
pandora.getClipsItems = function(width) {
width = width || window.innerWidth
- pandora.user.ui.showSidebar * pandora.user.ui.sidebarSize - 1
- Ox.UI.SCROLLBAR_SIZE;
return Math.floor((width - 8) / (128 + 8)) - 1;
};
pandora.getClipsQuery = function(callback) {
// fixme: nice, but not needed
function addClipsConditions(conditions) {
conditions.forEach(function(condition) {
if (condition.conditions) {
addClipsConditions(condition.conditions);
} else if (
(condition.key == 'annotations'
||Ox.getIndexById(pandora.site.layers, condition.key) > -1)
&& condition.operator == '='
) {
clipsQuery.conditions.push(condition);
}
});
}
var clipsQuery = {
conditions: []
};
addClipsConditions(pandora.user.ui.find.conditions);
clipsQuery.operator = clipsQuery.conditions.length ? '|' : '&';
if (callback) {
if (pandora.user.ui._list) {
pandora.api.getList({id: pandora.user.ui._list}, function(result) {
if (result.data.type == 'smart') {
addClipsConditions(result.data.query.conditions);
}
callback(clipsQuery)
});
} else {
callback(clipsQuery)
}
} else {
return clipsQuery;
}
};
pandora.getClipVideos = function(clip, resolution) {
var currentTime = 0,
start = clip['in'] || 0,
end = clip.out;
resolution = resolution || pandora.user.ui.videoResolution;
return Ox.flatten(Ox.range(clip.parts).map(function(i) {
var item = {
src: pandora.getVideoURL(clip.item, resolution, i + 1)
};
if (currentTime + clip.durations[i] <= start || currentTime > end) {
item = null;
} else {
if (currentTime <= start && currentTime + clip.durations[i] > start) {
item['in'] = start - currentTime;
}
if (currentTime + clip.durations[i] >= end) {
item.out = end - currentTime;
}
if (item['in'] && item.out) {
item.duration = item.out - item['in']
} else if (item.out) {
item.duration = item.out;
} else if (!Ox.isUndefined(item['in'])) {
item.duration = clip.durations[i] - item['in'];
item.out = clip.durations[i];
} else {
item.duration = clip.durations[i];
item['in'] = 0;
item.out = item.duration;
}
}
currentTime += clip.durations[i];
return item;
}).filter(function(c) {
return !!c;
}));
};
(function() {
var itemTitles = {};
pandora.getDocumentTitle = function(itemData) {
var parts = [];
if (itemData) {
itemTitles[pandora.user.ui.item] = Ox.decodeHTMLEntities(
pandora.getItemTitle(itemData)
);
}
if (pandora.user.ui.section == 'items') {
if (!pandora.user.ui.item) {
parts.push(
pandora.user.ui._list
? pandora.user.ui._list.split(':').slice(1).join(':')
: pandora.getAllItemsTitle('items')
);
parts.push(Ox._(Ox.toTitleCase(pandora.user.ui.listView) + ' View'));
} else {
parts.push(itemTitles[pandora.user.ui.item] || pandora.user.ui.item);
parts.push(Ox._(Ox.toTitleCase(pandora.user.ui.itemView) + ' View'));
}
} else if (pandora.user.ui.section == 'edits') {
if (pandora.user.ui.edit) {
parts.push(pandora.user.ui.edit.split(':').slice(1).join(':'));
}
parts.push(Ox._('Edits'));
} else if (pandora.user.ui.section == 'texts') {
if (pandora.user.ui.text) {
parts.push(pandora.user.ui.text.split(':').slice(1).join(':'));
}
parts.push(Ox._('Texts'));
}
parts.push(pandora.site.site.name);
return parts.join(' – ');
};
}());
pandora.getDownloadLink = function(item, rightslevel) {
var torrent = pandora.site.video.torrent;
if (arguments.length == 2 && torrent &&
pandora.site.capabilities.canSeeItem.guest < rightslevel) {
torrent = false;
}
return '/' + item + (torrent ? '/torrent/' : '/download/');
};
pandora.getEditTooltip = function(title) {
return function(e) {
var $target = $(e.target);
return (
$target.is('a') || $target.parents('a').length
? Ox._('Shift+doubleclick to edit') : Ox._('Doubleclick to edit')
) + (title ? ' ' + title : '');
}
};
pandora.getFilterSizes = function() {
return Ox.splitInt(
window.innerWidth
- pandora.user.ui.showSidebar * pandora.user.ui.sidebarSize
- 1,
5
);
};
pandora.getFoldersHeight = function(section) {
section = section || pandora.user.ui.section;
var height = 0;
pandora.site.sectionFolders[section].forEach(function(folder, i) {
height += 16 + pandora.user.ui.showFolder[section][folder.id] * (
!!(folder.showBrowser && folder.items) * 40 + (folder.items || 1) * 16
);
});
return height;
};
pandora.getFoldersWidth = function(section) {
section = section || pandora.user.ui.section;
var width = pandora.user.ui.sidebarSize;
if (
pandora.$ui.appPanel
&& pandora.getFoldersHeight(section)
> window.innerHeight - 20 - 24 -16 - 1 - pandora.getInfoHeight(section)
) {
width -= Ox.UI.SCROLLBAR_SIZE;
}
return width;
};
pandora.getHash = function(state, callback) {
var embedKeys = [
'annotationsFont', 'annotationsRange', 'annotationsSort',
'embed',
'ignoreRights', 'invertHighlight',
'matchRatio',
'paused', 'playInToOut',
'showAnnotations', 'showCloseButton', 'showLayers', 'showTimeline',
'timeline', 'title'
],
isEmbed = state.hash && state.hash.anchor == 'embed',
isPrint = state.hash && state.hash.anchor == 'print',
printKeys = [],
removeKeys = [];
if (state.hash && state.hash.anchor && !isEmbed && !isPrint) {
delete state.hash.anchor;
}
if (state.hash && state.hash.query) {
if (isEmbed) {
state.hash.query.forEach(function(condition) {
if (!Ox.contains(embedKeys, condition.key)) {
removeKeys.push(condition.key);
}
});
} else if (isPrint) {
state.hash.query.forEach(function(condition) {
if (!Ox.contains(printKeys, condition.key)) {
removeKeys.push(condition.key);
}
});
} else {
state.hash.query.forEach(function(condition) {
var key = condition.key.split('.')[0];
if (pandora.site.user.ui[key] === void 0) {
removeKeys.push(condition.key);
}
});
}
state.hash.query = state.hash.query.filter(function(condition) {
return !Ox.contains(removeKeys, condition.key);
});
if (Ox.isEmpty(state.hash.query)) {
delete state.hash.query;
}
}
if (Ox.isEmpty(state.hash)) {
delete state.hash;
}
callback();
};
pandora.getInfoHeight = function(section, includeHidden) {
// Note: Either argument can be ommitted
// fixme: new, check if it can be used more
section = section || pandora.user.ui.section;
if (arguments.length == 1 && Ox.isBoolean(arguments[0])) {
section = pandora.user.ui.section;
includeHidden = arguments[0];
}
var height = 0, isVideoPreview;
if (pandora.user.ui.showInfo || includeHidden) {
isVideoPreview = section == 'items' && (
pandora.user.ui.item || (
pandora.user.ui.listSelection.length && !pandora.isClipView()
)
);
height = Math.min(
isVideoPreview
? Math.round(pandora.user.ui.sidebarSize / pandora.site.video.previewRatio) + 16
: pandora.user.ui.sidebarSize,
window.innerHeight - 109 // 20 menu + 24 bar + 64 (4 closed folders) + 1 resizebar
);
}
return height;
};
pandora.getItem = function(state, str, callback) {
if (state.type == pandora.site.itemName.plural.toLowerCase()) {
var secondaryId = pandora.site.itemKeys.filter(function(key) {
return key.secondaryId;
}).map(function(key) {
return key.id;
})[0],
sortKey = Ox.getObjectById(pandora.site.itemKeys, 'votes')
? 'votes'
: 'timesaccessed';
Ox.getObjectById(pandora.site.itemKeys, 'alt')
pandora.api.get({id: str, keys: ['id']}, function(result) {
if (result.status.code == 200) {
state.item = result.data.id;
callback();
} else {
(secondaryId ? pandora.api.find : Ox.noop)({
query: {
conditions: [{key: secondaryId, value: str, operator: '=='}],
operator: '&'
},
sort: [{key: sortKey, operator: '-'}],
range: [0, 1],
keys: ['id']
}, function(result) {
if (result && result.data.items.length) {
state.item = result.data.items[0].id;
callback();
} else {
pandora.api.find({
query: {
conditions: [{key: 'title', value: str, operator: '=='}],
operator: '&'
},
sort: [{key: sortKey, operator: '-'}],
range: [0, 100],
keys: ['id', 'title', sortKey]
}, function(result) {
if (result.data.items.length) {
var regexp = new RegExp('^' + Ox.escapeRegExp(str) + '$', 'i'),
items = result.data.items.map(function(item) {
return {
id: item.id,
// prefer title match over originalTitle match
sort: (item.title == str ? 1000000 : 0)
+ (parseInt(item[sortKey]) || 0)
// fixme: remove the (...|| 0) check
// once the backend sends correct data
};
});
state.item = items.sort(function(a, b) {
return b.sort - a.sort;
})[0].id;
}
callback();
});
}
});
}
});
} else if (state.type == 'texts') {
pandora.api.getText({id: str, keys: ['id', 'names', 'pages', 'type']}, function(result) {
if (result.status.code == 200) {
state.item = result.data.id;
callback();
} else {
// FIXME: add findText call here?
// FIXME: it's obscure that in the texts case,
// we have to set item to '', while for videos,
// it remains undefined
state.item = '';
callback();
}
});
} else if (state.type == 'edits') {
pandora.api.getEdit({id: str}, function(result) {
if (result.status.code == 200) {
state.item = result.data.id;
callback();
} else {
state.item = '';
callback();
}
});
} else {
callback();
}
};
pandora.getItemFind = function(find) {
var itemFind = '';
Ox.forEach(find.conditions, function(condition) {
if (
(
condition.key == '*' || condition.key == 'annotations'
|| Ox.getIndexById(pandora.site.layers, condition.key) > -1
)
&& condition.value.length
&& ['=', '=='].indexOf(condition.operator) > -1
) {
itemFind = condition.value;
return false;
}
})
return itemFind;
};
pandora.getItemIdAndPosition = function() {
var selected, ret, ui = pandora.user.ui;
function getIdAndPositionByClipId(clipId) {
var split = clipId.replace('-', '/').split('/');
return {
id: split[0],
position: parseFloat(split[1])
};
}
function getIdAndPositionByItemId(itemId) {
return {
id: itemId,
position: ui.videoPoints[itemId] ? ui.videoPoints[itemId].position : 0
};
}
if (!ui.item) {
if (
ui.listView == 'timelines'
&& (selected = ui.listSelection).length == 1
) {
ret = getIdAndPositionByItemId(selected[0]);
} else if (
['clip', 'map', 'calendar'].indexOf(ui.listView) > -1
&& pandora.$ui.clipList
&& (selected = pandora.$ui.clipList.options('selected')).length == 1
) {
ret = getIdAndPositionByClipId(selected[0]);
}
} else {
if (pandora.isVideoView()) {
ret = getIdAndPositionByItemId(ui.item);
} else if (
['clips', 'map', 'calendar'].indexOf(ui.itemView) > -1
&& pandora.$ui.clipList
&& (selected = pandora.$ui.clipList.options('selected')).length == 1
) {
ret = getIdAndPositionByClipId(selected[0]);
}
}
return ret;
}
pandora.getItemTitle = function(itemData) {
return (itemData.title || Ox._('Untitled')) + (
Ox.len(itemData.director) || itemData.year
? ' (' + (
Ox.len(itemData.director)
? itemData.director
: [Ox._('Unknown Director')]
).join(', ') + ')'
: ''
) + (itemData.year ? ' ' + itemData.year : '')
};
pandora.getLargeClipTimelineURL = function(item, inPoint, outPoint, type, callback) {
var fps = 25,
width = Math.ceil((outPoint - inPoint) * fps),
height = 64,
canvas = Ox.$('