code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','cs',{placeholder:{title:'Vlastnosti vyhrazeného prostoru',toolbar:'Vytvořit vyhrazený prostor',text:'Vyhrazený text',edit:'Upravit vyhrazený prostor',textMissing:'Vyhrazený prostor musí obsahovat text.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('placeholder','pt-br',{placeholder:{title:'Propriedades do Espaço Reservado',toolbar:'Criar Espaço Reservado',text:'Texto do Espaço Reservado',edit:'Editar Espaço Reservado',textMissing:'O espaço reservado deve conter texto.'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nl',{uicolor:{title:'UI Kleurenkiezer',preview:'Live voorbeeld',config:'Plak deze tekst in jouw config.js bestand',predefined:'Voorgedefinieerde kleurensets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','ug',{uicolor:{title:'ئىشلەتكۈچى ئارايۈزى رەڭ تاللىغۇچ',preview:'شۇئان ئالدىن كۆزىتىش',config:'بۇ ھەرپ تىزىقىنى config.js ھۆججەتكە چاپلايدۇ',predefined:'ئالدىن بەلگىلەنگەن رەڭلەر'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','it',{uicolor:{title:'Selettore Colore UI',preview:'Anteprima Live',config:'Incolla questa stringa nel tuo file config.js',predefined:'Set di colori predefiniti'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','de',{uicolor:{title:'UI Pipette',preview:'Live-Vorschau',config:"Fügen Sie diese Zeichenfolge in die 'config.js' Datei.",predefined:'Vordefinierte Farbsätze'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','pl',{uicolor:{title:'Wybór koloru interfejsu',preview:'Podgląd na żywo',config:'Wklej poniższy łańcuch znaków do pliku config.js:',predefined:'Predefiniowane zestawy kolorów'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','vi',{uicolor:{title:'Giao diện người dùng Color Picker',preview:'Xem trước trực tiếp',config:'Dán chuỗi này vào tập tin config.js của bạn',predefined:'Tập màu định nghĩa sẵn'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','hr',{uicolor:{title:'UI odabir boja',preview:'Pregled uživo',config:'Zalijepite ovaj tekst u Vašu config.js datoteku.',predefined:'Već postavljeni setovi boja'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','tr',{uicolor:{title:'UI Renk Seçicisi',preview:'Canlı önizleme',config:'Bu dizeyi config.js dosyasının içine yapıştırın',predefined:'Önceden tanımlanmış renk kümeleri'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fr',{uicolor:{title:'UI Sélecteur de couleur',preview:'Aperçu',config:'Collez cette chaîne de caractères dans votre fichier config.js',predefined:'Palettes de couleurs prédéfinies'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','zh-cn',{uicolor:{title:'用户界面颜色选择器',preview:'即时预览',config:'粘贴此字符串到你的 config.js 文件',predefined:'预定义颜色集'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','eo',{uicolor:{title:'UI Kolorselektilo',preview:'Vidigi la aspekton',config:'Gluu tiun signoĉenon en vian dosieron config.js',predefined:'Antaŭdifinita koloraro'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','da',{uicolor:{title:'Brugerflade på farvevælger',preview:'Vis liveeksempel',config:'Indsæt denne streng i din config.js fil',predefined:'Prædefinerede farveskemaer'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','nb',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','bg',{uicolor:{title:'ПИ избор на цвят',preview:'Преглед',config:'Вмъкнете този низ във Вашия config.js fajl',predefined:'Предефинирани цветови палитри'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','el',{uicolor:{title:'Διεπαφή Επιλογέα Χρωμάτων',preview:'Ζωντανή Προεπισκόπηση',config:'Επικολλήστε αυτό το κείμενο στο αρχείο config.js',predefined:'Προκαθορισμένα σύνολα χρωμάτων'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fi',{uicolor:{title:'Käyttöliittymän värivalitsin',preview:'Esikatsele',config:'Liitä tämä merkkijono config.js tiedostoosi',predefined:'Esimääritellyt värijoukot'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cy',{uicolor:{title:"Dewisydd Lliwiau'r UI",preview:'Rhagolwg Byw',config:"Gludwch y llinyn hwn i'ch ffeil config.js",predefined:"Setiau lliw wedi'u cyn-ddiffinio"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','no',{uicolor:{title:'Fargevelger for brukergrensesnitt',preview:'Forhåndsvisning i sanntid',config:'Lim inn følgende tekst i din config.js-fil',predefined:'Forhåndsdefinerte fargesett'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','mk',{uicolor:{title:'Палета со бои',preview:'Преглед',config:'Залепи го овој текст во config.js датотеката',predefined:'Предефинирани множества на бои'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','fa',{uicolor:{title:'انتخاب رنگ UI',preview:'پیشنمایش زنده',config:'این رشته را در فایل config.js خود بچسبانید.',predefined:'مجموعه رنگ از پیش تعریف شده'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','et',{uicolor:{title:'Värvivalija kasutajaliides',preview:'Automaatne eelvaade',config:'Aseta see sõne oma config.js faili.',predefined:'Eelmääratud värvikomplektid'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','uk',{uicolor:{title:'Color Picker Інтерфейс',preview:'Перегляд наживо',config:'Вставте цей рядок у файл config.js',predefined:'Стандартний набір кольорів'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','cs',{uicolor:{title:'Výběr barvy rozhraní',preview:'Živý náhled',config:'Vložte tento řetězec do Vašeho souboru config.js',predefined:'Přednastavené sady barev'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('uicolor','pt-br',{uicolor:{title:'Paleta de Cores',preview:'Visualização ao vivo',config:'Cole o texto no seu arquivo config.js',predefined:'Conjuntos de cores predefinidos'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nl',{devTools:{title:'Elementinformatie',dialogName:'Naam dialoogvenster',tabName:'Tabnaam',elementId:'Element ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','ug',{devTools:{title:'ئېلېمېنت ئۇچۇرى',dialogName:'سۆزلەشكۈ كۆزنەك ئاتى',tabName:'Tab ئاتى',elementId:'ئېلېمېنت كىملىكى',elementType:'ئېلېمېنت تىپى'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','it',{devTools:{title:'Informazioni elemento',dialogName:'Nome finestra di dialogo',tabName:'Nome Tab',elementId:'ID Elemento',elementType:'Tipo elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','de',{devTools:{title:'Elementinformation',dialogName:'Dialogfenstername',tabName:'Reitername',elementId:'Element ID',elementType:'Elementtyp'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pl',{devTools:{title:'Informacja o elemencie',dialogName:'Nazwa okna dialogowego',tabName:'Nazwa zakładki',elementId:'ID elementu',elementType:'Typ elementu'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','vi',{devTools:{title:'Thông tin thành ph',dialogName:'Tên hộp tho',tabName:'Tên th',elementId:'Mã thành ph',elementType:'Loại thành ph'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','hr',{devTools:{title:'Informacije elementa',dialogName:'Naziv prozora za dijalog',tabName:'Naziva jahača',elementId:'ID elementa',elementType:'Vrsta elementa'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','tr',{devTools:{title:'Eleman Bilgisi',dialogName:'İletişim pencere ismi',tabName:'Sekme adı',elementId:'Eleman ID',elementType:'Eleman türü'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fr',{devTools:{title:"Information sur l'élément",dialogName:'Nom de la fenêtre de dialogue',tabName:"Nom de l'onglet",elementId:"ID de l'élément",elementType:"Type de l'élément"}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','zh-cn',{devTools:{title:'元素信息',dialogName:'对话框窗口名称',tabName:'Tab 名称',elementId:'元素 ID',elementType:'元素类型'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','eo',{devTools:{title:'Informo pri la elemento',dialogName:'Nomo de la dialogfenestro',tabName:'Langetnomo',elementId:'ID de la elemento',elementType:'Tipo de la elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','en',{devTools:{title:'Element Information',dialogName:'Dialog window name',tabName:'Tab name',elementId:'Element ID',elementType:'Element type'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','da',{devTools:{title:'Information på elementet',dialogName:'Dialogboks',tabName:'Tab beskrivelse',elementId:'ID på element',elementType:'Type af element'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','nb',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','bg',{devTools:{title:'Информация за елемента',dialogName:'Име на диалоговия прозорец',tabName:'Име на таб',elementId:'ID на елемента',elementType:'Тип на елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','el',{devTools:{title:'Πληροφορίες Στοιχείου',dialogName:'Όνομα παραθύρου διαλόγου',tabName:'Όνομα καρτέλας',elementId:'ID Στοιχείου',elementType:'Τύπος στοιχείου'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fi',{devTools:{title:'Elementin tiedot',dialogName:'Dialogi-ikkunan nimi',tabName:'Välilehden nimi',elementId:'Elementin ID',elementType:'Elementin tyyppi'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cy',{devTools:{title:'Gwybodaeth am yr Elfen',dialogName:'Enw ffenestr y deialog',tabName:"Enw'r tab",elementId:'ID yr Elfen',elementType:'Math yr elfen'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','no',{devTools:{title:'Elementinformasjon',dialogName:'Navn på dialogvindu',tabName:'Navn på fane',elementId:'Element-ID',elementType:'Elementtype'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','fa',{devTools:{title:'اطلاعات عنصر',dialogName:'نام پنجره محاورهای',tabName:'نام برگه',elementId:'ID عنصر',elementType:'نوع عنصر'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','et',{devTools:{title:'Elemendi andmed',dialogName:'Dialoogiakna nimi',tabName:'Saki nimi',elementId:'Elemendi ID',elementType:'Elemendi liik'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','he',{devTools:{title:'מידע על האלמנט',dialogName:'שם הדיאלוג',tabName:'שם הטאב',elementId:'ID של האלמנט',elementType:'סוג האלמנט'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','uk',{devTools:{title:'Відомості про Елемент',dialogName:'Заголовок діалогового вікна',tabName:'Назва вкладки',elementId:'Ідентифікатор Елемента',elementType:'Тип Елемента'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','cs',{devTools:{title:'Informace o prvku',dialogName:'Název dialogového okna',tabName:'Název karty',elementId:'ID prvku',elementType:'Typ prvku'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','pt-br',{devTools:{title:'Informação do Elemento',dialogName:'Nome da janela de diálogo',tabName:'Nome da aba',elementId:'ID do elemento',elementType:'Tipo do elemento'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('devtools','gu',{devTools:{title:'પ્રાથમિક માહિતી',dialogName:'વિન્ડોનું નામ',tabName:'ટેબનું નામ',elementId:'પ્રાથમિક આઈડી',elementType:'પ્રાથમિક પ્રકાર'}});
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('docprops',{init:function(a){var b=new CKEDITOR.dialogCommand('docProps');b.modes={wysiwyg:a.config.fullPage};a.addCommand('docProps',b);CKEDITOR.dialog.add('docProps',this.path+'dialogs/docprops.js');a.ui.addButton('DocProps',{label:a.lang.docprops.label,command:'docProps'});}});
| JavaScript |
/*!
* jQuery Right-Click Plugin
*
* Version 1.01
*
* Cory S.N. LaViska
* A Beautiful Site (http://abeautifulsite.net/)
* 20 December 2008
*
* Visit http://abeautifulsite.net/notebook/68 for more information
*
* License:
* This plugin is dual-licensed under the GNU General Public License and the MIT License
* and is copyright 2008 A Beautiful Site, LLC.
*/
if(jQuery){(function(){$.extend($.fn,{rightClick:function(a){$(this).each(function(){$(this).mousedown(function(c){var b=c;if($.browser.safari&&navigator.userAgent.indexOf("Mac")!=-1&&parseInt($.browser.version,10)<=525){if(b.button==2){a.call($(this),b);return false}else{return true}}else{$(this).mouseup(function(){$(this).unbind("mouseup");if(b.button==2){a.call($(this),b);return false}else{return true}})}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseDown:function(a){$(this).each(function(){$(this).mousedown(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseUp:function(a){$(this).each(function(){$(this).mouseup(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},noContext:function(){$(this).each(function(){$(this)[0].oncontextmenu=function(){return false}});return $(this)}})})(jQuery)}; | JavaScript |
/** This file is part of KCFinder project
*
* @desc Helper object
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/
var _ = function(id) {
return document.getElementById(id);
};
_.nopx = function(val) {
return parseInt(val.replace(/^(\d+)px$/, "$1"));
};
_.unselect = function() {
if (document.selection && document.selection.empty)
document.selection.empty() ;
else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges)
sel.removeAllRanges();
}
};
_.selection = function(field, start, end) {
if (field.createTextRange) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end-start);
selRange.select();
} else if (field.setSelectionRange) {
field.setSelectionRange(start, end);
} else if (field.selectionStart) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
};
_.htmlValue = function(value) {
return value
.replace(/\&/g, "&")
.replace(/\"/g, """)
.replace(/\'/g, "'");
};
_.htmlData = function(value) {
return value
.replace(/\&/g, "&")
.replace(/\</g, "<")
.replace(/\>/g, ">")
.replace(/\ /g, " ");
}
_.jsValue = function(value) {
return value
.replace(/\\/g, "\\\\")
.replace(/\r?\n/, "\\\n")
.replace(/\"/g, "\\\"")
.replace(/\'/g, "\\'");
};
_.basename = function(path) {
var expr = /^.*\/([^\/]+)\/?$/g;
return expr.test(path)
? path.replace(expr, "$1")
: path;
};
_.dirname = function(path) {
var expr = /^(.*)\/[^\/]+\/?$/g;
return expr.test(path)
? path.replace(expr, "$1")
: '';
};
_.inArray = function(needle, arr) {
if ((typeof arr == 'undefined') || !arr.length || !arr.push)
return false;
for (var i = 0; i < arr.length; i++)
if (arr[i] == needle)
return true;
return false;
};
_.getFileExtension = function(filename, toLower) {
if (typeof(toLower) == 'undefined') toLower = true;
if (/^.*\.[^\.]*$/.test(filename)) {
var ext = filename.replace(/^.*\.([^\.]*)$/, "$1");
return toLower ? ext.toLowerCase(ext) : ext;
} else
return "";
};
_.escapeDirs = function(path) {
var fullDirExpr = /^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/,
prefix = "";
if (fullDirExpr.test(path)) {
var port = path.replace(fullDirExpr, "$4");
prefix = path.replace(fullDirExpr, "$1://$2")
if (port.length)
prefix += ":" + port;
prefix += "/";
path = path.replace(fullDirExpr, "$5");
}
var dirs = path.split('/');
var escapePath = '';
for (var i = 0; i < dirs.length; i++)
escapePath += encodeURIComponent(dirs[i]) + '/';
return prefix + escapePath.substr(0, escapePath.length - 1);
};
_.outerSpace = function(selector, type, mbp) {
if (!mbp) mbp = "mbp";
var r = 0;
if (/m/i.test(mbp)) {
var m = _.nopx($(selector).css('margin-' + type));
if (m) r += m;
}
if (/b/i.test(mbp)) {
var b = _.nopx($(selector).css('border-' + type + '-width'));
if (b) r += b;
}
if (/p/i.test(mbp)) {
var p = _.nopx($(selector).css('padding-' + type));
if (p) r += p;
}
return r;
};
_.outerLeftSpace = function(selector, mbp) {
return _.outerSpace(selector, 'left', mbp);
};
_.outerTopSpace = function(selector, mbp) {
return _.outerSpace(selector, 'top', mbp);
};
_.outerRightSpace = function(selector, mbp) {
return _.outerSpace(selector, 'right', mbp);
};
_.outerBottomSpace = function(selector, mbp) {
return _.outerSpace(selector, 'bottom', mbp);
};
_.outerHSpace = function(selector, mbp) {
return (_.outerLeftSpace(selector, mbp) + _.outerRightSpace(selector, mbp));
};
_.outerVSpace = function(selector, mbp) {
return (_.outerTopSpace(selector, mbp) + _.outerBottomSpace(selector, mbp));
};
_.kuki = {
prefix: '',
duration: 356,
domain: '',
path: '',
secure: false,
set: function(name, value, duration, domain, path, secure) {
name = this.prefix + name;
if (duration == null) duration = this.duration;
if (secure == null) secure = this.secure;
if ((domain == null) && this.domain) domain = this.domain;
if ((path == null) && this.path) path = this.path;
secure = secure ? true : false;
var date = new Date();
date.setTime(date.getTime() + (duration * 86400000));
var expires = date.toGMTString();
var str = name + '=' + value + '; expires=' + expires;
if (domain != null) str += '; domain=' + domain;
if (path != null) str += '; path=' + path;
if (secure) str += '; secure';
return (document.cookie = str) ? true : false;
},
get: function(name) {
name = this.prefix + name;
var nameEQ = name + '=';
var kukis = document.cookie.split(';');
var kuki;
for (var i = 0; i < kukis.length; i++) {
kuki = kukis[i];
while (kuki.charAt(0) == ' ')
kuki = kuki.substring(1, kuki.length);
if (kuki.indexOf(nameEQ) == 0)
return kuki.substring(nameEQ.length, kuki.length);
}
return null;
},
del: function(name) {
return this.set(name, '', -1);
},
isSet: function(name) {
return (this.get(name) != null);
}
};
_.md5 = function(string) {
var RotateLeft = function(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
};
var AddUnsigned = function(lX,lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4)
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4)
return (lResult & 0x40000000)
? (lResult ^ 0xC0000000 ^ lX8 ^ lY8)
: (lResult ^ 0x40000000 ^ lX8 ^ lY8);
else
return (lResult ^ lX8 ^ lY8);
};
var F = function(x, y, z) { return (x & y) | ((~x) & z); };
var G = function(x, y, z) { return (x & z) | (y & (~z)); };
var H = function(x, y, z) { return (x ^ y ^ z); };
var I = function(x, y, z) { return (y ^ (x | (~z))); };
var FF = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var GG = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var HH = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var II = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var ConvertToWordArray = function(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = [lNumberOfWords - 1];
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var WordToHex = function(lValue) {
var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2,2);
}
return WordToHexValue;
};
var x = [];
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
string = _.utf8encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a; BB = b; CC = c; DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD);
}
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toLowerCase();
};
_.utf8encode = function(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Object initializations
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.init = function() {
if (!this.checkAgent()) return;
$('body').click(function() {
browser.hideDialog();
});
$('#shadow').click(function() {
return false;
});
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$('#alert').unbind();
$('#alert').click(function() {
return false;
});
this.initOpeners();
this.initSettings();
this.initContent();
this.initToolbar();
this.initResizer();
this.initDropUpload();
};
browser.checkAgent = function() {
if (!$.browser.version ||
($.browser.msie && (parseInt($.browser.version) < 7) && !this.support.chromeFrame) ||
($.browser.opera && (parseInt($.browser.version) < 10)) ||
($.browser.mozilla && (parseFloat($.browser.version.replace(/^(\d+(\.\d+)?)([^\d].*)?$/, "$1")) < 1.8))
) {
var html = '<div style="padding:10px">Your browser is not capable to display KCFinder. Please update your browser or install another one: <a href="http://www.mozilla.com/firefox/" target="_blank">Mozilla Firefox</a>, <a href="http://www.apple.com/safari" target="_blank">Apple Safari</a>, <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>, <a href="http://www.opera.com/browser" target="_blank">Opera</a>.';
if ($.browser.msie)
html += ' You may also install <a href="http://www.google.com/chromeframe" target="_blank">Google Chrome Frame ActiveX plugin</a> to get Internet Explorer 6 working.';
html += '</div>';
$('body').html(html);
return false;
}
return true;
};
browser.initOpeners = function() {
if (this.opener.TinyMCE && (typeof(tinyMCEPopup) == 'undefined'))
this.opener.TinyMCE = null;
if (this.opener.TinyMCE)
this.opener.callBack = true;
if ((!this.opener.name || (this.opener.name == 'fckeditor')) &&
window.opener && window.opener.SetUrl
) {
this.opener.FCKeditor = true;
this.opener.callBack = true;
}
if (this.opener.CKEditor) {
if (window.parent && window.parent.CKEDITOR)
this.opener.CKEditor.object = window.parent.CKEDITOR;
else if (window.opener && window.opener.CKEDITOR) {
this.opener.CKEditor.object = window.opener.CKEDITOR;
this.opener.callBack = true;
} else
this.opener.CKEditor = null;
}
if (!this.opener.CKEditor && !this.opener.FCKEditor && !this.TinyMCE) {
if ((window.opener && window.opener.KCFinder && window.opener.KCFinder.callBack) ||
(window.parent && window.parent.KCFinder && window.parent.KCFinder.callBack)
)
this.opener.callBack = window.opener
? window.opener.KCFinder.callBack
: window.parent.KCFinder.callBack;
if ((
window.opener &&
window.opener.KCFinder &&
window.opener.KCFinder.callBackMultiple
) || (
window.parent &&
window.parent.KCFinder &&
window.parent.KCFinder.callBackMultiple
)
)
this.opener.callBackMultiple = window.opener
? window.opener.KCFinder.callBackMultiple
: window.parent.KCFinder.callBackMultiple;
}
};
browser.initContent = function() {
$('div#folders').html(this.label("Loading folders..."));
$('div#files').html(this.label("Loading files..."));
$.ajax({
type: 'GET',
dataType: 'json',
url: browser.baseGetData('init'),
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.dirWritable = data.dirWritable;
$('#folders').html(browser.buildTree(data.tree));
browser.setTreeData(data.tree);
browser.initFolders();
browser.files = data.files ? data.files : [];
browser.orderFiles();
},
error: function() {
$('div#folders').html(browser.label("Unknown error."));
$('div#files').html(browser.label("Unknown error."));
}
});
};
browser.initResizer = function() {
var cursor = ($.browser.opera) ? 'move' : 'col-resize';
$('#resizer').css('cursor', cursor);
$('#resizer').drag('start', function() {
$(this).css({opacity:'0.4', filter:'alpha(opacity:40)'});
$('#all').css('cursor', cursor);
});
$('#resizer').drag(function(e) {
var left = e.pageX - parseInt(_.nopx($(this).css('width')) / 2);
left = (left >= 0) ? left : 0;
left = (left + _.nopx($(this).css('width')) < $(window).width())
? left : $(window).width() - _.nopx($(this).css('width'));
$(this).css('left', left);
});
var end = function() {
$(this).css({opacity:'0', filter:'alpha(opacity:0)'});
$('#all').css('cursor', '');
var left = _.nopx($(this).css('left')) + _.nopx($(this).css('width'));
var right = $(window).width() - left;
$('#left').css('width', left + 'px');
$('#right').css('width', right + 'px');
_('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px';
_('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px';
_('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px';
browser.fixFilesHeight();
};
$('#resizer').drag('end', end);
$('#resizer').mouseup(end);
};
browser.resize = function() {
_('left').style.width = '25%';
_('right').style.width = '75%';
_('toolbar').style.height = $('#toolbar a').outerHeight() + "px";
_('shadow').style.width = $(window).width() + 'px';
_('shadow').style.height = _('resizer').style.height = $(window).height() + 'px';
_('left').style.height = _('right').style.height =
$(window).height() - $('#status').outerHeight() + 'px';
_('folders').style.height =
$('#left').outerHeight() - _.outerVSpace('#folders') + 'px';
browser.fixFilesHeight();
var width = $('#left').outerWidth() + $('#right').outerWidth();
_('status').style.width = width + 'px';
while ($('#status').outerWidth() > width)
_('status').style.width = _.nopx(_('status').style.width) - 1 + 'px';
while ($('#status').outerWidth() < width)
_('status').style.width = _.nopx(_('status').style.width) + 1 + 'px';
if ($.browser.msie && ($.browser.version.substr(0, 1) < 8))
_('right').style.width = $(window).width() - $('#left').outerWidth() + 'px';
_('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px';
_('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px';
_('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px';
};
browser.fixFilesHeight = function() {
_('files').style.height =
$('#left').outerHeight() - $('#toolbar').outerHeight() - _.outerVSpace('#files') -
(($('#settings').css('display') != "none") ? $('#settings').outerHeight() : 0) + 'px';
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Upload files using drag and drop
* @package KCFinder
* @version 2.51
* @author Forum user (updated by Pavel Tzonkov)
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initDropUpload = function() {
if ((typeof(XMLHttpRequest) == 'undefined') ||
(typeof(document.addEventListener) == 'undefined') ||
(typeof(File) == 'undefined') ||
(typeof(FileReader) == 'undefined')
)
return;
if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
var ords = Array.prototype.map.call(datastr, function(x) {
return x.charCodeAt(0) & 0xff;
});
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
var uploadQueue = [],
uploadInProgress = false,
filesCount = 0,
errors = [],
files = $('#files'),
folders = $('div.folder > a'),
boundary = '------multipartdropuploadboundary' + (new Date).getTime(),
currentFile,
filesDragOver = function(e) {
if (e.preventDefault) e.preventDefault();
$('#files').addClass('drag');
return false;
},
filesDragEnter = function(e) {
if (e.preventDefault) e.preventDefault();
return false;
},
filesDragLeave = function(e) {
if (e.preventDefault) e.preventDefault();
$('#files').removeClass('drag');
return false;
},
filesDrop = function(e) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
$('#files').removeClass('drag');
if (!$('#folders span.current').first().parent().data('writable')) {
browser.alert("Cannot write to upload folder.");
return false;
}
filesCount += e.dataTransfer.files.length
for (var i = 0; i < e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
file.thisTargetDir = browser.dir;
uploadQueue.push(file);
}
processUploadQueue();
return false;
},
folderDrag = function(e) {
if (e.preventDefault) e.preventDefault();
return false;
},
folderDrop = function(e, dir) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
if (!$(dir).data('writable')) {
browser.alert("Cannot write to upload folder.");
return false;
}
filesCount += e.dataTransfer.files.length
for (var i = 0; i < e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
file.thisTargetDir = $(dir).data('path');
uploadQueue.push(file);
}
processUploadQueue();
return false;
};
files.get(0).removeEventListener('dragover', filesDragOver, false);
files.get(0).removeEventListener('dragenter', filesDragEnter, false);
files.get(0).removeEventListener('dragleave', filesDragLeave, false);
files.get(0).removeEventListener('drop', filesDrop, false);
files.get(0).addEventListener('dragover', filesDragOver, false);
files.get(0).addEventListener('dragenter', filesDragEnter, false);
files.get(0).addEventListener('dragleave', filesDragLeave, false);
files.get(0).addEventListener('drop', filesDrop, false);
folders.each(function() {
var folder = this,
dragOver = function(e) {
$(folder).children('span.folder').addClass('context');
return folderDrag(e);
},
dragLeave = function(e) {
$(folder).children('span.folder').removeClass('context');
return folderDrag(e);
},
drop = function(e) {
$(folder).children('span.folder').removeClass('context');
return folderDrop(e, folder);
};
this.removeEventListener('dragover', dragOver, false);
this.removeEventListener('dragenter', folderDrag, false);
this.removeEventListener('dragleave', dragLeave, false);
this.removeEventListener('drop', drop, false);
this.addEventListener('dragover', dragOver, false);
this.addEventListener('dragenter', folderDrag, false);
this.addEventListener('dragleave', dragLeave, false);
this.addEventListener('drop', drop, false);
});
function updateProgress(evt) {
var progress = evt.lengthComputable
? Math.round((evt.loaded * 100) / evt.total) + '%'
: Math.round(evt.loaded / 1024) + " KB";
$('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", {
number: filesCount - uploadQueue.length,
count: filesCount,
progress: progress
}));
}
function processUploadQueue() {
if (uploadInProgress)
return false;
if (uploadQueue && uploadQueue.length) {
var file = uploadQueue.shift();
currentFile = file;
$('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", {
number: filesCount - uploadQueue.length,
count: filesCount,
progress: ""
}));
$('#loading').css('display', 'inline');
var reader = new FileReader();
reader.thisFileName = file.name;
reader.thisFileType = file.type;
reader.thisFileSize = file.size;
reader.thisTargetDir = file.thisTargetDir;
reader.onload = function(evt) {
uploadInProgress = true;
var postbody = '--' + boundary + '\r\nContent-Disposition: form-data; name="upload[]"';
if (evt.target.thisFileName)
postbody += '; filename="' + _.utf8encode(evt.target.thisFileName) + '"';
postbody += '\r\n';
if (evt.target.thisFileSize)
postbody += 'Content-Length: ' + evt.target.thisFileSize + '\r\n';
postbody += 'Content-Type: ' + evt.target.thisFileType + '\r\n\r\n' + evt.target.result + '\r\n--' + boundary + '\r\nContent-Disposition: form-data; name="dir"\r\n\r\n' + _.utf8encode(evt.target.thisTargetDir) + '\r\n--' + boundary + '\r\n--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.thisFileName = evt.target.thisFileName;
if (xhr.upload) {
xhr.upload.thisFileName = evt.target.thisFileName;
xhr.upload.addEventListener("progress", updateProgress, false);
}
xhr.open('POST', browser.baseGetData('upload'), true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Content-Length', postbody.length);
xhr.onload = function(e) {
$('#loading').css('display', 'none');
if (browser.dir == reader.thisTargetDir)
browser.fadeFiles();
uploadInProgress = false;
processUploadQueue();
if (xhr.responseText.substr(0, 1) != '/')
errors[errors.length] = xhr.responseText;
}
xhr.sendAsBinary(postbody);
};
reader.onerror = function(evt) {
$('#loading').css('display', 'none');
uploadInProgress = false;
processUploadQueue();
errors[errors.length] = browser.label("Failed to upload {filename}!", {
filename: evt.target.thisFileName
});
};
reader.readAsBinaryString(file);
} else {
filesCount = 0;
var loop = setInterval(function() {
if (uploadInProgress) return;
clearInterval(loop);
if (currentFile.thisTargetDir == browser.dir)
browser.refresh();
boundary = '------multipartdropuploadboundary' + (new Date).getTime();
if (errors.length) {
browser.alert(errors.join('\n'));
errors = [];
}
}, 333);
}
}
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Folder related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFolders = function() {
$('#folders').scroll(function() {
browser.hideDialog();
});
$('div.folder > a').unbind();
$('div.folder > a').bind('click', function() {
browser.hideDialog();
return false;
});
$('div.folder > a > span.brace').unbind();
$('div.folder > a > span.brace').click(function() {
if ($(this).hasClass('opened') || $(this).hasClass('closed'))
browser.expandDir($(this).parent());
});
$('div.folder > a > span.folder').unbind();
$('div.folder > a > span.folder').click(function() {
browser.changeDir($(this).parent());
});
$('div.folder > a > span.folder').rightClick(function(e) {
_.unselect();
browser.menuDir($(this).parent(), e);
});
if ($.browser.msie && $.browser.version &&
(parseInt($.browser.version.substr(0, 1)) < 8)
) {
var fls = $('div.folder').get();
var body = $('body').get(0);
var div;
$.each(fls, function(i, folder) {
div = document.createElement('div');
div.style.display = 'inline';
div.style.margin = div.style.border = div.style.padding = '0';
div.innerHTML='<table style="border-collapse:collapse;border:0;margin:0;width:0"><tr><td nowrap="nowrap" style="white-space:nowrap;padding:0;border:0">' + $(folder).html() + "</td></tr></table>";
body.appendChild(div);
$(folder).css('width', $(div).innerWidth() + 'px');
body.removeChild(div);
});
}
};
browser.setTreeData = function(data, path) {
if (!path)
path = '';
else if (path.length && (path.substr(path.length - 1, 1) != '/'))
path += '/';
path += data.name;
var selector = '#folders a[href="kcdir:/' + _.escapeDirs(path) + '"]';
$(selector).data({
name: data.name,
path: path,
readable: data.readable,
writable: data.writable,
removable: data.removable,
hasDirs: data.hasDirs
});
$(selector + ' span.folder').addClass(data.current ? 'current' : 'regular');
if (data.dirs && data.dirs.length) {
$(selector + ' span.brace').addClass('opened');
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path + '/');
});
} else if (data.hasDirs)
$(selector + ' span.brace').addClass('closed');
};
browser.buildTree = function(root, path) {
if (!path) path = "";
path += root.name;
var html = '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(root.name) + '</span></a>';
if (root.dirs) {
html += '<div class="folders">';
for (var i = 0; i < root.dirs.length; i++) {
cdir = root.dirs[i];
html += browser.buildTree(cdir, path + '/');
}
html += '</div>';
}
html += '</div>';
return html;
};
browser.expandDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened')) {
dir.parent().children('.folders').hide(500, function() {
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
});
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
} else {
if (dir.parent().children('.folders').get(0)) {
dir.parent().children('.folders').show(500);
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else if (!$('#loadingDirs').get(0)) {
dir.parent().append('<div id="loadingDirs">' + this.label("Loading folders...") + '</div>');
$('#loadingDirs').css('display', 'none');
$('#loadingDirs').show(200, function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('expand'),
data: {dir:path},
async: false,
success: function(data) {
$('#loadingDirs').hide(200, function() {
$('#loadingDirs').detach();
});
if (browser.check4errors(data))
return;
var html = '';
$.each(data.dirs, function(i, cdir) {
html += '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path + '/' + cdir.name) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(cdir.name) + '</span></a></div>';
});
if (html.length) {
dir.parent().append('<div class="folders">' + html + '</div>');
var folders = $(dir.parent().children('.folders').first());
folders.css('display', 'none');
$(folders).show(500);
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path);
});
}
if (data.dirs.length) {
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else {
dir.children('.brace').removeClass('opened');
dir.children('.brace').removeClass('closed');
}
browser.initFolders();
browser.initDropUpload();
},
error: function() {
$('#loadingDirs').detach();
browser.alert(browser.label("Unknown error."));
}
});
});
}
}
};
browser.changeDir = function(dir) {
if (dir.children('span.folder').hasClass('regular')) {
$('div.folder > a > span.folder').removeClass('current');
$('div.folder > a > span.folder').removeClass('regular');
$('div.folder > a > span.folder').addClass('regular');
dir.children('span.folder').removeClass('regular');
dir.children('span.folder').addClass('current');
$('#files').html(browser.label("Loading files..."));
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:dir.data('path')},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.files = data.files;
browser.orderFiles();
browser.dir = dir.data('path');
browser.dirWritable = data.dirWritable;
var title = "KCFinder: /" + browser.dir;
document.title = title;
if (browser.opener.TinyMCE)
tinyMCEPopup.editor.windowManager.setTitle(window, title);
browser.statusDir();
},
error: function() {
$('#files').html(browser.label("Unknown error."));
}
});
}
};
browser.statusDir = function() {
for (var i = 0, size = 0; i < this.files.length; i++)
size += parseInt(this.files[i].size);
size = this.humanSize(size);
$('#fileinfo').html(this.files.length + ' ' + this.label("files") + ' (' + size + ')');
};
browser.menuDir = function(dir, e) {
var data = dir.data();
var html = '<div class="menu">';
if (this.clipboard && this.clipboard.length) {
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Copy {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Move {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>';
}
html +=
'<a href="kcact:refresh">' + this.label("Refresh") + '</a>';
if (this.support.zip) html+=
'<div class="delimiter"></div>' +
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.dirs.create || this.access.dirs.rename || this.access.dirs['delete'])
html += '<div class="delimiter"></div>';
if (this.access.dirs.create)
html += '<a href="kcact:mkdir"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("New Subfolder...") + '</a>';
if (this.access.dirs.rename)
html += '<a href="kcact:mvdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.dirs['delete'])
html += '<a href="kcact:rmdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('div.folder > a > span.folder').removeClass('context');
if (dir.children('span.folder').hasClass('regular'))
dir.children('span.folder').addClass('context');
if (this.clipboard && this.clipboard.length && data.writable) {
$('.menu a[href="kcact:cpcbd"]').click(function() {
browser.hideDialog();
browser.copyClipboard(data.path);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
browser.hideDialog();
browser.moveClipboard(data.path);
return false;
});
}
$('.menu a[href="kcact:refresh"]').click(function() {
browser.hideDialog();
browser.refreshDir(dir);
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.post(browser.baseGetData('downloadDir'), {dir:data.path});
return false;
});
$('.menu a[href="kcact:mkdir"]').click(function(e) {
if (!data.writable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newDir', '', browser.baseGetData('newDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function() {
browser.refreshDir(dir);
browser.initDropUpload();
if (!data.hasDirs) {
dir.data('hasDirs', true);
dir.children('span.brace').addClass('closed');
}
}
);
return false;
});
$('.menu a[href="kcact:mvdir"]').click(function(e) {
if (!data.removable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newName', data.name, browser.baseGetData('renameDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function(dt) {
if (!dt.name) {
browser.alert(browser.label("Unknown error."));
return;
}
var currentDir = (data.path == browser.dir);
dir.children('span.folder').html(_.htmlData(dt.name));
dir.data('name', dt.name);
dir.data('path', _.dirname(data.path) + '/' + dt.name);
if (currentDir)
browser.dir = dir.data('path');
browser.initDropUpload();
},
true
);
return false;
});
$('.menu a[href="kcact:rmdir"]').click(function() {
if (!data.removable) return false;
browser.hideDialog();
browser.confirm(
"Are you sure you want to delete this folder and all its content?",
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('deleteDir'),
data: {dir: data.path},
async: false,
success: function(data) {
if (callBack) callBack();
if (browser.check4errors(data))
return;
dir.parent().hide(500, function() {
var folders = dir.parent().parent();
var pDir = folders.parent().children('a').first();
dir.parent().detach();
if (!folders.children('div.folder').get(0)) {
pDir.children('span.brace').first().removeClass('opened');
pDir.children('span.brace').first().removeClass('closed');
pDir.parent().children('.folders').detach();
pDir.data('hasDirs', false);
}
if (pDir.data('path') == browser.dir.substr(0, pDir.data('path').length))
browser.changeDir(pDir);
browser.initDropUpload();
});
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
};
browser.refreshDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened') || dir.children('.brace').hasClass('closed')) {
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
}
dir.parent().children('.folders').first().detach();
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
browser.expandDir(dir);
return true;
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc File related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFiles = function() {
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
$('#files').unbind();
$('#files').scroll(function() {
browser.hideDialog();
});
$('.file').unbind();
$('.file').click(function(e) {
_.unselect();
browser.selectFile($(this), e);
});
$('.file').rightClick(function(e) {
_.unselect();
browser.menuFile($(this), e);
});
$('.file').dblclick(function() {
_.unselect();
browser.returnFile($(this));
});
$('.file').mouseup(function() {
_.unselect();
});
$('.file').mouseout(function() {
_.unselect();
});
$.each(this.shows, function(i, val) {
var display = (_.kuki.get('show' + val) == 'off')
? 'none' : 'block';
$('#files .file div.' + val).css('display', display);
});
this.statusDir();
};
browser.showFiles = function(callBack, selected) {
this.fadeFiles();
setTimeout(function() {
var html = '';
$.each(browser.files, function(i, file) {
var stamp = [];
$.each(file, function(key, val) {
stamp[stamp.length] = key + "|" + val;
});
stamp = _.md5(stamp.join('|'));
if (_.kuki.get('view') == 'list') {
if (!i) html += '<table summary="list">';
var icon = _.getFileExtension(file.name);
if (file.thumb)
icon = '.image';
else if (!icon.length || !file.smallIcon)
icon = '.';
icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<tr class="file">' +
'<td class="name" style="background-image:url(' + icon + ')">' + _.htmlData(file.name) + '</td>' +
'<td class="time">' + file.date + '</td>' +
'<td class="size">' + browser.humanSize(file.size) + '</td>' +
'</tr>';
if (i == browser.files.length - 1) html += '</table>';
} else {
if (file.thumb)
var icon = browser.baseGetData('thumb') + '&file=' + encodeURIComponent(file.name) + '&dir=' + encodeURIComponent(browser.dir) + '&stamp=' + stamp;
else if (file.smallThumb) {
var icon = browser.uploadURL + '/' + browser.dir + '/' + file.name;
icon = _.escapeDirs(icon).replace(/\'/g, "%27");
} else {
var icon = file.bigIcon ? _.getFileExtension(file.name) : '.';
if (!icon.length) icon = '.';
icon = 'themes/' + browser.theme + '/img/files/big/' + icon + '.png';
}
html += '<div class="file">' +
'<div class="thumb" style="background-image:url(\'' + icon + '\')" ></div>' +
'<div class="name">' + _.htmlData(file.name) + '</div>' +
'<div class="time">' + file.date + '</div>' +
'<div class="size">' + browser.humanSize(file.size) + '</div>' +
'</div>';
}
});
$('#files').html('<div>' + html + '<div>');
$.each(browser.files, function(i, file) {
var item = $('#files .file').get(i);
$(item).data(file);
if (_.inArray(file.name, selected) ||
((typeof selected != 'undefined') && !selected.push && (file.name == selected))
)
$(item).addClass('selected');
});
$('#files > div').css({opacity:'', filter:''});
if (callBack) callBack();
browser.initFiles();
}, 200);
};
browser.selectFile = function(file, e) {
if (e.ctrlKey || e.metaKey) {
if (file.hasClass('selected'))
file.removeClass('selected');
else
file.addClass('selected');
var files = $('.file.selected').get();
var size = 0;
if (!files.length)
this.statusDir();
else {
$.each(files, function(i, cfile) {
size += parseInt($(cfile).data('size'));
});
size = this.humanSize(size);
if (files.length > 1)
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
else {
var data = $(files[0]).data();
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
}
} else {
var data = file.data();
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
};
browser.selectAll = function(e) {
if ((!e.ctrlKey && !e.metaKey) || ((e.keyCode != 65) && (e.keyCode != 97)))
return false;
var files = $('.file').get();
if (files.length) {
var size = 0;
$.each(files, function(i, file) {
if (!$(file).hasClass('selected'))
$(file).addClass('selected');
size += parseInt($(file).data('size'));
});
size = this.humanSize(size);
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
}
return true;
};
browser.returnFile = function(file) {
var fileURL = file.substr
? file : browser.uploadURL + '/' + browser.dir + '/' + file.data('name');
fileURL = _.escapeDirs(fileURL);
if (this.opener.CKEditor) {
this.opener.CKEditor.object.tools.callFunction(this.opener.CKEditor.funcNum, fileURL, '');
window.close();
} else if (this.opener.FCKeditor) {
window.opener.SetUrl(fileURL) ;
window.close() ;
} else if (this.opener.TinyMCE) {
var win = tinyMCEPopup.getWindowArg('window');
win.document.getElementById(tinyMCEPopup.getWindowArg('input')).value = fileURL;
if (win.getImageData) win.getImageData();
if (typeof(win.ImageDialog) != "undefined") {
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(fileURL);
}
tinyMCEPopup.close();
} else if (this.opener.callBack) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBack(fileURL);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBack(fileURL);
}
} else if (this.opener.callBackMultiple) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBackMultiple([fileURL]);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBackMultiple([fileURL]);
}
}
};
browser.returnFiles = function(files) {
if (this.opener.callBackMultiple && files.length) {
var rfiles = [];
$.each(files, function(i, file) {
rfiles[i] = browser.uploadURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[i] = _.escapeDirs(rfiles[i]);
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.returnThumbnails = function(files) {
if (this.opener.callBackMultiple) {
var rfiles = [];
var j = 0;
$.each(files, function(i, file) {
if ($(file).data('thumb')) {
rfiles[j] = browser.thumbsURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[j] = _.escapeDirs(rfiles[j++]);
}
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.menuFile = function(file, e) {
var data = file.data();
var path = this.dir + '/' + data.name;
var files = $('.file.selected').get();
var html = '';
if (file.hasClass('selected') && files.length && (files.length > 1)) {
var thumb = false;
var notWritable = 0;
var cdata;
$.each(files, function(i, cfile) {
cdata = $(cfile).data();
if (cdata.thumb) thumb = true;
if (!data.writable) notWritable++;
});
if (this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnails") + '</a>';
}
if (data.thumb || data.smallThumb || this.support.zip) {
html += (html.length ? '<div class="delimiter"></div>' : '');
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
if (this.support.zip) html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:download">' + this.label("Download") + '</a>';
}
if (this.access.files.copy || this.access.files.move)
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files['delete'])
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:rm"' + ((notWritable == files.length) ? ' class="denied"' : '') +
'>' + this.label("Delete") + '</a>';
if (html.length) {
html = '<div class="menu">' + html + '</div>';
$('#dialog').html(html);
this.showMenu(e);
} else
return;
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFiles(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
browser.returnThumbnails(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
var pfiles = [];
$.each(files, function(i, cfile) {
pfiles[i] = $(cfile).data('name');
});
browser.post(browser.baseGetData('downloadSelected'), {dir:browser.dir, files:pfiles});
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
browser.hideDialog();
var msg = '';
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
var failed = false;
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == cdata.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
failed = true
msg += cdata.name + ": " + browser.label("This file is already added to the Clipboard.") + "\n";
break;
}
if (!failed) {
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
}
});
browser.initClipboard();
if (msg.length) browser.alert(msg.substr(0, msg.length - 1));
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if ($(this).hasClass('denied')) return false;
browser.hideDialog();
var failed = 0;
var dfiles = [];
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
if (!cdata.writable)
failed++;
else
dfiles[dfiles.length] = browser.dir + "/" + cdata.name;
});
if (failed == files.length) {
browser.alert(browser.label("The selected files are not removable."));
return false;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:dfiles},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} selected files are not removable. Do you want to delete the rest?", {count:failed}),
go
)
else
browser.confirm(
browser.label("Are you sure you want to delete all selected files?"),
go
);
return false;
});
} else {
html += '<div class="menu">';
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
if (this.opener.callBack || this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (data.thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnail") + '</a>';
html += '<div class="delimiter"></div>';
}
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
html +=
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>' +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files.rename || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.rename)
html += '<a href="kcact:mv"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rm"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFile(file);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
var path = browser.thumbsURL + '/' + browser.dir + '/' + data.name;
browser.returnFile(path);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
var html = '<form id="downloadForm" method="post" action="' + browser.baseGetData('download') + '">' +
'<input type="hidden" name="dir" />' +
'<input type="hidden" name="file" />' +
'</form>';
$('#dialog').html(html);
$('#downloadForm input').get(0).value = browser.dir;
$('#downloadForm input').get(1).value = data.name;
$('#downloadForm').submit();
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == data.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
browser.hideDialog();
browser.alert(browser.label("This file is already added to the Clipboard."));
return false;
}
var cdata = data;
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
browser.initClipboard();
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:mv"]').click(function(e) {
if (!data.writable) return false;
browser.fileNameDialog(
e, {dir: browser.dir, file: data.name},
'newName', data.name, browser.baseGetData('rename'), {
title: "New file name:",
errEmpty: "Please enter new file name.",
errSlash: "Unallowable characters in file name.",
errDot: "File name shouldn't begins with '.'"
},
function() {
browser.refresh();
}
);
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if (!data.writable) return false;
browser.hideDialog();
browser.confirm(browser.label("Are you sure you want to delete this file?"),
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('delete'),
data: {dir:browser.dir, file:data.name},
async: false,
success: function(data) {
if (callBack) callBack();
browser.clearClipboard();
if (browser.check4errors(data))
return;
browser.refresh();
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
}
$('.menu a[href="kcact:view"]').click(function() {
browser.hideDialog();
var ts = new Date().getTime();
var showImage = function(data) {
url = _.escapeDirs(browser.uploadURL + '/' + browser.dir + '/' + data.name) + '?ts=' + ts,
$('#loading').html(browser.label("Loading image..."));
$('#loading').css('display', 'inline');
var img = new Image();
img.src = url;
img.onerror = function() {
browser.lock = false;
$('#loading').css('display', 'none');
browser.alert(browser.label("Unknown error."));
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
browser.refresh();
};
var onImgLoad = function() {
browser.lock = false;
$('#files .file').each(function() {
if ($(this).data('name') == data.name)
browser.ssImage = this;
});
$('#loading').css('display', 'none');
$('#dialog').html('<div class="slideshow"><img /></div>');
$('#dialog img').attr({
src: url,
title: data.name
}).fadeIn('fast', function() {
var o_w = $('#dialog').outerWidth();
var o_h = $('#dialog').outerHeight();
var f_w = $(window).width() - 30;
var f_h = $(window).height() - 30;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
$('#dialog img').attr({
width: f_w,
height: f_h
});
}
$('#dialog').unbind('click');
$('#dialog').click(function(e) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
if (browser.ssImage) {
browser.selectFile($(browser.ssImage), e);
}
});
browser.showDialog();
var images = [];
$.each(browser.files, function(i, file) {
if (file.thumb || file.smallThumb)
images[images.length] = file;
});
if (images.length)
$.each(images, function(i, image) {
if (image.name == data.name) {
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (images.length > 1) {
if (!browser.lock && (e.keyCode == 37)) {
var nimg = i
? images[i - 1]
: images[images.length - 1];
browser.lock = true;
showImage(nimg);
}
if (!browser.lock && (e.keyCode == 39)) {
var nimg = (i >= images.length - 1)
? images[0]
: images[i + 1];
browser.lock = true;
showImage(nimg);
}
}
if (e.keyCode == 27) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
}
});
}
});
});
};
if (img.complete)
onImgLoad();
else
img.onload = onImgLoad;
};
showImage(data);
return false;
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Base JavaScript object properties
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
var browser = {
opener: {},
support: {},
files: [],
clipboard: [],
labels: [],
shows: [],
orders: [],
cms: ""
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Clipboard functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var size = 0;
$.each(this.clipboard, function(i, val) {
size += parseInt(val.size);
});
size = this.humanSize(size);
$('#clipboard').html('<div title="' + this.label("Clipboard") + ' (' + this.clipboard.length + ' ' + this.label("files") + ', ' + size + ')" onclick="browser.openClipboard()"></div>');
var resize = function() {
$('#clipboard').css({
left: $(window).width() - $('#clipboard').outerWidth() + 'px',
top: $(window).height() - $('#clipboard').outerHeight() + 'px'
});
};
resize();
$('#clipboard').css('display', 'block');
$(window).unbind();
$(window).resize(function() {
browser.resize();
resize();
});
};
browser.openClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
if ($('.menu a[href="kcact:cpcbd"]').html()) {
$('#clipboard').removeClass('selected');
this.hideDialog();
return;
}
var html = '<div class="menu"><div class="list">';
$.each(this.clipboard, function(i, val) {
icon = _.getFileExtension(val.name);
if (val.thumb)
icon = '.image';
else if (!val.smallIcon || !icon.length)
icon = '.';
var icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<a style="background-image:url(' + _.escapeDirs(icon) + ')" title="' + browser.label("Click to remove from the Clipboard") + '" onclick="browser.removeFromClipboard(' + i + ')">' + _.htmlData(_.basename(val.name)) + '</a>';
});
html += '</div><div class="delimiter"></div>';
if (this.support.zip) html+=
'<a href="kcact:download">' + this.label("Download files") + '</a>';
if (this.access.files.copy || this.access.files.move || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Copy files here") + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Move files here") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rmcbd">' + this.label("Delete files") + '</a>';
html += '<div class="delimiter"></div>' +
'<a href="kcact:clrcbd">' + this.label("Clear the Clipboard") + '</a>' + '</div>';
setTimeout(function() {
$('#clipboard').addClass('selected');
$('#dialog').html(html);
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.downloadClipboard();
return false;
});
$('.menu a[href="kcact:cpcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.copyClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.moveClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:rmcbd"]').click(function() {
browser.hideDialog();
browser.confirm(
browser.label("Are you sure you want to delete all files in the Clipboard?"),
function(callBack) {
if (callBack) callBack();
browser.deleteClipboard();
}
);
return false;
});
$('.menu a[href="kcact:clrcbd"]').click(function() {
browser.hideDialog();
browser.clearClipboard();
return false;
});
var left = $(window).width() - $('#dialog').outerWidth();
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
var lheight = top + _.outerTopSpace('#dialog');
$('.menu .list').css('max-height', lheight + 'px');
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
$('#dialog').css({
left: (left - 4) + 'px',
top: top + 'px'
});
$('#dialog').fadeIn();
}, 1);
};
browser.removeFromClipboard = function(i) {
if (!this.clipboard || !this.clipboard[i]) return false;
if (this.clipboard.length == 1) {
this.clearClipboard();
this.hideDialog();
return;
}
if (i < this.clipboard.length - 1) {
var last = this.clipboard.slice(i + 1);
this.clipboard = this.clipboard.slice(0, i);
this.clipboard = this.clipboard.concat(last);
} else
this.clipboard.pop();
this.initClipboard();
this.hideDialog();
this.openClipboard();
return true;
};
browser.copyClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not readable."));
return;
}
var go = function(callBack) {
if (dir == browser.dir)
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('cp_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
if (dir == browser.dir)
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?", {count:failed}),
go
)
else
go();
};
browser.moveClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + "/" + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not movable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('mv_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not movable. Do you want to move the rest?", {count: failed}),
go
);
else
go();
};
browser.deleteClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not removable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter:''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?", {count: failed}),
go
);
else
go();
};
browser.downloadClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
if (files.length)
this.post(this.baseGetData('downloadClipboard'), {files:files});
};
browser.clearClipboard = function() {
$('#clipboard').html('');
this.clipboard = [];
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Miscellaneous functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.drag = function(ev, dd) {
var top = dd.offsetY,
left = dd.offsetX;
if (top < 0) top = 0;
if (left < 0) left = 0;
if (top + $(this).outerHeight() > $(window).height())
top = $(window).height() - $(this).outerHeight();
if (left + $(this).outerWidth() > $(window).width())
left = $(window).width() - $(this).outerWidth();
$(this).css({
top: top,
left: left
});
};
browser.showDialog = function(e) {
$('#dialog').css({left: 0, top: 0});
this.shadow();
if ($('#dialog div.box') && !$('#dialog div.title').get(0)) {
var html = $('#dialog div.box').html();
var title = $('#dialog').data('title') ? $('#dialog').data('title') : "";
html = '<div class="title"><span class="close"></span>' + title + '</div>' + html;
$('#dialog div.box').html(html);
$('#dialog div.title span.close').mousedown(function() {
$(this).addClass('clicked');
});
$('#dialog div.title span.close').mouseup(function() {
$(this).removeClass('clicked');
});
$('#dialog div.title span.close').click(function() {
browser.hideDialog();
browser.hideAlert();
});
}
$('#dialog').drag(browser.drag, {handle: '#dialog div.title'});
$('#dialog').css('display', 'block');
if (e) {
var left = e.pageX - parseInt($('#dialog').outerWidth() / 2);
var top = e.pageY - parseInt($('#dialog').outerHeight() / 2);
if (left < 0) left = 0;
if (top < 0) top = 0;
if (($('#dialog').outerWidth() + left) > $(window).width())
left = $(window).width() - $('#dialog').outerWidth();
if (($('#dialog').outerHeight() + top) > $(window).height())
top = $(window).height() - $('#dialog').outerHeight();
$('#dialog').css({
left: left + 'px',
top: top + 'px'
});
} else
$('#dialog').css({
left: parseInt(($(window).width() - $('#dialog').outerWidth()) / 2) + 'px',
top: parseInt(($(window).height() - $('#dialog').outerHeight()) / 2) + 'px'
});
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (e.keyCode == 27)
browser.hideDialog();
});
};
browser.hideDialog = function() {
this.unshadow();
if ($('#clipboard').hasClass('selected'))
$('#clipboard').removeClass('selected');
$('#dialog').css('display', 'none');
$('div.folder > a > span.folder').removeClass('context');
$('#dialog').html('');
$('#dialog').data('title', null);
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
browser.hideAlert();
};
browser.showAlert = function(shadow) {
$('#alert').css({left: 0, top: 0});
if (typeof shadow == 'undefined')
shadow = true;
if (shadow)
this.shadow();
var left = parseInt(($(window).width() - $('#alert').outerWidth()) / 2),
top = parseInt(($(window).height() - $('#alert').outerHeight()) / 2);
var wheight = $(window).height();
if (top < 0)
top = 0;
$('#alert').css({
left: left + 'px',
top: top + 'px',
display: 'block'
});
if ($('#alert').outerHeight() > wheight) {
$('#alert div.message').css({
height: wheight - $('#alert div.title').outerHeight() - $('#alert div.ok').outerHeight() - 20 + 'px'
});
}
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (e.keyCode == 27) {
browser.hideDialog();
browser.hideAlert();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
}
});
};
browser.hideAlert = function(shadow) {
if (typeof shadow == 'undefined')
shadow = true;
if (shadow)
this.unshadow();
$('#alert').css('display', 'none');
$('#alert').html('');
$('#alert').data('title', null);
};
browser.alert = function(msg, shadow) {
msg = msg.replace(/\r?\n/g, "<br />");
var title = $('#alert').data('title') ? $('#alert').data('title') : browser.label("Attention");
$('#alert').html('<div class="title"><span class="close"></span>' + title + '</div><div class="message">' + msg + '</div><div class="ok"><button>' + browser.label("OK") + '</button></div>');
$('#alert div.ok button').click(function() {
browser.hideAlert(shadow);
});
$('#alert div.title span.close').mousedown(function() {
$(this).addClass('clicked');
});
$('#alert div.title span.close').mouseup(function() {
$(this).removeClass('clicked');
});
$('#alert div.title span.close').click(function() {
browser.hideAlert(shadow);
});
$('#alert').drag(browser.drag, {handle: "#alert div.title"});
browser.showAlert(shadow);
};
browser.confirm = function(question, callBack) {
$('#dialog').data('title', browser.label("Question"));
$('#dialog').html('<div class="box"><div class="question">' + browser.label(question) + '<div class="buttons"><button>' + browser.label("No") + '</button> <button>' + browser.label("Yes") + '</button></div></div></div>');
browser.showDialog();
$('#dialog div.buttons button').first().click(function() {
browser.hideDialog();
});
$('#dialog div.buttons button').last().click(function() {
if (callBack)
callBack(function() {
browser.hideDialog();
});
else
browser.hideDialog();
});
$('#dialog div.buttons button').get(1).focus();
};
browser.shadow = function() {
$('#shadow').css('display', 'block');
};
browser.unshadow = function() {
$('#shadow').css('display', 'none');
};
browser.showMenu = function(e) {
var left = e.pageX;
var top = e.pageY;
if (($('#dialog').outerWidth() + left) > $(window).width())
left = $(window).width() - $('#dialog').outerWidth();
if (($('#dialog').outerHeight() + top) > $(window).height())
top = $(window).height() - $('#dialog').outerHeight();
$('#dialog').css({
left: left + 'px',
top: top + 'px',
display: 'none'
});
$('#dialog').fadeIn();
};
browser.fileNameDialog = function(e, post, inputName, inputValue, url, labels, callBack, selectAll) {
var html = '<form method="post" action="javascript:;">' +
'<div class="box">' +
'<input name="' + inputName + '" type="text" /><br />' +
'<div style="text-align:right">' +
'<input type="submit" value="' + _.htmlValue(this.label("OK")) + '" /> ' +
'<input type="button" value="' + _.htmlValue(this.label("Cancel")) + '" onclick="browser.hideDialog(); browser.hideAlert(); return false" />' +
'</div></div></form>';
$('#dialog').html(html);
$('#dialog').data('title', this.label(labels.title));
$('#dialog input[name="' + inputName + '"]').attr('value', inputValue);
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$('#dialog form').submit(function() {
var name = this.elements[0];
name.value = $.trim(name.value);
if (name.value == '') {
browser.alert(browser.label(labels.errEmpty), false);
name.focus();
return;
} else if (/[\/\\]/g.test(name.value)) {
browser.alert(browser.label(labels.errSlash), false);
name.focus();
return;
} else if (name.value.substr(0, 1) == ".") {
browser.alert(browser.label(labels.errDot), false);
name.focus();
return;
}
eval('post.' + inputName + ' = name.value;');
$.ajax({
type: 'POST',
dataType: 'json',
url: url,
data: post,
async: false,
success: function(data) {
if (browser.check4errors(data, false))
return;
if (callBack) callBack(data);
browser.hideDialog();
},
error: function() {
browser.alert(browser.label("Unknown error."), false);
}
});
return false;
});
browser.showDialog(e);
$('#dialog').css('display', 'block');
$('#dialog input[type="submit"]').click(function() {
return $('#dialog form').submit();
});
var field = $('#dialog input[type="text"]');
var value = field.attr('value');
if (!selectAll && /^(.+)\.[^\.]+$/ .test(value)) {
value = value.replace(/^(.+)\.[^\.]+$/, "$1");
_.selection(field.get(0), 0, value.length);
} else {
field.get(0).focus();
field.get(0).select();
}
};
browser.orderFiles = function(callBack, selected) {
var order = _.kuki.get('order');
var desc = (_.kuki.get('orderDesc') == 'on');
if (!browser.files || !browser.files.sort)
browser.files = [];
browser.files = browser.files.sort(function(a, b) {
var a1, b1, arr;
if (!order) order = 'name';
if (order == 'date') {
a1 = a.mtime;
b1 = b.mtime;
} else if (order == 'type') {
a1 = _.getFileExtension(a.name);
b1 = _.getFileExtension(b.name);
} else if (order == 'size') {
a1 = a.size;
b1 = b.size;
} else
eval('a1 = a.' + order + '.toLowerCase(); b1 = b.' + order + '.toLowerCase();');
if ((order == 'size') || (order == 'date')) {
if (a1 < b1) return desc ? 1 : -1;
if (a1 > b1) return desc ? -1 : 1;
}
if (a1 == b1) {
a1 = a.name.toLowerCase();
b1 = b.name.toLowerCase();
arr = [a1, b1];
arr = arr.sort();
return (arr[0] == a1) ? -1 : 1;
}
arr = [a1, b1];
arr = arr.sort();
if (arr[0] == a1) return desc ? 1 : -1;
return desc ? -1 : 1;
});
browser.showFiles(callBack, selected);
browser.initFiles();
};
browser.humanSize = function(size) {
if (size < 1024) {
size = size.toString() + ' B';
} else if (size < 1048576) {
size /= 1024;
size = parseInt(size).toString() + ' KB';
} else if (size < 1073741824) {
size /= 1048576;
size = parseInt(size).toString() + ' MB';
} else if (size < 1099511627776) {
size /= 1073741824;
size = parseInt(size).toString() + ' GB';
} else {
size /= 1099511627776;
size = parseInt(size).toString() + ' TB';
}
return size;
};
browser.baseGetData = function(act) {
var data = 'browse.php?type=' + encodeURIComponent(this.type) + '&lng=' + this.lang;
if (act)
data += "&act=" + act;
if (this.cms)
data += "&cms=" + this.cms;
return data;
};
browser.label = function(index, data) {
var label = this.labels[index] ? this.labels[index] : index;
if (data)
$.each(data, function(key, val) {
label = label.replace('{' + key + '}', val);
});
return label;
};
browser.check4errors = function(data, shadow) {
if (!data.error)
return false;
var msg;
if (data.error.join)
msg = data.error.join("\n");
else
msg = data.error;
browser.alert(msg, shadow);
return true;
};
browser.post = function(url, data) {
var html = '<form id="postForm" method="POST" action="' + url + '">';
$.each(data, function(key, val) {
if ($.isArray(val))
$.each(val, function(i, aval) {
html += '<input type="hidden" name="' + _.htmlValue(key) + '[]" value="' + _.htmlValue(aval) + '" />';
});
else
html += '<input type="hidden" name="' + _.htmlValue(key) + '" value="' + _.htmlValue(val) + '" />';
});
html += '</form>';
$('#dialog').html(html);
$('#dialog').css('display', 'block');
$('#postForm').get(0).submit();
};
browser.fadeFiles = function() {
$('#files > div').css({
opacity: '0.4',
filter: 'alpha(opacity:40)'
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Settings panel functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initSettings = function() {
if (!this.shows.length) {
var showInputs = $('#show input[type="checkbox"]').toArray();
$.each(showInputs, function (i, input) {
browser.shows[i] = input.name;
});
}
var shows = this.shows;
if (!_.kuki.isSet('showname')) {
_.kuki.set('showname', 'on');
$.each(shows, function (i, val) {
if (val != "name") _.kuki.set('show' + val, 'off');
});
}
$('#show input[type="checkbox"]').click(function() {
var kuki = $(this).get(0).checked ? 'on' : 'off';
_.kuki.set('show' + $(this).get(0).name, kuki)
if ($(this).get(0).checked)
$('#files .file div.' + $(this).get(0).name).css('display', 'block');
else
$('#files .file div.' + $(this).get(0).name).css('display', 'none');
});
$.each(shows, function(i, val) {
var checked = (_.kuki.get('show' + val) == 'on') ? 'checked' : '';
$('#show input[name="' + val + '"]').get(0).checked = checked;
});
if (!this.orders.length) {
var orderInputs = $('#order input[type="radio"]').toArray();
$.each(orderInputs, function (i, input) {
browser.orders[i] = input.value;
});
}
var orders = this.orders;
if (!_.kuki.isSet('order'))
_.kuki.set('order', 'name');
if (!_.kuki.isSet('orderDesc'))
_.kuki.set('orderDesc', 'off');
$('#order input[value="' + _.kuki.get('order') + '"]').get(0).checked = true;
$('#order input[name="desc"]').get(0).checked = (_.kuki.get('orderDesc') == 'on');
$('#order input[type="radio"]').click(function() {
_.kuki.set('order', $(this).get(0).value);
browser.orderFiles();
});
$('#order input[name="desc"]').click(function() {
_.kuki.set('orderDesc', $(this).get(0).checked ? 'on' : 'off');
browser.orderFiles();
});
if (!_.kuki.isSet('view'))
_.kuki.set('view', 'thumbs');
if (_.kuki.get('view') == 'list') {
$('#show input').each(function() { this.checked = true; });
$('#show input').each(function() { this.disabled = true; });
}
$('#view input[value="' + _.kuki.get('view') + '"]').get(0).checked = true;
$('#view input').click(function() {
var view = $(this).attr('value');
if (_.kuki.get('view') != view) {
_.kuki.set('view', view);
if (view == 'list') {
$('#show input').each(function() { this.checked = true; });
$('#show input').each(function() { this.disabled = true; });
} else {
$.each(browser.shows, function(i, val) {
$('#show input[name="' + val + '"]').get(0).checked =
(_.kuki.get('show' + val) == "on");
});
$('#show input').each(function() { this.disabled = false; });
}
}
browser.refresh();
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Toolbar functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initToolbar = function() {
$('#toolbar a').click(function() {
browser.hideDialog();
});
if (!_.kuki.isSet('displaySettings'))
_.kuki.set('displaySettings', 'off');
if (_.kuki.get('displaySettings') == 'on') {
$('#toolbar a[href="kcact:settings"]').addClass('selected');
$('#settings').css('display', 'block');
browser.resize();
}
$('#toolbar a[href="kcact:settings"]').click(function () {
if ($('#settings').css('display') == 'none') {
$(this).addClass('selected');
_.kuki.set('displaySettings', 'on');
$('#settings').css('display', 'block');
browser.fixFilesHeight();
} else {
$(this).removeClass('selected');
_.kuki.set('displaySettings', 'off');
$('#settings').css('display', 'none');
browser.fixFilesHeight();
}
return false;
});
$('#toolbar a[href="kcact:refresh"]').click(function() {
browser.refresh();
return false;
});
if (window.opener || this.opener.TinyMCE || $('iframe', window.parent.document).get(0))
$('#toolbar a[href="kcact:maximize"]').click(function() {
browser.maximize(this);
return false;
});
else
$('#toolbar a[href="kcact:maximize"]').css('display', 'none');
$('#toolbar a[href="kcact:about"]').click(function() {
var html = '<div class="box about">' +
'<div class="head"><a href="http://kcfinder.sunhater.com" target="_blank">KCFinder</a> ' + browser.version + '</div>';
if (browser.support.check4Update)
html += '<div id="checkver"><span class="loading"><span>' + browser.label("Checking for new version...") + '</span></span></div>';
html +=
'<div>' + browser.label("Licenses:") + ' GPLv2 & LGPLv2</div>' +
'<div>Copyright ©2010, 2011 Pavel Tzonkov</div>' +
'<button>' + browser.label("OK") + '</button>' +
'</div>';
$('#dialog').html(html);
$('#dialog').data('title', browser.label("About"));
browser.showDialog();
var close = function() {
browser.hideDialog();
browser.unshadow();
}
$('#dialog button').click(close);
var span = $('#checkver > span');
setTimeout(function() {
$.ajax({
dataType: 'json',
url: browser.baseGetData('check4Update'),
async: true,
success: function(data) {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
if (!data.version) {
span.html(browser.label("Unable to connect!"));
browser.showDialog();
return;
}
if (browser.version < data.version)
span.html('<a href="http://kcfinder.sunhater.com/download" target="_blank">' + browser.label("Download version {version} now!", {version: data.version}) + '</a>');
else
span.html(browser.label("KCFinder is up to date!"));
browser.showDialog();
},
error: function() {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
span.html(browser.label("Unable to connect!"));
browser.showDialog();
}
});
}, 1000);
$('#dialog').unbind();
return false;
});
this.initUploadButton();
};
browser.initUploadButton = function() {
var btn = $('#toolbar a[href="kcact:upload"]');
if (!this.access.files.upload) {
btn.css('display', 'none');
return;
}
var top = btn.get(0).offsetTop;
var width = btn.outerWidth();
var height = btn.outerHeight();
$('#toolbar').prepend('<div id="upload" style="top:' + top + 'px;width:' + width + 'px;height:' + height + 'px">' +
'<form enctype="multipart/form-data" method="post" target="uploadResponse" action="' + browser.baseGetData('upload') + '">' +
'<input type="file" name="upload[]" onchange="browser.uploadFile(this.form)" style="height:' + height + 'px" multiple="multiple" />' +
'<input type="hidden" name="dir" value="" />' +
'</form>' +
'</div>');
$('#upload input').css('margin-left', "-" + ($('#upload input').outerWidth() - width) + 'px');
$('#upload').mouseover(function() {
$('#toolbar a[href="kcact:upload"]').addClass('hover');
});
$('#upload').mouseout(function() {
$('#toolbar a[href="kcact:upload"]').removeClass('hover');
});
};
browser.uploadFile = function(form) {
if (!this.dirWritable) {
browser.alert(this.label("Cannot write to upload folder."));
$('#upload').detach();
browser.initUploadButton();
return;
}
form.elements[1].value = browser.dir;
$('<iframe id="uploadResponse" name="uploadResponse" src="javascript:;"></iframe>').prependTo(document.body);
$('#loading').html(this.label("Uploading file..."));
$('#loading').css('display', 'inline');
form.submit();
$('#uploadResponse').load(function() {
var response = $(this).contents().find('body').html();
$('#loading').css('display', 'none');
response = response.split("\n");
var selected = [], errors = [];
$.each(response, function(i, row) {
if (row.substr(0, 1) == '/')
selected[selected.length] = row.substr(1, row.length - 1)
else
errors[errors.length] = row;
});
if (errors.length)
browser.alert(errors.join("\n"));
if (!selected.length)
selected = null
browser.refresh(selected);
$('#upload').detach();
setTimeout(function() {
$('#uploadResponse').detach();
}, 1);
browser.initUploadButton();
});
};
browser.maximize = function(button) {
if (window.opener) {
window.moveTo(0, 0);
width = screen.availWidth;
height = screen.availHeight;
if ($.browser.opera)
height -= 50;
window.resizeTo(width, height);
} else if (browser.opener.TinyMCE) {
var win, ifr, id;
$('iframe', window.parent.document).each(function() {
if (/^mce_\d+_ifr$/.test($(this).attr('id'))) {
id = parseInt($(this).attr('id').replace(/^mce_(\d+)_ifr$/, "$1"));
win = $('#mce_' + id, window.parent.document);
ifr = $('#mce_' + id + '_ifr', window.parent.document);
}
});
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
win.css({
left: browser.maximizeMCE.left + 'px',
top: browser.maximizeMCE.top + 'px',
width: browser.maximizeMCE.width + 'px',
height: browser.maximizeMCE.height + 'px'
});
ifr.css({
width: browser.maximizeMCE.width - browser.maximizeMCE.Hspace + 'px',
height: browser.maximizeMCE.height - browser.maximizeMCE.Vspace + 'px'
});
} else {
$(button).addClass('selected')
browser.maximizeMCE = {
width: _.nopx(win.css('width')),
height: _.nopx(win.css('height')),
left: win.position().left,
top: win.position().top,
Hspace: _.nopx(win.css('width')) - _.nopx(ifr.css('width')),
Vspace: _.nopx(win.css('height')) - _.nopx(ifr.css('height'))
};
var width = $(window.parent).width();
var height = $(window.parent).height();
win.css({
left: $(window.parent).scrollLeft() + 'px',
top: $(window.parent).scrollTop() + 'px',
width: width + 'px',
height: height + 'px'
});
ifr.css({
width: width - browser.maximizeMCE.Hspace + 'px',
height: height - browser.maximizeMCE.Vspace + 'px'
});
}
} else if ($('iframe', window.parent.document).get(0)) {
var ifrm = $('iframe[name="' + window.name + '"]', window.parent.document);
var parent = ifrm.parent();
var width, height;
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
if (browser.maximizeThread) {
clearInterval(browser.maximizeThread);
browser.maximizeThread = null;
}
if (browser.maximizeW) browser.maximizeW = null;
if (browser.maximizeH) browser.maximizeH = null;
$.each($('*', window.parent.document).get(), function(i, e) {
e.style.display = browser.maximizeDisplay[i];
});
ifrm.css({
display: browser.maximizeCSS.display,
position: browser.maximizeCSS.position,
left: browser.maximizeCSS.left,
top: browser.maximizeCSS.top,
width: browser.maximizeCSS.width,
height: browser.maximizeCSS.height
});
$(window.parent).scrollLeft(browser.maximizeLest);
$(window.parent).scrollTop(browser.maximizeTop);
} else {
$(button).addClass('selected');
browser.maximizeCSS = {
display: ifrm.css('display'),
position: ifrm.css('position'),
left: ifrm.css('left'),
top: ifrm.css('top'),
width: ifrm.outerWidth() + 'px',
height: ifrm.outerHeight() + 'px'
};
browser.maximizeTop = $(window.parent).scrollTop();
browser.maximizeLeft = $(window.parent).scrollLeft();
browser.maximizeDisplay = [];
$.each($('*', window.parent.document).get(), function(i, e) {
browser.maximizeDisplay[i] = $(e).css('display');
$(e).css('display', 'none');
});
ifrm.css('display', 'block');
ifrm.parents().css('display', 'block');
var resize = function() {
width = $(window.parent).width();
height = $(window.parent).height();
if (!browser.maximizeW || (browser.maximizeW != width) ||
!browser.maximizeH || (browser.maximizeH != height)
) {
browser.maximizeW = width;
browser.maximizeH = height;
ifrm.css({
width: width + 'px',
height: height + 'px'
});
browser.resize();
}
}
ifrm.css('position', 'absolute');
if ((ifrm.offset().left == ifrm.position().left) &&
(ifrm.offset().top == ifrm.position().top)
)
ifrm.css({left: '0', top: '0'});
else
ifrm.css({
left: - ifrm.offset().left + 'px',
top: - ifrm.offset().top + 'px'
});
resize();
browser.maximizeThread = setInterval(resize, 250);
}
}
};
browser.refresh = function(selected) {
this.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:browser.dir},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.dirWritable = data.dirWritable;
browser.files = data.files ? data.files : [];
browser.orderFiles(null, selected);
browser.statusDir();
},
error: function() {
$('#files > div').css({opacity:'', filter:''});
$('#files').html(browser.label("Unknown error."));
}
});
};
| JavaScript |
// If this file exists in theme directory, it will be loaded in <head> section
var imgLoading = new Image();
imgLoading.src = 'themes/dark/img/loading.gif';
| JavaScript |
// If this file exists in theme directory, it will be loaded in <head> section
var imgLoading = new Image();
imgLoading.src = 'themes/oxygen/img/loading.gif';
| JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
String.prototype.toAlias = function() {
var str = this;
str = str.replace(/^\s+|\s+$/g, ''); //trim
str = str.toLowerCase();
var from = "àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđ";
var to = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd";
for (var i = 0, l = from.length; i < l; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9\s-]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
} | JavaScript |
(function($){
$.fn.extend({
mbAlias: function(options) {
var defaults = {
target: '#alias'
}
var options = $.extend(defaults, options);
return this.each(function() {
$(this).change(function(){
$(options.target).val($(this).val().toAlias());
});
});
}
});
})(jQuery); | JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2011 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . All rights reserved.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Dutch
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, niet beschikbaar</span>',
confirmCancel : 'Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?',
ok : 'OK',
cancel : 'Annuleren',
confirmationTitle : 'Bevestigen',
messageTitle : 'Informatie',
inputTitle : 'Vraag',
undo : 'Ongedaan maken',
redo : 'Opnieuw uitvoeren',
skip : 'Overslaan',
skipAll : 'Alles overslaan',
makeDecision : 'Welke actie moet uitgevoerd worden?',
rememberDecision: 'Onthoud mijn keuze'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'nl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd-m-yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappen',
FolderLoading : 'Laden...',
FolderNew : 'Vul de mapnaam in: ',
FolderRename : 'Vul de nieuwe mapnaam in: ',
FolderDelete : 'Weet je het zeker dat je de map "%1" wilt verwijderen?',
FolderRenaming : ' (Aanpassen...)',
FolderDeleting : ' (Verwijderen...)',
// Files
FileRename : 'Vul de nieuwe bestandsnaam in: ',
FileRenameExt : 'Weet je zeker dat je de extensie wilt wijzigen? Het bestand kan onbruikbaar worden.',
FileRenaming : 'Aanpassen...',
FileDelete : 'Weet je zeker dat je het bestand "%1" wilt verwijderen?',
FilesLoading : 'Laden...',
FilesEmpty : 'De map is leeg.',
FilesMoved : 'Bestand %1 is verplaatst naar %2:%3.',
FilesCopied : 'Bestand %1 is gekopieerd naar %2:%3.',
// Basket
BasketFolder : 'Mandje',
BasketClear : 'Mandje legen',
BasketRemove : 'Verwijder uit het mandje',
BasketOpenFolder : 'Bovenliggende map openen',
BasketTruncateConfirm : 'Weet je zeker dat je alle bestand uit het mandje wilt verwijderen?',
BasketRemoveConfirm : 'Weet je zeker dat je het bestand "%1" uit het mandje wilt verwijderen?',
BasketEmpty : 'Geen bestanden in het mandje, sleep bestanden hierheen.',
BasketCopyFilesHere : 'Bestanden kopiëren uit het mandje',
BasketMoveFilesHere : 'Bestanden verplaatsen uit het mandje',
BasketPasteErrorOther : 'Bestand %s foutmelding: %e',
BasketPasteMoveSuccess : 'De volgende bestanden zijn verplaatst: %s',
BasketPasteCopySuccess : 'De volgende bestanden zijn gekopieerd: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Uploaden',
UploadTip : 'Nieuw bestand uploaden',
Refresh : 'Vernieuwen',
Settings : 'Instellingen',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Selecteer',
SelectThumbnail : 'Selecteer miniatuurafbeelding',
View : 'Bekijken',
Download : 'Downloaden',
NewSubFolder : 'Nieuwe onderliggende map',
Rename : 'Naam wijzigen',
Delete : 'Verwijderen',
CopyDragDrop : 'Bestand hierheen kopiëren',
MoveDragDrop : 'Bestand hierheen verplaatsen',
// Dialogs
RenameDlgTitle : 'Naam wijzigen',
NewNameDlgTitle : 'Nieuwe naam',
FileExistsDlgTitle : 'Bestand bestaat al',
SysErrorDlgTitle : 'Systeemfout',
FileOverwrite : 'Overschrijven',
FileAutorename : 'Automatisch hernoemen',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuleren',
CloseBtn : 'Sluiten',
// Upload Panel
UploadTitle : 'Nieuw bestand uploaden',
UploadSelectLbl : 'Selecteer het bestand om te uploaden',
UploadProgressLbl : '(Bezig met uploaden, even geduld a.u.b...)',
UploadBtn : 'Upload geselecteerde bestand',
UploadBtnCancel : 'Annuleren',
UploadNoFileMsg : 'Kies een bestand van je computer.',
UploadNoFolder : 'Selecteer a.u.b. een map voordat je gaat uploaden.',
UploadNoPerms : 'Uploaden bestand niet toegestaan.',
UploadUnknError : 'Fout bij het versturen van het bestand.',
UploadExtIncorrect : 'Bestandsextensie is niet toegestaan in deze map.',
// Flash Uploads
UploadLabel : 'Te uploaden bestanden',
UploadTotalFiles : 'Totaal aantal bestanden:',
UploadTotalSize : 'Totale grootte:',
UploadAddFiles : 'Bestanden toevoegen',
UploadClearFiles : 'Bestanden wissen',
UploadCancel : 'Upload annuleren',
UploadRemove : 'Verwijderen',
UploadRemoveTip : 'Verwijder !f',
UploadUploaded : '!n% geüpload',
UploadProcessing : 'Verwerken...',
// Settings Panel
SetTitle : 'Instellingen',
SetView : 'Bekijken:',
SetViewThumb : 'Miniatuurafbeelding',
SetViewList : 'Lijst',
SetDisplay : 'Weergave:',
SetDisplayName : 'Bestandsnaam',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Bestandsgrootte',
SetSort : 'Sorteren op:',
SetSortName : 'Op bestandsnaam',
SetSortDate : 'Op datum',
SetSortSize : 'Op grootte',
// Status Bar
FilesCountEmpty : '<Lege map>',
FilesCountOne : '1 bestand',
FilesCountMany : '%1 bestanden',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Het was niet mogelijk om deze actie uit te voeren. (Fout %1)',
Errors :
{
10 : 'Ongeldig commando.',
11 : 'Het bestandstype komt niet voor in de aanvraag.',
12 : 'Het gevraagde brontype is niet geldig.',
102 : 'Ongeldige bestands- of mapnaam.',
103 : 'Het verzoek kon niet worden voltooid vanwege autorisatie beperkingen.',
104 : 'Het verzoek kon niet worden voltooid door beperkingen in de rechten op het bestandssysteem.',
105 : 'Ongeldige bestandsextensie.',
109 : 'Ongeldige aanvraag.',
110 : 'Onbekende fout.',
115 : 'Er bestaat al een bestand of map met deze naam.',
116 : 'Map niet gevonden, vernieuw de mappenlijst of kies een andere map.',
117 : 'Bestand niet gevonden, vernieuw de mappenlijst of kies een andere map.',
118 : 'Bron- en doelmap zijn gelijk.',
201 : 'Er bestaat al een bestand met dezelfde naam. Het geüploade bestand is hernoemd naar: "%1".',
202 : 'Ongeldige bestand.',
203 : 'Ongeldige bestand. Het bestand is te groot.',
204 : 'De geüploade file is kapot.',
205 : 'Er is geen hoofdmap gevonden.',
206 : 'Het uploaden van het bestand is om veiligheidsredenen afgebroken. Er is HTML code in het bestand aangetroffen.',
207 : 'Het geüploade bestand is hernoemd naar: "%1".',
300 : 'Bestand(en) verplaatsen is mislukt.',
301 : 'Bestand(en) kopiëren is mislukt.',
500 : 'Het uploaden van een bestand is momenteel niet mogelijk. Contacteer de beheerder en controleer het CKFinder configuratiebestand.',
501 : 'De ondersteuning voor miniatuurafbeeldingen is uitgeschakeld.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'De bestandsnaam mag niet leeg zijn.',
FileExists : 'Bestand %s bestaat al.',
FolderEmpty : 'De mapnaam mag niet leeg zijn.',
FileInvChar : 'De bestandsnaam mag de volgende tekens niet bevatten: \n\\ / : * ? " < > |',
FolderInvChar : 'De mapnaam mag de volgende tekens niet bevatten: \n\\ / : * ? " < > |',
PopupBlockView : 'Het was niet mogelijk om dit bestand in een nieuw venster te openen. Configureer de browser zodat het de popups van deze website niet blokkeert.',
XmlError : 'Het is niet gelukt om de XML van de webserver te laden.',
XmlEmpty : 'Het is niet gelukt om de XML van de webserver te laden. De server gaf een leeg resultaat terug.',
XmlRawResponse : 'Origineel resultaat van de server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : '%s herschalen',
sizeTooBig : 'Het is niet mogelijk om een breedte of hoogte in te stellen die groter is dan de originele afmetingen (%size).',
resizeSuccess : 'De afbeelding is met succes herschaald.',
thumbnailNew : 'Miniatuurafbeelding maken',
thumbnailSmall : 'Klein (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Groot (%s)',
newSize : 'Nieuwe afmetingen instellen',
width : 'Breedte',
height : 'Hoogte',
invalidHeight : 'Ongeldige hoogte.',
invalidWidth : 'Ongeldige breedte.',
invalidName : 'Ongeldige bestandsnaam.',
newImage : 'Nieuwe afbeelding maken',
noExtensionChange : 'De bestandsextensie kan niet worden gewijzigd.',
imageSmall : 'Bronafbeelding is te klein.',
contextMenuName : 'Herschalen',
lockRatio : 'Afmetingen vergrendelen',
resetSize : 'Afmetingen resetten'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Opslaan',
fileOpenError : 'Kan het bestand niet openen.',
fileSaveSuccess : 'Bestand is succesvol opgeslagen.',
contextMenuName : 'Wijzigen',
loadingFile : 'Bestand laden, even geduld a.u.b...'
},
Maximize :
{
maximize : 'Maximaliseren',
minimize : 'Minimaliseren'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Italian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['it'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, non disponibile</span>',
confirmCancel : 'Alcune delle opzioni sono state cambiate. Sei sicuro di voler chiudere la finestra di dialogo?',
ok : 'OK',
cancel : 'Annulla',
confirmationTitle : 'Confermare',
messageTitle : 'Informazione',
inputTitle : 'Domanda',
undo : 'Annulla',
redo : 'Ripristina',
skip : 'Ignora',
skipAll : 'Ignora tutti',
makeDecision : 'Che azione prendere?',
rememberDecision: 'Ricorda mia decisione'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'it',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Cartelle',
FolderLoading : 'Caricando...',
FolderNew : 'Nome della cartella: ',
FolderRename : 'Nuovo nome della cartella: ',
FolderDelete : 'Se sicuro di voler eliminare la cartella "%1"?',
FolderRenaming : ' (Rinominando...)',
FolderDeleting : ' (Eliminando...)',
// Files
FileRename : 'Nuovo nome del file: ',
FileRenameExt : 'Sei sicure di voler cambiare la estensione del file? Il file può risultare inusabile.',
FileRenaming : 'Rinominando...',
FileDelete : 'Sei sicuro di voler eliminare il file "%1"?',
FilesLoading : 'Caricamento in corso...',
FilesEmpty : 'Cartella vuota',
FilesMoved : 'File %1 mosso a %2:%3.',
FilesCopied : 'File %1 copiato in %2:%3.',
// Basket
BasketFolder : 'Cestino',
BasketClear : 'Svuota Cestino',
BasketRemove : 'Rimuove dal Cestino',
BasketOpenFolder : 'Apre Cartella Superiore',
BasketTruncateConfirm : 'Sei sicuro di voler svuotare il cestino?',
BasketRemoveConfirm : 'Sei sicuro di voler rimuovere il file "%1" dal cestino?',
BasketEmpty : 'Nessun file nel cestino, si deve prima trascinare qualcuno.',
BasketCopyFilesHere : 'Copia i File dal Cestino',
BasketMoveFilesHere : 'Muove i File dal Cestino',
BasketPasteErrorOther : 'File %s errore: %e',
BasketPasteMoveSuccess : 'File mossi: %s',
BasketPasteCopySuccess : 'File copiati: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Carica Nuovo File',
Refresh : 'Aggiorna',
Settings : 'Configurazioni',
Help : 'Aiuto',
HelpTip : 'Aiuto (Inglese)',
// Context Menus
Select : 'Seleziona',
SelectThumbnail : 'Seleziona la miniatura',
View : 'Vedi',
Download : 'Scarica',
NewSubFolder : 'Nuova Sottocartella',
Rename : 'Rinomina',
Delete : 'Elimina',
CopyDragDrop : 'Copia file qui',
MoveDragDrop : 'Muove file qui',
// Dialogs
RenameDlgTitle : 'Rinomina',
NewNameDlgTitle : 'Nuovo nome',
FileExistsDlgTitle : 'Il file già esiste',
SysErrorDlgTitle : 'Errore di Sistema',
FileOverwrite : 'Sovrascrivere',
FileAutorename : 'Rinomina automaticamente',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anulla',
CloseBtn : 'Chiudi',
// Upload Panel
UploadTitle : 'Carica Nuovo File',
UploadSelectLbl : 'Seleziona il file',
UploadProgressLbl : '(Caricamento in corso, attendere prego...)',
UploadBtn : 'Carica File',
UploadBtnCancel : 'Annulla',
UploadNoFileMsg : 'Seleziona il file da caricare',
UploadNoFolder : 'Seleziona il file prima di caricare.',
UploadNoPerms : 'Non è permesso il caricamento di file.',
UploadUnknError : 'Errore nel caricamento del file.',
UploadExtIncorrect : 'In questa cartella non sono permessi file con questa estensione.',
// Flash Uploads
UploadLabel : 'File da Caricare',
UploadTotalFiles : 'File:',
UploadTotalSize : 'Dimensione:',
UploadAddFiles : 'Aggiungi File',
UploadClearFiles : 'Elimina File',
UploadCancel : 'Annulla il Caricamento',
UploadRemove : 'Rimuovi',
UploadRemoveTip : 'Rimuove !f',
UploadUploaded : '!n% caricato',
UploadProcessing : 'Attendere...',
// Settings Panel
SetTitle : 'Configurazioni',
SetView : 'Vedi:',
SetViewThumb : 'Anteprima',
SetViewList : 'Lista',
SetDisplay : 'Informazioni:',
SetDisplayName : 'Nome del File',
SetDisplayDate : 'Data',
SetDisplaySize : 'Dimensione',
SetSort : 'Ordina:',
SetSortName : 'per Nome',
SetSortDate : 'per Data',
SetSortSize : 'per Dimensione',
// Status Bar
FilesCountEmpty : '<Nessun file>',
FilesCountOne : '1 file',
FilesCountMany : '%1 file',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Impossibile completare la richiesta. (Errore %1)',
Errors :
{
10 : 'Commando non valido.',
11 : 'Il tipo di risorsa non è stato specificato nella richiesta.',
12 : 'Il tipo di risorsa richiesto non è valido.',
102 : 'Nome di file o cartella non valido.',
103 : 'Non è stato possibile completare la richiesta a causa di restrizioni di autorizazione.',
104 : 'Non è stato possibile completare la richiesta a causa di restrizioni nei permessi del file system.',
105 : 'L\'estensione del file non è valida.',
109 : 'Richiesta invalida.',
110 : 'Errore sconosciuto.',
115 : 'Un file o cartella con lo stesso nome è già esistente.',
116 : 'Cartella non trovata. Prego aggiornare e riprovare.',
117 : 'File non trovato. Prego aggirnare la lista dei file e riprovare.',
118 : 'Il percorso di origine e di destino sono uguali.',
201 : 'Un file con lo stesso nome è già disponibile. Il file caricato è stato rinominato in "%1".',
202 : 'File invalido.',
203 : 'File invalido. La dimensione del file eccede i limiti del sistema.',
204 : 'Il file caricato è corrotto.',
205 : 'Il folder temporario non è disponibile new server.',
206 : 'Upload annullato per motivi di sicurezza. Il file contiene dati in formatto HTML.',
207 : 'Il file caricato è stato rinominato a "%1".',
300 : 'Non è stato possibile muovere i file.',
301 : 'Non è stato possibile copiare i file.',
500 : 'Questo programma è disabilitato per motivi di sicurezza. Prego contattare l\'amministratore del sistema e verificare le configurazioni di CKFinder.',
501 : 'Il supporto alle anteprime non è attivo.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Il nome del file non può essere vuoto.',
FileExists : 'File %s già esiste.',
FolderEmpty : 'Il nome della cartella non può essere vuoto.',
FileInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome del file: \n\\ / : * ? " < > |',
FolderInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome della cartella: \n\\ / : * ? " < > |',
PopupBlockView : 'Non è stato possile aprire il file in una nuova finestra. Prego configurare il browser e disabilitare i blocchi delle popup.',
XmlError : 'Non è stato possibile caricare la risposta XML dal server.',
XmlEmpty : 'Non è stato possibile caricare la risposta XML dal server. La risposta è vuota.',
XmlRawResponse : 'Risposta originale inviata dal server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Ridimensiona %s',
sizeTooBig : 'Non si può usare valori di altezza e larghezza che siano maggiore che le dimensioni originali (%size).',
resizeSuccess : 'Immagine ridimensionata.',
thumbnailNew : 'Crea una nuova thumbnail',
thumbnailSmall : 'Piccolo (%s)',
thumbnailMedium : 'Medio (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Nuove dimensioni',
width : 'Larghezza',
height : 'Altezza',
invalidHeight : 'Altezza non valida.',
invalidWidth : 'Larghezza non valida.',
invalidName : 'Nome del file non valido.',
newImage : 'Crea nuova immagine',
noExtensionChange : 'L\'estensione del file non può essere cambiata.',
imageSmall : 'L\'immagine originale è molto piccola.',
contextMenuName : 'Ridimensiona',
lockRatio : 'Blocca rapporto',
resetSize : 'Reimposta dimensione'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Salva',
fileOpenError : 'Non è stato possibile aprire il file.',
fileSaveSuccess : 'File salvato.',
contextMenuName : 'Modifica',
loadingFile : 'Attendere prego. Caricamento del file in corso...'
},
Maximize :
{
maximize : 'Massimizza',
minimize : 'Minimizza'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the German
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['de'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nicht verfügbar</span>',
confirmCancel : 'Einige Optionen wurden geändert. Wollen Sie den Dialog dennoch schließen?',
ok : 'OK',
cancel : 'Abbrechen',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Frage',
undo : 'Rückgängig',
redo : 'Wiederherstellen',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'de',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd.m.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Verzeichnisse',
FolderLoading : 'Laden...',
FolderNew : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderRename : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderDelete : 'Wollen Sie wirklich den Ordner "%1" löschen?',
FolderRenaming : ' (Umbenennen...)',
FolderDeleting : ' (Löschen...)',
// Files
FileRename : 'Bitte geben Sie den neuen Dateinamen an: ',
FileRenameExt : 'Wollen Sie wirklich die Dateierweiterung ändern? Die Datei könnte unbrauchbar werden!',
FileRenaming : 'Umbennenen...',
FileDelete : 'Wollen Sie wirklich die Datei "%1" löschen?',
FilesLoading : 'Laden...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Hochladen',
UploadTip : 'Neue Datei hochladen',
Refresh : 'Aktualisieren',
Settings : 'Einstellungen',
Help : 'Hilfe',
HelpTip : 'Hilfe',
// Context Menus
Select : 'Auswählen',
SelectThumbnail : 'Miniatur auswählen',
View : 'Ansehen',
Download : 'Herunterladen',
NewSubFolder : 'Neues Unterverzeichnis',
Rename : 'Umbenennen',
Delete : 'Löschen',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'Systemfehler',
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Abbrechen',
CloseBtn : 'Schließen',
// Upload Panel
UploadTitle : 'Neue Datei hochladen',
UploadSelectLbl : 'Bitte wählen Sie die Datei aus',
UploadProgressLbl : '(Die Daten werden übertragen, bitte warten...)',
UploadBtn : 'Ausgewählte Datei hochladen',
UploadBtnCancel : 'Abbrechen',
UploadNoFileMsg : 'Bitte wählen Sie eine Datei auf Ihrem Computer aus.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Entfernen',
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Einstellungen',
SetView : 'Ansicht:',
SetViewThumb : 'Miniaturansicht',
SetViewList : 'Liste',
SetDisplay : 'Anzeige:',
SetDisplayName : 'Dateiname',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Dateigröße',
SetSort : 'Sortierung:',
SetSortName : 'nach Dateinamen',
SetSortDate : 'nach Datum',
SetSortSize : 'nach Größe',
// Status Bar
FilesCountEmpty : '<Leeres Verzeichnis>',
FilesCountOne : '1 Datei',
FilesCountMany : '%1 Datei',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Ihre Anfrage konnte nicht bearbeitet werden. (Fehler %1)',
Errors :
{
10 : 'Unbekannter Befehl.',
11 : 'Der Ressourcentyp wurde nicht spezifiziert.',
12 : 'Der Ressourcentyp ist nicht gültig.',
102 : 'Ungültiger Datei oder Verzeichnisname.',
103 : 'Ihre Anfrage konnte wegen Authorisierungseinschränkungen nicht durchgeführt werden.',
104 : 'Ihre Anfrage konnte wegen Dateisystemeinschränkungen nicht durchgeführt werden.',
105 : 'Invalid file extension.',
109 : 'Unbekannte Anfrage.',
110 : 'Unbekannter Fehler.',
115 : 'Es existiert bereits eine Datei oder ein Ordner mit dem gleichen Namen.',
116 : 'Verzeichnis nicht gefunden. Bitte aktualisieren Sie die Anzeige und versuchen es noch einmal.',
117 : 'Datei nicht gefunden. Bitte aktualisieren Sie die Dateiliste und versuchen es noch einmal.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Es existiert bereits eine Datei unter gleichem Namen. Die hochgeladene Datei wurde unter "%1" gespeichert.',
202 : 'Ungültige Datei.',
203 : 'ungültige Datei. Die Dateigröße ist zu groß.',
204 : 'Die hochgeladene Datei ist korrupt.',
205 : 'Es existiert kein temp. Ordner für das Hochladen auf den Server.',
206 : 'Das Hochladen wurde aus Sicherheitsgründen abgebrochen. Die Datei enthält HTML-Daten.',
207 : 'Die hochgeladene Datei wurde unter "%1" gespeichert.',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Der Dateibrowser wurde aus Sicherheitsgründen deaktiviert. Bitte benachrichtigen Sie Ihren Systemadministrator und prüfen Sie die Konfigurationsdatei.',
501 : 'Die Miniaturansicht wurde deaktivert.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Der Dateinamen darf nicht leer sein.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'Der Verzeichnisname darf nicht leer sein.',
FileInvChar : 'Der Dateinamen darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
FolderInvChar : 'Der Verzeichnisname darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
PopupBlockView : 'Die Datei konnte nicht in einem neuen Fenster geöffnet werden. Bitte deaktivieren Sie in Ihrem Browser alle Popup-Blocker für diese Seite.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Klein (%s)',
thumbnailMedium : 'Mittel (%s)',
thumbnailLarge : 'Groß (%s)',
newSize : 'Set a new size', // MISSING
width : 'Breite',
height : 'Höhe',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Größenverhältnis beibehalten',
resetSize : 'Größe zurücksetzen'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Speichern',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maximieren',
minimize : 'Minimieren'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Polish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['pl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, wyłączone</span>',
confirmCancel : 'Pewne opcje zostały zmienione. Czy na pewno zamknąć okno dialogowe?',
ok : 'OK',
cancel : 'Anuluj',
confirmationTitle : 'Potwierdzenie',
messageTitle : 'Informacja',
inputTitle : 'Pytanie',
undo : 'Cofnij',
redo : 'Ponów',
skip : 'Pomiń',
skipAll : 'Pomiń wszystkie',
makeDecision : 'Wybierz jedną z opcji:',
rememberDecision: 'Zapamiętaj mój wybór'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'pl',
LangCode : 'pl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Foldery',
FolderLoading : 'Ładowanie...',
FolderNew : 'Podaj nazwę nowego folderu: ',
FolderRename : 'Podaj nową nazwę folderu: ',
FolderDelete : 'Czy na pewno chcesz usunąć folder "%1"?',
FolderRenaming : ' (Zmieniam nazwę...)',
FolderDeleting : ' (Kasowanie...)',
// Files
FileRename : 'Podaj nową nazwę pliku: ',
FileRenameExt : 'Czy na pewno chcesz zmienić rozszerzenie pliku? Może to spowodować problemy z otwieraniem pliku przez innych użytkowników.',
FileRenaming : 'Zmieniam nazwę...',
FileDelete : 'Czy na pewno chcesz usunąć plik "%1"?',
FilesLoading : 'Ładowanie...',
FilesEmpty : 'Folder jest pusty',
FilesMoved : 'Plik %1 został przeniesiony do %2:%3.',
FilesCopied : 'Plik %1 został skopiowany do %2:%3.',
// Basket
BasketFolder : 'Koszyk',
BasketClear : 'Wyczyść koszyk',
BasketRemove : 'Usuń z koszyka',
BasketOpenFolder : 'Otwórz folder z plikiem',
BasketTruncateConfirm : 'Czy naprawdę chcesz usunąć wszystkie pliki z koszyka?',
BasketRemoveConfirm : 'Czy naprawdę chcesz usunąć plik "%1" z koszyka?',
BasketEmpty : 'Brak plików w koszyku. Aby dodać plik, przeciągnij i upuść (drag\'n\'drop) dowolny plik do koszyka.',
BasketCopyFilesHere : 'Skopiuj pliki z koszyka',
BasketMoveFilesHere : 'Przenieś pliki z koszyka',
BasketPasteErrorOther : 'Plik: %s błąd: %e',
BasketPasteMoveSuccess : 'Następujące pliki zostały przeniesione: %s',
BasketPasteCopySuccess : 'Następujące pliki zostały skopiowane: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Wyślij',
UploadTip : 'Wyślij plik',
Refresh : 'Odśwież',
Settings : 'Ustawienia',
Help : 'Pomoc',
HelpTip : 'Wskazówka',
// Context Menus
Select : 'Wybierz',
SelectThumbnail : 'Wybierz miniaturkę',
View : 'Zobacz',
Download : 'Pobierz',
NewSubFolder : 'Nowy podfolder',
Rename : 'Zmień nazwę',
Delete : 'Usuń',
CopyDragDrop : 'Skopiuj plik tutaj',
MoveDragDrop : 'Przenieś plik tutaj',
// Dialogs
RenameDlgTitle : 'Zmiana nazwy',
NewNameDlgTitle : 'Nowa nazwa',
FileExistsDlgTitle : 'Plik już istnieje',
SysErrorDlgTitle : 'Błąd systemu',
FileOverwrite : 'Nadpisz',
FileAutorename : 'Zmień automatycznie nazwę',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anuluj',
CloseBtn : 'Zamknij',
// Upload Panel
UploadTitle : 'Wyślij plik',
UploadSelectLbl : 'Wybierz plik',
UploadProgressLbl : '(Trwa wysyłanie pliku, proszę czekać...)',
UploadBtn : 'Wyślij wybrany plik',
UploadBtnCancel : 'Anuluj',
UploadNoFileMsg : 'Wybierz plik ze swojego komputera.',
UploadNoFolder : 'Wybierz folder przed wysłaniem pliku.',
UploadNoPerms : 'Wysyłanie plików nie jest dozwolone.',
UploadUnknError : 'Błąd podczas wysyłania pliku.',
UploadExtIncorrect : 'Rozszerzenie pliku nie jest dozwolone w tym folderze.',
// Flash Uploads
UploadLabel : 'Pliki do wysłania',
UploadTotalFiles : 'Ilość razem:',
UploadTotalSize : 'Rozmiar razem:',
UploadAddFiles : 'Dodaj pliki',
UploadClearFiles : 'Wyczyść wszystko',
UploadCancel : 'Anuluj wysyłanie',
UploadRemove : 'Usuń',
UploadRemoveTip : 'Usuń !f',
UploadUploaded : 'Wysłano: !n',
UploadProcessing : 'Przetwarzanie...',
// Settings Panel
SetTitle : 'Ustawienia',
SetView : 'Widok:',
SetViewThumb : 'Miniaturki',
SetViewList : 'Lista',
SetDisplay : 'Wyświetlanie:',
SetDisplayName : 'Nazwa pliku',
SetDisplayDate : 'Data',
SetDisplaySize : 'Rozmiar pliku',
SetSort : 'Sortowanie:',
SetSortName : 'wg nazwy pliku',
SetSortDate : 'wg daty',
SetSortSize : 'wg rozmiaru',
// Status Bar
FilesCountEmpty : '<Pusty folder>',
FilesCountOne : '1 plik',
FilesCountMany : 'Ilość plików: %1',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Wykonanie operacji zakończyło się niepowodzeniem. (Błąd %1)',
Errors :
{
10 : 'Nieprawidłowe polecenie (command).',
11 : 'Brak wymaganego parametru: typ danych (resource type).',
12 : 'Nieprawidłowy typ danych (resource type).',
102 : 'Nieprawidłowa nazwa pliku lub folderu.',
103 : 'Wykonanie operacji nie jest możliwe: brak uprawnień.',
104 : 'Wykonanie operacji nie powiodło się z powodu niewystarczających uprawnień do systemu plików.',
105 : 'Nieprawidłowe rozszerzenie.',
109 : 'Nieprawiłowe żądanie.',
110 : 'Niezidentyfikowany błąd.',
115 : 'Plik lub folder o podanej nazwie już istnieje.',
116 : 'Nie znaleziono folderu. Odśwież panel i spróbuj ponownie.',
117 : 'Nie znaleziono pliku. Odśwież listę plików i spróbuj ponownie.',
118 : 'Ścieżki źródłowa i docelowa są jednakowe.',
201 : 'Plik o podanej nazwie już istnieje. Nazwa przesłanego pliku została zmieniona na "%1".',
202 : 'Nieprawidłowy plik.',
203 : 'Nieprawidłowy plik. Plik przekracza dozwolony rozmiar.',
204 : 'Przesłany plik jest uszkodzony.',
205 : 'Brak folderu tymczasowego na serwerze do przesyłania plików.',
206 : 'Przesyłanie pliku zakończyło się niepowodzeniem z powodów bezpieczeństwa. Plik zawiera dane przypominające HTML.',
207 : 'Nazwa przesłanego pliku została zmieniona na "%1".',
300 : 'Przenoszenie nie powiodło się.',
301 : 'Kopiowanie nie powiodo się.',
500 : 'Menedżer plików jest wyłączony z powodów bezpieczeństwa. Skontaktuj się z administratorem oraz sprawdź plik konfiguracyjny CKFindera.',
501 : 'Tworzenie miniaturek jest wyłączone.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Nazwa pliku nie może być pusta.',
FileExists : 'Plik %s już istnieje.',
FolderEmpty : 'Nazwa folderu nie może być pusta.',
FileInvChar : 'Nazwa pliku nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
FolderInvChar : 'Nazwa folderu nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
PopupBlockView : 'Otwarcie pliku w nowym oknie nie powiodło się. Należy zmienić konfigurację przeglądarki i wyłączyć wszelkie blokady okienek popup dla tej strony.',
XmlError : 'Nie można poprawnie załadować odpowiedzi XML z serwera WWW.',
XmlEmpty : 'Nie można załadować odpowiedzi XML z serwera WWW. Serwer zwrócił pustą odpowiedź.',
XmlRawResponse : 'Odpowiedź serwera: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Zmiana rozmiaru %s',
sizeTooBig : 'Nie możesz zmienić wysokości lub szerokości na wartość większą od oryginalnego rozmiaru (%size).',
resizeSuccess : 'Obrazek został pomyślnie przeskalowany.',
thumbnailNew : 'Utwórz nową miniaturkę',
thumbnailSmall : 'Mała (%s)',
thumbnailMedium : 'Średnia (%s)',
thumbnailLarge : 'Duża (%s)',
newSize : 'Podaj nowe wymiary',
width : 'Szerokość',
height : 'Wysokość',
invalidHeight : 'Nieprawidłowa wysokość.',
invalidWidth : 'Nieprawidłowa szerokość.',
invalidName : 'Nieprawidłowa nazwa pliku.',
newImage : 'Utwórz nowy obrazek',
noExtensionChange : 'Rozszerzenie pliku nie może zostac zmienione.',
imageSmall : 'Plik źródłowy jest zbyt mały.',
contextMenuName : 'Zmień rozmiar',
lockRatio : 'Zablokuj proporcje',
resetSize : 'Przywróć rozmiar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Zapisz',
fileOpenError : 'Nie udało się otworzyć pliku.',
fileSaveSuccess : 'Plik został zapisany pomyślnie.',
contextMenuName : 'Edytuj',
loadingFile : 'Trwa ładowanie pliku, proszę czekać...'
},
Maximize :
{
maximize : 'Maksymalizuj',
minimize : 'Minimalizuj'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Hungarian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['hu'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nem elérhető</span>',
confirmCancel : 'Az űrlap tartalma megváltozott, ám a változásokat nem rögzítette. Biztosan be szeretné zárni az űrlapot?',
ok : 'Rendben',
cancel : 'Mégsem',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Visszavonás',
redo : 'Ismétlés',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'hu',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy. m. d. HH:MM',
DateAmPm : ['de.', 'du.'],
// Folders
FoldersTitle : 'Mappák',
FolderLoading : 'Betöltés...',
FolderNew : 'Kérjük adja meg a mappa nevét: ',
FolderRename : 'Kérjük adja meg a mappa új nevét: ',
FolderDelete : 'Biztosan törölni szeretné a következő mappát: "%1"?',
FolderRenaming : ' (átnevezés...)',
FolderDeleting : ' (törlés...)',
// Files
FileRename : 'Kérjük adja meg a fájl új nevét: ',
FileRenameExt : 'Biztosan szeretné módosítani a fájl kiterjesztését? A fájl esetleg használhatatlan lesz.',
FileRenaming : 'Átnevezés...',
FileDelete : 'Biztosan törölni szeretné a következő fájlt: "%1"?',
FilesLoading : 'Betöltés...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Feltöltés',
UploadTip : 'Új fájl feltöltése',
Refresh : 'Frissítés',
Settings : 'Beállítások',
Help : 'Súgó',
HelpTip : 'Súgó (angolul)',
// Context Menus
Select : 'Kiválaszt',
SelectThumbnail : 'Bélyegkép kiválasztása',
View : 'Megtekintés',
Download : 'Letöltés',
NewSubFolder : 'Új almappa',
Rename : 'Átnevezés',
Delete : 'Törlés',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Mégsem',
CloseBtn : 'Bezárás',
// Upload Panel
UploadTitle : 'Új fájl feltöltése',
UploadSelectLbl : 'Válassza ki a feltölteni kívánt fájlt',
UploadProgressLbl : '(A feltöltés folyamatban, kérjük várjon...)',
UploadBtn : 'A kiválasztott fájl feltöltése',
UploadBtnCancel : 'Mégsem',
UploadNoFileMsg : 'Kérjük válassza ki a fájlt a számítógépéről.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Beállítások',
SetView : 'Nézet:',
SetViewThumb : 'bélyegképes',
SetViewList : 'listás',
SetDisplay : 'Megjelenik:',
SetDisplayName : 'fájl neve',
SetDisplayDate : 'dátum',
SetDisplaySize : 'fájlméret',
SetSort : 'Rendezés:',
SetSortName : 'fájlnév',
SetSortDate : 'dátum',
SetSortSize : 'méret',
// Status Bar
FilesCountEmpty : '<üres mappa>',
FilesCountOne : '1 fájl',
FilesCountMany : '%1 fájl',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'A parancsot nem sikerült végrehajtani. (Hiba: %1)',
Errors :
{
10 : 'Érvénytelen parancs.',
11 : 'A fájl típusa nem lett a kérés során beállítva.',
12 : 'A kívánt fájl típus érvénytelen.',
102 : 'Érvénytelen fájl vagy könyvtárnév.',
103 : 'Hitelesítési problémák miatt nem sikerült a kérést teljesíteni.',
104 : 'Jogosultsági problémák miatt nem sikerült a kérést teljesíteni.',
105 : 'Érvénytelen fájl kiterjesztés.',
109 : 'Érvénytelen kérés.',
110 : 'Ismeretlen hiba.',
115 : 'A fálj vagy mappa már létezik ezen a néven.',
116 : 'Mappa nem található. Kérjük frissítsen és próbálja újra.',
117 : 'Fájl nem található. Kérjük frissítsen és próbálja újra.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ilyen nevű fájl már létezett. A feltöltött fájl a következőre lett átnevezve: "%1".',
202 : 'Érvénytelen fájl.',
203 : 'Érvénytelen fájl. A fájl mérete túl nagy.',
204 : 'A feltöltött fájl hibás.',
205 : 'A szerveren nem található a feltöltéshez ideiglenes mappa.',
206 : 'Upload cancelled due to security reasons. The file contains HTML-like data.', // MISSING
207 : 'El fichero subido ha sido renombrado como "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'A fájl-tallózó biztonsági okok miatt nincs engedélyezve. Kérjük vegye fel a kapcsolatot a rendszer üzemeltetőjével és ellenőrizze a CKFinder konfigurációs fájlt.',
501 : 'A bélyegkép támogatás nincs engedélyezve.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'A fájl neve nem lehet üres.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'A mappa neve nem lehet üres.',
FileInvChar : 'A fájl neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
FolderInvChar : 'A mappa neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
PopupBlockView : 'A felugró ablak megnyitása nem sikerült. Kérjük ellenőrizze a böngészője beállításait és tiltsa le a felugró ablakokat blokkoló alkalmazásait erre a honlapra.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Szélesség',
height : 'Magasság',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Arány megtartása',
resetSize : 'Eredeti méret'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Mentés',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Teljes méret',
minimize : 'Kis méret'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Russian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['ru'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, недоступно</span>',
confirmCancel : 'Внесенные вами изменения будут утеряны. Вы уверены?',
ok : 'OK',
cancel : 'Отмена',
confirmationTitle : 'Подтверждение',
messageTitle : 'Информация',
inputTitle : 'Вопрос',
undo : 'Отменить',
redo : 'Повторить',
skip : 'Пропустить',
skipAll : 'Пропустить все',
makeDecision : 'Что следует сделать?',
rememberDecision: 'Запомнить мой выбор'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'ru',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd.mm.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Папки',
FolderLoading : 'Загрузка...',
FolderNew : 'Пожалуйста, введите новое имя папки: ',
FolderRename : 'Пожалуйста, введите новое имя папки: ',
FolderDelete : 'Вы уверены, что хотите удалить папку "%1"?',
FolderRenaming : ' (Переименовываю...)',
FolderDeleting : ' (Удаляю...)',
// Files
FileRename : 'Пожалуйста, введите новое имя файла: ',
FileRenameExt : 'Вы уверены, что хотите изменить расширение файла? Файл может стать недоступным.',
FileRenaming : 'Переименовываю...',
FileDelete : 'Вы уверены, что хотите удалить файл "%1"?',
FilesLoading : 'Загрузка...',
FilesEmpty : 'Пустая папка',
FilesMoved : 'Файл %1 перемещен в %2:%3.',
FilesCopied : 'Файл %1 скопирован в %2:%3.',
// Basket
BasketFolder : 'Корзина',
BasketClear : 'Очистить корзину',
BasketRemove : 'Убрать из корзины',
BasketOpenFolder : 'Перейти в папку этого файла',
BasketTruncateConfirm : 'Вы точно хотите очистить корзину?',
BasketRemoveConfirm : 'Вы точно хотите убрать файл "%1" из корзины?',
BasketEmpty : 'В корзине пока нет файлов, добавьте новые с помощью драг-н-дропа (перетащите файл в корзину).',
BasketCopyFilesHere : 'Скопировать файл из корзины',
BasketMoveFilesHere : 'Переместить файл из корзины',
BasketPasteErrorOther : 'Произошла ошибка при обработке файла %s: %e',
BasketPasteMoveSuccess : 'Файлы перемещены: %s',
BasketPasteCopySuccess : 'Файлы скопированы: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Загрузка',
UploadTip : 'Загрузить новый файл',
Refresh : 'Обновить',
Settings : 'Установки',
Help : 'Помощь',
HelpTip : 'Помощь',
// Context Menus
Select : 'Выбрать',
SelectThumbnail : 'Выбрать миниатюру',
View : 'Посмотреть',
Download : 'Сохранить',
NewSubFolder : 'Новая папка',
Rename : 'Переименовать',
Delete : 'Удалить',
CopyDragDrop : 'Копировать',
MoveDragDrop : 'Переместить',
// Dialogs
RenameDlgTitle : 'Переименовать',
NewNameDlgTitle : 'Новое имя',
FileExistsDlgTitle : 'Файл уже существует',
SysErrorDlgTitle : 'Системная ошибка',
FileOverwrite : 'Заменить файл',
FileAutorename : 'Автоматически переименовывать',
// Generic
OkBtn : 'ОК',
CancelBtn : 'Отмена',
CloseBtn : 'Закрыть',
// Upload Panel
UploadTitle : 'Загрузить новый файл',
UploadSelectLbl : 'Выбрать файл для загрузки',
UploadProgressLbl : '(Загрузка в процессе, пожалуйста подождите...)',
UploadBtn : 'Загрузить выбранный файл',
UploadBtnCancel : 'Отмена',
UploadNoFileMsg : 'Пожалуйста, выберите файл на вашем компьютере.',
UploadNoFolder : 'Пожалуйста, выберите папку, в которую вы хотите закачать файл.',
UploadNoPerms : 'Загрузка файлов запрещена.',
UploadUnknError : 'Ошибка при передаче файла.',
UploadExtIncorrect : 'В эту папку нельзя закачивать файлы с таким расширением.',
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Установки',
SetView : 'Просмотр:',
SetViewThumb : 'Миниатюры',
SetViewList : 'Список',
SetDisplay : 'Отобразить:',
SetDisplayName : 'Имя файла',
SetDisplayDate : 'Дата',
SetDisplaySize : 'Размер файла',
SetSort : 'Сортировка:',
SetSortName : 'по имени файла',
SetSortDate : 'по дате',
SetSortSize : 'по размеру',
// Status Bar
FilesCountEmpty : '<Пустая папка>',
FilesCountOne : '1 файл',
FilesCountMany : '%1 файлов',
// Size and Speed
Kb : '%1 кБ',
KbPerSecond : '%1 кБ/с',
// Connector Error Messages.
ErrorUnknown : 'Невозможно завершить запрос. (Ошибка %1)',
Errors :
{
10 : 'Неверная команда.',
11 : 'Тип ресурса не указан в запросе.',
12 : 'Неверный запрошенный тип ресурса.',
102 : 'Неверное имя файла или папки.',
103 : 'Невозможно завершить запрос из-за ограничений авторизации.',
104 : 'Невозможно завершить запрос из-за ограничения разрешений файловой системы.',
105 : 'Неверное расширение файла.',
109 : 'Неверный запрос.',
110 : 'Неизвестная ошибка.',
115 : 'Файл или папка с таким именем уже существует.',
116 : 'Папка не найдена. Пожалуйста, обновите вид папок и попробуйте еще раз.',
117 : 'Файл не найден. Пожалуйста, обновите список файлов и попробуйте еще раз.',
118 : 'Исходное расположение файла совпадает с указанным.',
201 : 'Файл с таким именем уже существует. Загруженный файл был переименован в "%1".',
202 : 'Неверный файл.',
203 : 'Неверный файл. Размер файла слишком большой.',
204 : 'Загруженный файл поврежден.',
205 : 'Недоступна временная папка для загрузки файлов на сервер.',
206 : 'Загрузка отменена из-за соображений безопасности. Файл содержит похожие на HTML данные.',
207 : 'Загруженный файл был переименован в "%1".',
300 : 'Произошла ошибка при перемещении файла(ов).',
301 : 'Произошла ошибка при копировании файла(ов).',
500 : 'Браузер файлов отключен из-за соображений безопасности. Пожалуйста, сообщите вашему системному администратру и проверьте конфигурационный файл CKFinder.',
501 : 'Поддержка миниатюр отключена.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Имя файла не может быть пустым.',
FileExists : 'Файл %s уже существует.',
FolderEmpty : 'Имя папки не может быть пустым.',
FileInvChar : 'Имя файла не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
FolderInvChar : 'Имя папки не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
PopupBlockView : 'Невозможно открыть файл в новом окне. Пожалуйста, проверьте настройки браузера и отключите все блокировки всплывающих окон для этого сайта.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Изменить размеры %s',
sizeTooBig : 'Нельзя указывать размеры больше, чем у оригинального файла (%size).',
resizeSuccess : 'Размеры успешно изменены.',
thumbnailNew : 'Создать миниатюру(ы)',
thumbnailSmall : 'Маленькая (%s)',
thumbnailMedium : 'Средняя (%s)',
thumbnailLarge : 'Большая (%s)',
newSize : 'Установить новые размеры',
width : 'Ширина',
height : 'Высота',
invalidHeight : 'Высота должна быть числом больше нуля.',
invalidWidth : 'Ширина должна быть числом больше нуля.',
invalidName : 'Неверное имя файла.',
newImage : 'Сохранить как новый файл',
noExtensionChange : 'Не удалось поменять расширение файла.',
imageSmall : 'Исходная картинка слишком маленькая.',
contextMenuName : 'Изменить размер',
lockRatio : 'Сохранять пропорции',
resetSize : 'Вернуть обычные размеры'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Сохранить',
fileOpenError : 'Не удалось открыть файл.',
fileSaveSuccess : 'Файл успешно сохранен.',
contextMenuName : 'Редактировать',
loadingFile : 'Файл загружается, пожалуйста подождите...'
},
Maximize :
{
maximize : 'Развернуть',
minimize : 'Свернуть'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Swedish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sv'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, Ej tillgänglig</span>',
confirmCancel : 'Några av de alternativ har ändrats. Är du säker på att stänga dialogrutan?',
ok : 'OK',
cancel : 'Avbryt',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Ångra',
redo : 'Gör om',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'sv',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappar',
FolderLoading : 'Laddar...',
FolderNew : 'Skriv namnet på den nya mappen: ',
FolderRename : 'Skriv det nya namnet på mappen: ',
FolderDelete : 'Är du säker på att du vill radera mappen "%1"?',
FolderRenaming : ' (Byter mappens namn...)',
FolderDeleting : ' (Raderar...)',
// Files
FileRename : 'Skriv det nya filnamnet: ',
FileRenameExt : 'Är du säker på att du fill ändra på filändelsen? Filen kan bli oanvändbar.',
FileRenaming : 'Byter filnamn...',
FileDelete : 'Är du säker på att du vill radera filen "%1"?',
FilesLoading : 'Laddar...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Ladda upp',
UploadTip : 'Ladda upp en ny fil',
Refresh : 'Uppdatera',
Settings : 'Inställningar',
Help : 'Hjälp',
HelpTip : 'Hjälp',
// Context Menus
Select : 'Infoga bild',
SelectThumbnail : 'Infoga som tumnagel',
View : 'Visa',
Download : 'Ladda ner',
NewSubFolder : 'Ny Undermapp',
Rename : 'Byt namn',
Delete : 'Radera',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Stäng',
// Upload Panel
UploadTitle : 'Ladda upp en ny fil',
UploadSelectLbl : 'Välj fil att ladda upp',
UploadProgressLbl : '(Laddar upp filen, var god vänta...)',
UploadBtn : 'Ladda upp den valda filen',
UploadBtnCancel : 'Avbryt',
UploadNoFileMsg : 'Välj en fil från din dator.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Inställningar',
SetView : 'Visa:',
SetViewThumb : 'Tumnaglar',
SetViewList : 'Lista',
SetDisplay : 'Visa:',
SetDisplayName : 'Filnamn',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Filstorlek',
SetSort : 'Sortering:',
SetSortName : 'Filnamn',
SetSortDate : 'Datum',
SetSortSize : 'Storlek',
// Status Bar
FilesCountEmpty : '<Tom Mapp>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB', // MISSING
KbPerSecond : '%1 kB/s', // MISSING
// Connector Error Messages.
ErrorUnknown : 'Begäran kunde inte utföras eftersom ett fel uppstod. (Error %1)',
Errors :
{
10 : 'Ogiltig begäran.',
11 : 'Resursens typ var inte specificerad i förfrågan.',
12 : 'Den efterfrågade resurstypen är inte giltig.',
102 : 'Ogiltigt fil- eller mappnamn.',
103 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheterna.',
104 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheter i filsystemet.',
105 : 'Ogiltig filändelse.',
109 : 'Ogiltig begäran.',
110 : 'Okänt fel.',
115 : 'En fil eller mapp med aktuellt namn finns redan.',
116 : 'Mappen kunde inte hittas. Var god uppdatera sidan och försök igen.',
117 : 'Filen kunde inte hittas. Var god uppdatera sidan och försök igen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'En fil med aktuellt namn fanns redan. Den uppladdade filen har döpts om till "%1".',
202 : 'Ogiltig fil.',
203 : 'Ogiltig fil. Filen var för stor.',
204 : 'Den uppladdade filen var korrupt.',
205 : 'En tillfällig mapp för uppladdning är inte tillgänglig på servern.',
206 : 'Uppladdningen stoppades av säkerhetsskäl. Filen innehåller HTML-liknande data.',
207 : 'Den uppladdade filen har döpts om till "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filhanteraren har stoppats av säkerhetsskäl. Var god kontakta administratören för att kontrollera konfigurationsfilen för CKFinder.',
501 : 'Stöd för tumnaglar har stängts av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnamnet får inte vara tomt.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'Mappens namn får inte vara tomt.',
FileInvChar : 'Filnamnet får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappens namn får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
PopupBlockView : 'Det gick inte att öppna filen i ett nytt fönster. Ändra inställningarna i din webbläsare och tillåt popupfönster för den här hemsidan.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Bredd',
height : 'Höjd',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Lås höjd/bredd förhållanden',
resetSize : 'Återställ storlek'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Spara',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maximera',
minimize : 'Minimera'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Turkish
* language. This is the base file for all translations.
*
* Turkish translation by Abdullah M CEYLAN a.k.a. Kenan Balamir.
* Last updated: 26-07-2011
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['tr'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility"> öğesi, mevcut değil</span>',
confirmCancel : 'Bazı seçenekler değiştirildi. Pencereyi kapatmak istiyor musunuz?',
ok : 'Tamam',
cancel : 'Vazgeç',
confirmationTitle : 'Onay',
messageTitle : 'Bilgi',
inputTitle : 'Soru',
undo : 'Geri Al',
redo : 'Yinele',
skip : 'Atla',
skipAll : 'Tümünü Atla',
makeDecision : 'Hangi işlem yapılsın?',
rememberDecision: 'Kararımı hatırla'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'tr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd/m/yyyy h:MM aa',
DateAmPm : ['GN', 'GC'],
// Folders
FoldersTitle : 'Klasörler',
FolderLoading : 'Yükleniyor...',
FolderNew : 'Lütfen yeni klasör adını yazın: ',
FolderRename : 'Lütfen yeni klasör adını yazın: ',
FolderDelete : '"%1" klasörünü silmek istediğinizden emin misiniz?',
FolderRenaming : ' (Yeniden adlandırılıyor...)',
FolderDeleting : ' (Siliniyor...)',
// Files
FileRename : 'Lütfen yeni dosyanın adını yazın: ',
FileRenameExt : 'Dosya uzantısını değiştirmek istiyor musunuz? Bu, dosyayı kullanılamaz hale getirebilir.',
FileRenaming : 'Yeniden adlandırılıyor...',
FileDelete : '"%1" dosyasını silmek istediğinizden emin misiniz?',
FilesLoading : 'Yükleniyor...',
FilesEmpty : 'Klasör boş',
FilesMoved : '%1 dosyası, %2:%3 içerisine taşındı',
FilesCopied : '%1 dosyası, %2:%3 içerisine kopyalandı',
// Basket
BasketFolder : 'Sepet',
BasketClear : 'Sepeti temizle',
BasketRemove : 'Sepetten sil',
BasketOpenFolder : 'Üst klasörü aç',
BasketTruncateConfirm : 'Sepetteki tüm dosyaları silmek istediğinizden emin misiniz?',
BasketRemoveConfirm : 'Sepetteki %1% dosyasını silmek istediğinizden emin misiniz?',
BasketEmpty : 'Sepette hiç dosya yok, birkaç tane sürükleyip bırakabilirsiniz',
BasketCopyFilesHere : 'Sepetten Dosya Kopyala',
BasketMoveFilesHere : 'Sepetten Dosya Taşı',
BasketPasteErrorOther : '%s Dosya Hatası: %e',
BasketPasteMoveSuccess : 'Taşınan dosya: %s',
BasketPasteCopySuccess : 'Kopyalanan dosya: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Yükle',
UploadTip : 'Yeni Dosya Yükle',
Refresh : 'Yenile',
Settings : 'Ayarlar',
Help : 'Yardım',
HelpTip : 'Yardım',
// Context Menus
Select : 'Seç',
SelectThumbnail : 'Önizleme Olarak Seç',
View : 'Görüntüle',
Download : 'İndir',
NewSubFolder : 'Yeni Altklasör',
Rename : 'Yeniden Adlandır',
Delete : 'Sil',
CopyDragDrop : 'Dosyayı buraya kopyala',
MoveDragDrop : 'Dosyayı buraya taşı',
// Dialogs
RenameDlgTitle : 'Yeniden Adlandır',
NewNameDlgTitle : 'Yeni Adı',
FileExistsDlgTitle : 'Dosya zaten var',
SysErrorDlgTitle : 'Sistem hatası',
FileOverwrite : 'Üzerine yaz',
FileAutorename : 'Oto-Yeniden Adlandır',
// Generic
OkBtn : 'Tamam',
CancelBtn : 'Vazgeç',
CloseBtn : 'Kapat',
// Upload Panel
UploadTitle : 'Yeni Dosya Yükle',
UploadSelectLbl : 'Yüklenecek dosyayı seçin',
UploadProgressLbl : '(Yükleniyor, lütfen bekleyin...)',
UploadBtn : 'Seçili Dosyayı Yükle',
UploadBtnCancel : 'Vazgeç',
UploadNoFileMsg : 'Lütfen bilgisayarınızdan dosya seçin',
UploadNoFolder : 'Lütfen yüklemeden önce klasör seçin.',
UploadNoPerms : 'Dosya yüklemeye izin verilmiyor.',
UploadUnknError : 'Dosya gönderme hatası.',
UploadExtIncorrect : 'Bu dosya uzantısına, bu klasörde izin verilmiyor.',
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Ayarlar',
SetView : 'Görünüm:',
SetViewThumb : 'Önizlemeler',
SetViewList : 'Liste',
SetDisplay : 'Gösterim:',
SetDisplayName : 'Dosya adı',
SetDisplayDate : 'Tarih',
SetDisplaySize : 'Dosya boyutu',
SetSort : 'Sıralama:',
SetSortName : 'Dosya adına göre',
SetSortDate : 'Tarihe göre',
SetSortSize : 'Boyuta göre',
// Status Bar
FilesCountEmpty : '<Klasörde Dosya Yok>',
FilesCountOne : '1 dosya',
FilesCountMany : '%1 dosya',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'İsteğinizi yerine getirmek mümkün değil. (Hata %1)',
Errors :
{
10 : 'Geçersiz komut.',
11 : 'İstekte kaynak türü belirtilmemiş.',
12 : 'Talep edilen kaynak türü geçersiz.',
102 : 'Geçersiz dosya ya da klasör adı.',
103 : 'Kimlik doğrulama kısıtlamaları nedeni ile talebinizi yerine getiremiyoruz.',
104 : 'Dosya sistemi kısıtlamaları nedeni ile talebinizi yerine getiremiyoruz.',
105 : 'Geçersiz dosya uzantısı.',
109 : 'Geçersiz istek.',
110 : 'Bilinmeyen hata.',
115 : 'Aynı isimde bir dosya ya da klasör zaten var.',
116 : 'Klasör bulunamadı. Lütfen yenileyin ve tekrar deneyin.',
117 : 'Dosya bulunamadı. Lütfen dosya listesini yenileyin ve tekrar deneyin.',
118 : 'Kaynak ve hedef yol aynı!',
201 : 'Aynı ada sahip bir dosya zaten var. Yüklenen dosyanın adı "%1" olarak değiştirildi.',
202 : 'Geçersiz dosya',
203 : 'Geçersiz dosya. Dosya boyutu çok büyük.',
204 : 'Yüklenen dosya bozuk.',
205 : 'Dosyaları yüklemek için gerekli geçici klasör sunucuda bulunamadı.',
206 : 'Güvenlik nedeni ile yükleme iptal edildi. Dosya HTML benzeri veri içeriyor.',
207 : 'Yüklenen dosyanın adı "%1" olarak değiştirildi.',
300 : 'Dosya taşıma işlemi başarısız.',
301 : 'Dosya kopyalama işlemi başarısız.',
500 : 'Güvenlik nedeni ile dosya gezgini devredışı bırakıldı. Lütfen sistem yöneticiniz ile irtibata geçin ve CKFinder yapılandırma dosyasını kontrol edin.',
501 : 'Önizleme desteği devredışı.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Dosya adı boş olamaz',
FileExists : '%s dosyası zaten var',
FolderEmpty : 'Klasör adı boş olamaz',
FileInvChar : 'Dosya adının içermesi mümkün olmayan karakterler: \n\\ / : * ? " < > |',
FolderInvChar : 'Klasör adının içermesi mümkün olmayan karakterler: \n\\ / : * ? " < > |',
PopupBlockView : 'Dosyayı yeni pencerede açmak için, tarayıcı ayarlarından bu sitenin açılır pencerelerine izin vermeniz gerekiyor.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Boyutlandır: %s',
sizeTooBig : 'Yükseklik ve genişlik değeri orijinal boyuttan büyük olduğundan, işlem gerçekleştirilemedi (%size).',
resizeSuccess : 'Resim başarıyla yeniden boyutlandırıldı.',
thumbnailNew : 'Yeni önizleme oluştur',
thumbnailSmall : 'Küçük (%s)',
thumbnailMedium : 'Orta (%s)',
thumbnailLarge : 'Büyük (%s)',
newSize : 'Yeni boyutu ayarla',
width : 'Genişlik',
height : 'Yükseklik',
invalidHeight : 'Geçersiz yükseklik.',
invalidWidth : 'Geçersiz genişlik.',
invalidName : 'Geçersiz dosya adı.',
newImage : 'Yeni resim oluştur',
noExtensionChange : 'Dosya uzantısı değiştirilemedi.',
imageSmall : 'Kaynak resim çok küçük',
contextMenuName : 'Boyutlandır',
lockRatio : 'Lock ratio', // MISSING
resetSize : 'Reset size' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Kaydet',
fileOpenError : 'Dosya açılamadı.',
fileSaveSuccess : 'Dosya başarıyla kaydedildi.',
contextMenuName : 'Düzenle',
loadingFile : 'Dosya yükleniyor, lütfen bekleyin...'
},
Maximize :
{
maximize : 'Maximize', // MISSING
minimize : 'Minimize' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the French
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['fr'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, Inaccessible</span>',
confirmCancel : 'Certaines options ont été modifiées. Êtes vous sûr de vouloir fermer cette fenêtre?',
ok : 'OK',
cancel : 'Annuler',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Annuler',
redo : 'Rétablir',
skip : 'Passer',
skipAll : 'Passer tout',
makeDecision : 'Quelle action choisir?',
rememberDecision: 'Se rappeller de la décision'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'fr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Dossiers',
FolderLoading : 'Chargement...',
FolderNew : 'Entrez le nouveau nom du dossier: ',
FolderRename : 'Entrez le nouveau nom du dossier: ',
FolderDelete : 'Êtes-vous sûr de vouloir effacer le dossier "%1"?',
FolderRenaming : ' (Renommage en cours...)',
FolderDeleting : ' (Suppression en cours...)',
// Files
FileRename : 'Entrez le nouveau nom du fichier: ',
FileRenameExt : 'Êtes-vous sûr de vouloir ¨changer l\'extension de ce fichier? Le fichier pourrait devenir inutilisable.',
FileRenaming : 'Renommage en cours...',
FileDelete : 'Êtes-vous sûr de vouloir effacer le fichier "%1"?',
FilesLoading : 'Chargement...',
FilesEmpty : 'Répertoire vide',
FilesMoved : 'Fichier %1 déplacé vers %2:%3.',
FilesCopied : 'Fichier %1 copié vers %2:%3.',
// Basket
BasketFolder : 'Corbeille',
BasketClear : 'Vider la corbeille',
BasketRemove : 'Retirer de la corbeille',
BasketOpenFolder : 'Ouvrir le répertiore parent',
BasketTruncateConfirm : 'Êtes vous sûr de vouloir supprimer tous les fichiers de la corbeille?',
BasketRemoveConfirm : 'Êtes vous sûr de vouloir supprimer le fichier "%1" de la corbeille?',
BasketEmpty : 'Aucun fichier dans la corbeille, déposez en queques uns.',
BasketCopyFilesHere : 'Copier des fichiers depuis la corbeille',
BasketMoveFilesHere : 'Déplacer des fichiers depuis la corbeille',
BasketPasteErrorOther : 'Fichier %s erreur: %e.',
BasketPasteMoveSuccess : 'Les fichiers suivant ont été déplacés: %s',
BasketPasteCopySuccess : 'Les fichiers suivant ont été copiés: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Envoyer',
UploadTip : 'Envoyer un nouveau fichier',
Refresh : 'Rafraîchir',
Settings : 'Configuration',
Help : 'Aide',
HelpTip : 'Aide',
// Context Menus
Select : 'Choisir',
SelectThumbnail : 'Choisir une miniature',
View : 'Voir',
Download : 'Télécharger',
NewSubFolder : 'Nouveau sous-dossier',
Rename : 'Renommer',
Delete : 'Effacer',
CopyDragDrop : 'Copier les fichiers ici',
MoveDragDrop : 'Déplacer les fichiers ici',
// Dialogs
RenameDlgTitle : 'Renommer',
NewNameDlgTitle : 'Nouveau fichier',
FileExistsDlgTitle : 'Fichier déjà existant',
SysErrorDlgTitle : 'Erreur système',
FileOverwrite : 'Ré-écrire',
FileAutorename : 'Re-nommage automatique',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuler',
CloseBtn : 'Fermer',
// Upload Panel
UploadTitle : 'Envoyer un nouveau fichier',
UploadSelectLbl : 'Sélectionner le fichier à télécharger',
UploadProgressLbl : '(Envoi en cours, veuillez patienter...)',
UploadBtn : 'Envoyer le fichier sélectionné',
UploadBtnCancel : 'Annuler',
UploadNoFileMsg : 'Sélectionner un fichier sur votre ordinateur.',
UploadNoFolder : 'Merci de sélectionner un répertoire avant l\'envoi.',
UploadNoPerms : 'L\'envoi de fichier n\'est pas autorisé.',
UploadUnknError : 'Erreur pendant l\'envoi du fichier.',
UploadExtIncorrect : 'L\'extension du fichier n\'est pas autorisée dans ce dossier.',
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Configuration',
SetView : 'Voir:',
SetViewThumb : 'Miniatures',
SetViewList : 'Liste',
SetDisplay : 'Affichage:',
SetDisplayName : 'Nom du fichier',
SetDisplayDate : 'Date',
SetDisplaySize : 'Taille du fichier',
SetSort : 'Classement:',
SetSortName : 'par Nom de Fichier',
SetSortDate : 'par Date',
SetSortSize : 'par Taille',
// Status Bar
FilesCountEmpty : '<Dossier Vide>',
FilesCountOne : '1 fichier',
FilesCountMany : '%1 fichiers',
// Size and Speed
Kb : '%1 ko',
KbPerSecond : '%1 ko/s',
// Connector Error Messages.
ErrorUnknown : 'La demande n\'a pas abouti. (Erreur %1)',
Errors :
{
10 : 'Commande invalide.',
11 : 'Le type de ressource n\'a pas été spécifié dans la commande.',
12 : 'Le type de ressource n\'est pas valide.',
102 : 'Nom de fichier ou de dossier invalide.',
103 : 'La demande n\'a pas abouti : problème d\'autorisations.',
104 : 'La demande n\'a pas abouti : problème de restrictions de permissions.',
105 : 'Extension de fichier invalide.',
109 : 'Demande invalide.',
110 : 'Erreur inconnue.',
115 : 'Un fichier ou un dossier avec ce nom existe déjà.',
116 : 'Ce dossier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
117 : 'Ce fichier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
118 : 'Les chemins vers la source et la cible sont les mêmes.',
201 : 'Un fichier avec ce nom existe déjà. Le fichier téléversé a été renommé en "%1".',
202 : 'Fichier invalide.',
203 : 'Fichier invalide. La taille est trop grande.',
204 : 'Le fichier téléversé est corrompu.',
205 : 'Aucun dossier temporaire n\'est disponible sur le serveur.',
206 : 'Envoi interrompu pour raisons de sécurité. Le fichier contient des données de type HTML.',
207 : 'The uploaded file was renamed to "%1".', // MISSING
300 : 'Le déplacement des fichiers a échoué.',
301 : 'La copie des fichiers a échoué.',
500 : 'L\'interface de gestion des fichiers est désactivé. Contactez votre administrateur et vérifier le fichier de configuration de CKFinder.',
501 : 'La fonction "miniatures" est désactivée.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Le nom du fichier ne peut être vide.',
FileExists : 'Le fichier %s existes déjà.',
FolderEmpty : 'Le nom du dossier ne peut être vide.',
FileInvChar : 'Le nom du fichier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
FolderInvChar : 'Le nom du dossier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
PopupBlockView : 'Il n\'a pas été possible d\'ouvrir la nouvelle fenêtre. Désactiver votre bloqueur de fenêtres pour ce site.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionner %s',
sizeTooBig : 'Impossible de modifier la hauteur ou la largeur de cette image pour une valeur plus grande que l\'original (%size).',
resizeSuccess : 'L\'image a été redimensionné avec succès.',
thumbnailNew : 'Créer une nouvelle vignette',
thumbnailSmall : 'Petit (%s)',
thumbnailMedium : 'Moyen (%s)',
thumbnailLarge : 'Gros (%s)',
newSize : 'Déterminer les nouvelles dimensions',
width : 'Largeur',
height : 'Hauteur',
invalidHeight : 'Hauteur invalide.',
invalidWidth : 'Largeur invalide.',
invalidName : 'Nom de fichier incorrect.',
newImage : 'Créer une nouvelle image',
noExtensionChange : 'L\'extension du fichier ne peut pas être changé.',
imageSmall : 'L\'image est trop petit',
contextMenuName : 'Redimensionner',
lockRatio : 'Conserver les proportions',
resetSize : 'Taille d\'origine'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Sauvegarder',
fileOpenError : 'Impossible d\'ouvrir le fichier',
fileSaveSuccess : 'Fichier sauvegardé avec succès.',
contextMenuName : 'Edition',
loadingFile : 'Chargement du fichier, veuillez patientez...'
},
Maximize :
{
maximize : 'Agrandir',
minimize : 'Minimiser'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Chinese-Simplified
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['zh-cn'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, 不可用</span>',
confirmCancel : '部分内容尚未保存,确定关闭对话框么?',
ok : '确定',
cancel : '取消',
confirmationTitle : '确认',
messageTitle : '提示',
inputTitle : '询问',
undo : '撤销',
redo : '重做',
skip : '跳过',
skipAll : '全部跳过',
makeDecision : '应采取何样措施?',
rememberDecision: '下次不再询问'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'zh-cn',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy年m月d日 h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : '文件夹',
FolderLoading : '正在加载文件夹...',
FolderNew : '请输入新文件夹名称: ',
FolderRename : '请输入新文件夹名称: ',
FolderDelete : '您确定要删除文件夹 "%1" 吗?',
FolderRenaming : ' (正在重命名...)',
FolderDeleting : ' (正在删除...)',
// Files
FileRename : '请输入新文件名: ',
FileRenameExt : '如果改变文件扩展名,可能会导致文件不可用。\r\n确定要更改吗?',
FileRenaming : '正在重命名...',
FileDelete : '您确定要删除文件 "%1" 吗?',
FilesLoading : '加载中...',
FilesEmpty : '空文件夹',
FilesMoved : '文件 %1 已移动至 %2:%3.',
FilesCopied : '文件 %1 已拷贝至 %2:%3.',
// Basket
BasketFolder : '临时文件夹',
BasketClear : '清空临时文件夹',
BasketRemove : '从临时文件夹移除',
BasketOpenFolder : '打开临时文件夹',
BasketTruncateConfirm : '确认清空临时文件夹?',
BasketRemoveConfirm : '确认从临时文件夹中移除文件 "%1"?',
BasketEmpty : '临时文件夹为空, 可拖放文件至其中.',
BasketCopyFilesHere : '从临时文件夹复制至此',
BasketMoveFilesHere : '从临时文件夹移动至此',
BasketPasteErrorOther : '文件 %s 出错: %e',
BasketPasteMoveSuccess : '已移动以下文件: %s',
BasketPasteCopySuccess : '已拷贝以下文件: %s',
// Toolbar Buttons (some used elsewhere)
Upload : '上传',
UploadTip : '上传文件',
Refresh : '刷新',
Settings : '设置',
Help : '帮助',
HelpTip : '查看在线帮助',
// Context Menus
Select : '选择',
SelectThumbnail : '选中缩略图',
View : '查看',
Download : '下载',
NewSubFolder : '创建子文件夹',
Rename : '重命名',
Delete : '删除',
CopyDragDrop : '将文件复制至此',
MoveDragDrop : '将文件移动至此',
// Dialogs
RenameDlgTitle : '重命名',
NewNameDlgTitle : '文件名',
FileExistsDlgTitle : '文件已存在',
SysErrorDlgTitle : '系统错误',
FileOverwrite : '自动覆盖重名',
FileAutorename : '自动重命名重名',
// Generic
OkBtn : '确定',
CancelBtn : '取消',
CloseBtn : '关闭',
// Upload Panel
UploadTitle : '上传文件',
UploadSelectLbl : '选定要上传的文件',
UploadProgressLbl : '(正在上传文件,请稍候...)',
UploadBtn : '上传选定的文件',
UploadBtnCancel : '取消',
UploadNoFileMsg : '请选择一个要上传的文件',
UploadNoFolder : '需先选择一个文件.',
UploadNoPerms : '无文件上传权限.',
UploadUnknError : '上传文件出错.',
UploadExtIncorrect : '此文件后缀在当前文件夹中不可用.',
// Flash Uploads
UploadLabel : '上传文件',
UploadTotalFiles : '上传总计:',
UploadTotalSize : '上传总大小:',
UploadAddFiles : '添加文件',
UploadClearFiles : '清空文件',
UploadCancel : '取消上传',
UploadRemove : '删除',
UploadRemoveTip : '已删除!f',
UploadUploaded : '已上传!n%',
UploadProcessing : '上传中...',
// Settings Panel
SetTitle : '设置',
SetView : '查看:',
SetViewThumb : '缩略图',
SetViewList : '列表',
SetDisplay : '显示:',
SetDisplayName : '文件名',
SetDisplayDate : '日期',
SetDisplaySize : '大小',
SetSort : '排列顺序:',
SetSortName : '按文件名',
SetSortDate : '按日期',
SetSortSize : '按大小',
// Status Bar
FilesCountEmpty : '<空文件夹>',
FilesCountOne : '1 个文件',
FilesCountMany : '%1 个文件',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : '请求的操作未能完成. (错误 %1)',
Errors :
{
10 : '无效的指令.',
11 : '文件类型不在许可范围之内.',
12 : '文件类型无效.',
102 : '无效的文件名或文件夹名称.',
103 : '由于作者限制,该请求不能完成.',
104 : '由于文件系统的限制,该请求不能完成.',
105 : '无效的扩展名.',
109 : '无效请求.',
110 : '未知错误.',
115 : '存在重名的文件或文件夹.',
116 : '文件夹不存在. 请刷新后再试.',
117 : '文件不存在. 请刷新列表后再试.',
118 : '目标位置与当前位置相同.',
201 : '文件与现有的重名. 新上传的文件改名为 "%1".',
202 : '无效的文件.',
203 : '无效的文件. 文件尺寸太大.',
204 : '上传文件已损失.',
205 : '服务器中的上传临时文件夹无效.',
206 : '因为安全原因,上传中断. 上传文件包含不能 HTML 类型数据.',
207 : '新上传的文件改名为 "%1".',
300 : '移动文件失败.',
301 : '复制文件失败.',
500 : '因为安全原因,文件不可浏览. 请联系系统管理员并检查CKFinder配置文件.',
501 : '不支持缩略图方式.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : '文件名不能为空.',
FileExists : '文件 %s 已存在.',
FolderEmpty : '文件夹名称不能为空.',
FileInvChar : '文件名不能包含以下字符: \n\\ / : * ? " < > |',
FolderInvChar : '文件夹名称不能包含以下字符: \n\\ / : * ? " < > |',
PopupBlockView : '未能在新窗口中打开文件. 请修改浏览器配置解除对本站点的锁定.',
XmlError : '从服务器读取XML数据出错',
XmlEmpty : '无法从服务器读取数据,因XML响应返回结果为空',
XmlRawResponse : '服务器返回原始结果: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : '改变尺寸 %s',
sizeTooBig : '无法大于原图尺寸 (%size).',
resizeSuccess : '图像尺寸已修改.',
thumbnailNew : '创建缩略图',
thumbnailSmall : '小 (%s)',
thumbnailMedium : '中 (%s)',
thumbnailLarge : '大 (%s)',
newSize : '设置新尺寸',
width : '宽度',
height : '高度',
invalidHeight : '无效高度.',
invalidWidth : '无效宽度.',
invalidName : '文件名无效.',
newImage : '创建图像',
noExtensionChange : '无法改变文件后缀.',
imageSmall : '原文件尺寸过小',
contextMenuName : '改变尺寸',
lockRatio : '锁定比例',
resetSize : '原始尺寸'
},
// Fileeditor plugin
Fileeditor :
{
save : '保存',
fileOpenError : '无法打开文件.',
fileSaveSuccess : '成功保存文件.',
contextMenuName : '编辑',
loadingFile : '加载文件中...'
},
Maximize :
{
maximize : '全屏',
minimize : '最小化'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Japanese
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['ja'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, は利用できません。</span>',
confirmCancel : '変更された項目があります。ウィンドウを閉じてもいいですか?',
ok : '適用',
cancel : 'キャンセル',
confirmationTitle : '確認',
messageTitle : 'インフォメーション',
inputTitle : '質問',
undo : '元に戻す',
redo : 'やり直す',
skip : 'スキップ',
skipAll : 'すべてスキップ',
makeDecision : 'どうしますか?',
rememberDecision: '注意:'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'ja',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Folders',
FolderLoading : '読み込み中...',
FolderNew : '新しいフォルダ名を入力してください: ',
FolderRename : '新しいフォルダ名を入力してください: ',
FolderDelete : '本当にフォルダ「"%1"」を削除してもよろしいですか?',
FolderRenaming : ' (リネーム中...)',
FolderDeleting : ' (削除中...)',
// Files
FileRename : '新しいファイル名を入力してください: ',
FileRenameExt : 'ファイルが使えなくなる可能性がありますが、本当に拡張子を変更してもよろしいですか?',
FileRenaming : 'リネーム中...',
FileDelete : '本当に「"%1"」を削除してもよろしいですか?',
FilesLoading : '読み込み中...',
FilesEmpty : 'ファイルがありません',
FilesMoved : ' %1 は %2:%3 に移動されました',
FilesCopied : ' %1 cは %2:%3 にコピーされました',
// Basket
BasketFolder : 'Basket',
BasketClear : 'バスケットを空にする',
BasketRemove : 'バスケットから削除',
BasketOpenFolder : '親フォルダを開く',
BasketTruncateConfirm : '本当にバスケットの中身を空にしますか?',
BasketRemoveConfirm : '本当に「"%1"」をバスケットから削除しますか?',
BasketEmpty : 'バスケットの中にファイルがありません。このエリアにドラッグ&ドロップして追加することができます。',
BasketCopyFilesHere : 'バスケットからファイルをコピー',
BasketMoveFilesHere : 'バスケットからファイルを移動',
BasketPasteErrorOther : 'ファイル %s のエラー: %e',
BasketPasteMoveSuccess : '以下のファイルが移動されました: %s',
BasketPasteCopySuccess : '以下のファイルがコピーされました: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'アップロード',
UploadTip : '新しいファイルのアップロード',
Refresh : '表示の更新',
Settings : 'カスタマイズ',
Help : 'ヘルプ',
HelpTip : 'ヘルプ',
// Context Menus
Select : 'この画像を選択',
SelectThumbnail : 'この画像のサムネイルを選択',
View : '画像だけを表示',
Download : 'ダウンロード',
NewSubFolder : '新しいフォルダに入れる',
Rename : 'ファイル名の変更',
Delete : '削除',
CopyDragDrop : 'コピーするファイルをここにドロップしてください',
MoveDragDrop : '移動するファイルをここにドロップしてください',
// Dialogs
RenameDlgTitle : 'リネーム',
NewNameDlgTitle : '新しい名前',
FileExistsDlgTitle : 'ファイルはすでに存在します。',
SysErrorDlgTitle : 'システムエラー',
FileOverwrite : '上書き',
FileAutorename : 'A自動でリネーム',
// Generic
OkBtn : 'OK',
CancelBtn : 'キャンセル',
CloseBtn : '閉じる',
// Upload Panel
UploadTitle : 'ファイルのアップロード',
UploadSelectLbl : 'アップロードするファイルを選択してください',
UploadProgressLbl : '(ファイルのアップロード中...)',
UploadBtn : 'アップロード',
UploadBtnCancel : 'キャンセル',
UploadNoFileMsg : 'ファイルを選んでください。',
UploadNoFolder : 'アップロードの前にフォルダを選択してください。',
UploadNoPerms : 'ファイルのアップロード権限がありません。',
UploadUnknError : 'ファイルの送信に失敗しました。',
UploadExtIncorrect : '選択されたファイルの拡張子は許可されていません。',
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : '表示のカスタマイズ',
SetView : '表示方法:',
SetViewThumb : 'サムネイル',
SetViewList : '表示形式',
SetDisplay : '表示する項目:',
SetDisplayName : 'ファイル名',
SetDisplayDate : '日時',
SetDisplaySize : 'ファイルサイズ',
SetSort : '表示の順番:',
SetSortName : 'ファイル名',
SetSortDate : '日付',
SetSortSize : 'サイズ',
// Status Bar
FilesCountEmpty : '<フォルダ内にファイルがありません>',
FilesCountOne : '1つのファイル',
FilesCountMany : '%1個のファイル',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'リクエストの処理に失敗しました。 (Error %1)',
Errors :
{
10 : '不正なコマンドです。',
11 : 'リソースタイプが特定できませんでした。',
12 : '要求されたリソースのタイプが正しくありません。',
102 : 'ファイル名/フォルダ名が正しくありません。',
103 : 'リクエストを完了できませんでした。認証エラーです。',
104 : 'リクエストを完了できませんでした。ファイルのパーミッションが許可されていません。',
105 : '拡張子が正しくありません。',
109 : '不正なリクエストです。',
110 : '不明なエラーが発生しました。',
115 : '同じ名前のファイル/フォルダがすでに存在しています。',
116 : 'フォルダが見つかりませんでした。ページを更新して再度お試し下さい。',
117 : 'ファイルが見つかりませんでした。ページを更新して再度お試し下さい。',
118 : '対象が移動元と同じ場所を指定されています。',
201 : '同じ名前のファイルがすでに存在しています。"%1" にリネームして保存されました。',
202 : '不正なファイルです。',
203 : 'ファイルのサイズが大きすぎます。',
204 : 'アップロードされたファイルは壊れています。',
205 : 'サーバ内の一時作業フォルダが利用できません。',
206 : 'セキュリティ上の理由からアップロードが取り消されました。このファイルにはHTMLに似たデータが含まれています。',
207 : 'ファイルは "%1" にリネームして保存されました。',
300 : 'ファイルの移動に失敗しました。',
301 : 'ファイルのコピーに失敗しました。',
500 : 'ファイルブラウザはセキュリティ上の制限から無効になっています。システム担当者に連絡をして、CKFinderの設定をご確認下さい。',
501 : 'サムネイル機能は無効になっています。'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'ファイル名を入力してください',
FileExists : ' %s はすでに存在しています。別の名前を入力してください。',
FolderEmpty : 'フォルダ名を入力してください',
FileInvChar : 'ファイルに以下の文字は使えません: \n\\ / : * ? " < > |',
FolderInvChar : 'フォルダに以下の文字は使えません: \n\\ / : * ? " < > |',
PopupBlockView : 'ファイルを新しいウィンドウで開くことに失敗しました。 お使いのブラウザの設定でポップアップをブロックする設定を解除してください。',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'リサイズ: %s',
sizeTooBig : 'オリジナルの画像よりも大きいサイズは指定できません。 (%size).',
resizeSuccess : '画像のリサイズに成功しました',
thumbnailNew : 'サムネイルをつくる',
thumbnailSmall : '小 (%s)',
thumbnailMedium : '中 (%s)',
thumbnailLarge : '大 (%s)',
newSize : 'Set new size',
width : '幅',
height : '高さ',
invalidHeight : '高さの値が不正です。',
invalidWidth : '幅の値が不正です。',
invalidName : 'ファイル名が不正です。',
newImage : '新しい画像を作成',
noExtensionChange : '拡張子は変更できません。',
imageSmall : '元画像が小さすぎます。',
contextMenuName : 'リサイズ',
lockRatio : 'ロック比率',
resetSize : 'サイズリセット'
},
// Fileeditor plugin
Fileeditor :
{
save : '保存',
fileOpenError : 'ファイルを開けませんでした。',
fileSaveSuccess : 'ファイルの保存が完了しました。',
contextMenuName : '編集',
loadingFile : 'ファイルの読み込み中...'
},
Maximize :
{
maximize : '最大化',
minimize : '最小化'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Slovak
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sk'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Niektore možnosti boli zmenené. Naozaj chcete zavrieť okno?',
ok : 'OK',
cancel : 'Zrušiť',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Späť',
redo : 'Znovu',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'sk',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'mm/dd/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Adresáre',
FolderLoading : 'Nahrávam...',
FolderNew : 'Zadajte prosím meno nového adresára: ',
FolderRename : 'Zadajte prosím meno nového adresára: ',
FolderDelete : 'Skutočne zmazať adresár "%1"?',
FolderRenaming : ' (Prebieha premenovanie adresára...)',
FolderDeleting : ' (Prebieha zmazanie adresára...)',
// Files
FileRename : 'Zadajte prosím meno nového súboru: ',
FileRenameExt : 'Skutočne chcete zmeniť príponu súboru? Upozornenie: zmenou prípony sa súbor môže stať nepoužiteľným, pokiaľ prípona nie je podporovaná.',
FileRenaming : 'Prebieha premenovanie súboru...',
FileDelete : 'Skutočne chcete odstrániť súbor "%1"?',
FilesLoading : 'Nahrávam...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Prekopírovať na server (Upload)',
UploadTip : 'Prekopírovať nový súbor',
Refresh : 'Znovunačítať (Refresh)',
Settings : 'Nastavenia',
Help : 'Pomoc',
HelpTip : 'Pomoc',
// Context Menus
Select : 'Vybrať',
SelectThumbnail : 'Select Thumbnail', // MISSING
View : 'Náhľad',
Download : 'Stiahnuť',
NewSubFolder : 'Nový podadresár',
Rename : 'Premenovať',
Delete : 'Zmazať',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Zrušiť',
CloseBtn : 'Zatvoriť',
// Upload Panel
UploadTitle : 'Nahrať nový súbor',
UploadSelectLbl : 'Vyberte súbor, ktorý chcete prekopírovať na server',
UploadProgressLbl : '(Prebieha kopírovanie, čakajte prosím...)',
UploadBtn : 'Prekopírovať vybratý súbor',
UploadBtnCancel : 'Zrušiť',
UploadNoFileMsg : 'Vyberte prosím súbor na Vašom počítači!',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Nastavenia',
SetView : 'Náhľad:',
SetViewThumb : 'Miniobrázky',
SetViewList : 'Zoznam',
SetDisplay : 'Zobraziť:',
SetDisplayName : 'Názov súboru',
SetDisplayDate : 'Dátum',
SetDisplaySize : 'Veľkosť súboru',
SetSort : 'Zoradenie:',
SetSortName : 'podľa názvu súboru',
SetSortDate : 'podľa dátumu',
SetSortSize : 'podľa veľkosti',
// Status Bar
FilesCountEmpty : '<Prázdny adresár>',
FilesCountOne : '1 súbor',
FilesCountMany : '%1 súborov',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Server nemohol dokončiť spracovanie požiadavky. (Chyba %1)',
Errors :
{
10 : 'Neplatný príkaz.',
11 : 'V požiadavke nebol špecifikovaný typ súboru.',
12 : 'Nepodporovaný typ súboru.',
102 : 'Neplatný názov súboru alebo adresára.',
103 : 'Nebolo možné dokončiť spracovanie požiadavky kvôli nepostačujúcej úrovni oprávnení.',
104 : 'Nebolo možné dokončiť spracovanie požiadavky kvôli obmedzeniam v prístupových právach ku súborom.',
105 : 'Neplatná prípona súboru.',
109 : 'Neplatná požiadavka.',
110 : 'Neidentifikovaná chyba.',
115 : 'Zadaný súbor alebo adresár už existuje.',
116 : 'Adresár nebol nájdený. Aktualizujte obsah adresára (Znovunačítať) a skúste znovu.',
117 : 'Súbor nebol nájdený. Aktualizujte obsah adresára (Znovunačítať) a skúste znovu.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Súbor so zadaným názvom už existuje. Prekopírovaný súbor bol premenovaný na "%1".',
202 : 'Neplatný súbor.',
203 : 'Neplatný súbor - súbor presahuje maximálnu povolenú veľkosť.',
204 : 'Kopírovaný súbor je poškodený.',
205 : 'Server nemá špecifikovaný dočasný adresár pre kopírované súbory.',
206 : 'Kopírovanie prerušené kvôli nedostatočnému zabezpečeniu. Súbor obsahuje HTML data.',
207 : 'Prekopírovaný súbor bol premenovaný na "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Prehliadanie súborov je zakázané kvôli bezpečnosti. Kontaktujte prosím administrátora a overte nastavenia v konfiguračnom súbore pre CKFinder.',
501 : 'Momentálne nie je zapnutá podpora pre generáciu miniobrázkov.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Názov súbor nesmie prázdny.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'Názov adresára nesmie byť prázdny.',
FileInvChar : 'Súbor nesmie obsahovať žiadny z nasledujúcich znakov: \n\\ / : * ? " < > |',
FolderInvChar : 'Adresár nesmie obsahovať žiadny z nasledujúcich znakov: \n\\ / : * ? " < > |',
PopupBlockView : 'Nebolo možné otvoriť súbor v novom okne. Overte nastavenia Vášho prehliadača a zakážte všetky blokovače popup okien pre túto webstránku.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Šírka',
height : 'Výška',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Zámok',
resetSize : 'Pôvodná veľkosť'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Uložiť',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maximalizovať',
minimize : 'Minimalizovať'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the English
* language. This is the base file for all translations.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['en'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>',
confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?',
ok : 'OK',
cancel : 'Cancel',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Undo',
redo : 'Redo',
skip : 'Skip',
skipAll : 'Skip all',
makeDecision : 'What action should be taken?',
rememberDecision: 'Remember my decision'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'en',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM','PM'],
// Folders
FoldersTitle : 'Folders',
FolderLoading : 'Loading...',
FolderNew : 'Please type the new folder name: ',
FolderRename : 'Please type the new folder name: ',
FolderDelete : 'Are you sure you want to delete the "%1" folder?',
FolderRenaming : ' (Renaming...)',
FolderDeleting : ' (Deleting...)',
// Files
FileRename : 'Please type the new file name: ',
FileRenameExt : 'Are you sure you want to change the file extension? The file may become unusable.',
FileRenaming : 'Renaming...',
FileDelete : 'Are you sure you want to delete the file "%1"?',
FilesLoading : 'Loading...',
FilesEmpty : 'The folder is empty.',
FilesMoved : 'File %1 moved to %2:%3.',
FilesCopied : 'File %1 copied to %2:%3.',
// Basket
BasketFolder : 'Basket',
BasketClear : 'Clear Basket',
BasketRemove : 'Remove from Basket',
BasketOpenFolder : 'Open Parent Folder',
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?',
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?',
BasketEmpty : 'No files in the basket, drag and drop some.',
BasketCopyFilesHere : 'Copy Files from Basket',
BasketMoveFilesHere : 'Move Files from Basket',
BasketPasteErrorOther : 'File %s error: %e',
BasketPasteMoveSuccess : 'The following files were moved: %s',
BasketPasteCopySuccess : 'The following files were copied: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Upload New File',
Refresh : 'Refresh',
Settings : 'Settings',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Select',
SelectThumbnail : 'Select Thumbnail',
View : 'View',
Download : 'Download',
NewSubFolder : 'New Subfolder',
Rename : 'Rename',
Delete : 'Delete',
CopyDragDrop : 'Copy File Here',
MoveDragDrop : 'Move File Here',
// Dialogs
RenameDlgTitle : 'Rename',
NewNameDlgTitle : 'New Name',
FileExistsDlgTitle : 'File Already Exists',
SysErrorDlgTitle : 'System Error',
FileOverwrite : 'Overwrite',
FileAutorename : 'Auto-rename',
// Generic
OkBtn : 'OK',
CancelBtn : 'Cancel',
CloseBtn : 'Close',
// Upload Panel
UploadTitle : 'Upload New File',
UploadSelectLbl : 'Select a file to upload',
UploadProgressLbl : '(Upload in progress, please wait...)',
UploadBtn : 'Upload Selected File',
UploadBtnCancel : 'Cancel',
UploadNoFileMsg : 'Please select a file from your computer.',
UploadNoFolder : 'Please select a folder before uploading.',
UploadNoPerms : 'File upload not allowed.',
UploadUnknError : 'Error sending the file.',
UploadExtIncorrect : 'File extension not allowed in this folder.',
// Flash Uploads
UploadLabel : 'Files to Upload',
UploadTotalFiles : 'Total Files:',
UploadTotalSize : 'Total Size:',
UploadAddFiles : 'Add Files',
UploadClearFiles : 'Clear Files',
UploadCancel : 'Cancel Upload',
UploadRemove : 'Remove',
UploadRemoveTip : 'Remove !f',
UploadUploaded : 'Uploaded !n%',
UploadProcessing : 'Processing...',
// Settings Panel
SetTitle : 'Settings',
SetView : 'View:',
SetViewThumb : 'Thumbnails',
SetViewList : 'List',
SetDisplay : 'Display:',
SetDisplayName : 'File Name',
SetDisplayDate : 'Date',
SetDisplaySize : 'File Size',
SetSort : 'Sorting:',
SetSortName : 'by File Name',
SetSortDate : 'by Date',
SetSortSize : 'by Size',
// Status Bar
FilesCountEmpty : '<Empty Folder>',
FilesCountOne : '1 file',
FilesCountMany : '%1 files',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'It was not possible to complete the request. (Error %1)',
Errors :
{
10 : 'Invalid command.',
11 : 'The resource type was not specified in the request.',
12 : 'The requested resource type is not valid.',
102 : 'Invalid file or folder name.',
103 : 'It was not possible to complete the request due to authorization restrictions.',
104 : 'It was not possible to complete the request due to file system permission restrictions.',
105 : 'Invalid file extension.',
109 : 'Invalid request.',
110 : 'Unknown error.',
115 : 'A file or folder with the same name already exists.',
116 : 'Folder not found. Please refresh and try again.',
117 : 'File not found. Please refresh the files list and try again.',
118 : 'Source and target paths are equal.',
201 : 'A file with the same name is already available. The uploaded file was renamed to "%1".',
202 : 'Invalid file.',
203 : 'Invalid file. The file size is too big.',
204 : 'The uploaded file is corrupt.',
205 : 'No temporary folder is available for upload in the server.',
206 : 'Upload cancelled due to security reasons. The file contains HTML-like data.',
207 : 'The uploaded file was renamed to "%1".',
300 : 'Moving file(s) failed.',
301 : 'Copying file(s) failed.',
500 : 'The file browser is disabled for security reasons. Please contact your system administrator and check the CKFinder configuration file.',
501 : 'The thumbnails support is disabled.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'The file name cannot be empty.',
FileExists : 'File %s already exists.',
FolderEmpty : 'The folder name cannot be empty.',
FileInvChar : 'The file name cannot contain any of the following characters: \n\\ / : * ? " < > |',
FolderInvChar : 'The folder name cannot contain any of the following characters: \n\\ / : * ? " < > |',
PopupBlockView : 'It was not possible to open the file in a new window. Please configure your browser and disable all popup blockers for this site.',
XmlError : 'It was not possible to properly load the XML response from the web server.',
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.',
XmlRawResponse : 'Raw response from the server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s',
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).',
resizeSuccess : 'Image resized successfully.',
thumbnailNew : 'Create a new thumbnail',
thumbnailSmall : 'Small (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Large (%s)',
newSize : 'Set a new size',
width : 'Width',
height : 'Height',
invalidHeight : 'Invalid height.',
invalidWidth : 'Invalid width.',
invalidName : 'Invalid file name.',
newImage : 'Create a new image',
noExtensionChange : 'File extension cannot be changed.',
imageSmall : 'Source image is too small.',
contextMenuName : 'Resize',
lockRatio : 'Lock ratio',
resetSize : 'Reset size'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save',
fileOpenError : 'Unable to open file.',
fileSaveSuccess : 'File saved successfully.',
contextMenuName : 'Edit',
loadingFile : 'Loading file, please wait...'
},
Maximize :
{
maximize : 'Maximize',
minimize : 'Minimize'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Danish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['da'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, ikke tilgængelig</span>',
confirmCancel : 'Nogle af indstillingerne er blevet ændret. Er du sikker på at lukke dialogen?',
ok : 'OK',
cancel : 'Annuller',
confirmationTitle : 'Bekræftelse',
messageTitle : 'Information',
inputTitle : 'Spørgsmål',
undo : 'Fortryd',
redo : 'Annuller fortryd',
skip : 'Skip',
skipAll : 'Skip alle',
makeDecision : 'Hvad skal der foretages?',
rememberDecision: 'Husk denne indstilling'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'da',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd-mm-yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Indlæser...',
FolderNew : 'Skriv navnet på den nye mappe: ',
FolderRename : 'Skriv det nye navn på mappen: ',
FolderDelete : 'Er du sikker på, at du vil slette mappen "%1"?',
FolderRenaming : ' (Omdøber...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv navnet på den nye fil: ',
FileRenameExt : 'Er du sikker på, at du vil ændre filtypen? Filen kan muligvis ikke bruges bagefter.',
FileRenaming : '(Omdøber...)',
FileDelete : 'Er du sikker på, at du vil slette filen "%1"?',
FilesLoading : 'Indlæser...',
FilesEmpty : 'Tom mappe',
FilesMoved : 'Filen %1 flyttet til %2:%3',
FilesCopied : 'Filen %1 kopieret til %2:%3',
// Basket
BasketFolder : 'Kurv',
BasketClear : 'Tøm kurv',
BasketRemove : 'Fjern fra kurv',
BasketOpenFolder : 'Åben overordnet mappe',
BasketTruncateConfirm : 'Er du sikker på at du vil tømme kurven?',
BasketRemoveConfirm : 'Er du sikker på at du vil slette filen "%1" fra kurven?',
BasketEmpty : 'Ingen filer i kurven, brug musen til at trække filer til kurven.',
BasketCopyFilesHere : 'Kopier Filer fra kurven',
BasketMoveFilesHere : 'Flyt Filer fra kurven',
BasketPasteErrorOther : 'Fil fejl: %e',
BasketPasteMoveSuccess : 'Følgende filer blev flyttet: %s',
BasketPasteCopySuccess : 'Følgende filer blev kopieret: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Upload ny fil',
Refresh : 'Opdatér',
Settings : 'Indstillinger',
Help : 'Hjælp',
HelpTip : 'Hjælp',
// Context Menus
Select : 'Vælg',
SelectThumbnail : 'Vælg thumbnail',
View : 'Vis',
Download : 'Download',
NewSubFolder : 'Ny undermappe',
Rename : 'Omdøb',
Delete : 'Slet',
CopyDragDrop : 'Kopier hertil',
MoveDragDrop : 'Flyt hertil',
// Dialogs
RenameDlgTitle : 'Omdøb',
NewNameDlgTitle : 'Nyt navn',
FileExistsDlgTitle : 'Filen eksisterer allerede',
SysErrorDlgTitle : 'System fejl',
FileOverwrite : 'Overskriv',
FileAutorename : 'Auto-omdøb',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annullér',
CloseBtn : 'Luk',
// Upload Panel
UploadTitle : 'Upload ny fil',
UploadSelectLbl : 'Vælg den fil, som du vil uploade',
UploadProgressLbl : '(Uploader, vent venligst...)',
UploadBtn : 'Upload filen',
UploadBtnCancel : 'Annuller',
UploadNoFileMsg : 'Vælg en fil på din computer.',
UploadNoFolder : 'Venligst vælg en mappe før upload startes.',
UploadNoPerms : 'Upload er ikke tilladt.',
UploadUnknError : 'Fejl ved upload.',
UploadExtIncorrect : 'Denne filtype er ikke tilladt i denne mappe.',
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Indstillinger',
SetView : 'Vis:',
SetViewThumb : 'Thumbnails',
SetViewList : 'Liste',
SetDisplay : 'Thumbnails:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Størrelse',
SetSort : 'Sortering:',
SetSortName : 'efter filnavn',
SetSortDate : 'efter dato',
SetSortSize : 'efter størrelse',
// Status Bar
FilesCountEmpty : '<tom mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke muligt at fuldføre handlingen. (Fejl: %1)',
Errors :
{
10 : 'Ugyldig handling.',
11 : 'Ressourcetypen blev ikke angivet i anmodningen.',
12 : 'Ressourcetypen er ikke gyldig.',
102 : 'Ugyldig fil eller mappenavn.',
103 : 'Det var ikke muligt at fuldføre handlingen på grund af en begrænsning i rettigheder.',
104 : 'Det var ikke muligt at fuldføre handlingen på grund af en begrænsning i filsystem rettigheder.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig anmodning.',
110 : 'Ukendt fejl.',
115 : 'En fil eller mappe med det samme navn eksisterer allerede.',
116 : 'Mappen blev ikke fundet. Opdatér listen eller prøv igen.',
117 : 'Filen blev ikke fundet. Opdatér listen eller prøv igen.',
118 : 'Originalplacering og destination er ens.',
201 : 'En fil med det samme filnavn eksisterer allerede. Den uploadede fil er blevet omdøbt til "%1".',
202 : 'Ugyldig fil.',
203 : 'Ugyldig fil. Filstørrelsen er for stor.',
204 : 'Den uploadede fil er korrupt.',
205 : 'Der er ikke en midlertidig mappe til upload til rådighed på serveren.',
206 : 'Upload annulleret af sikkerhedsmæssige årsager. Filen indeholder HTML-lignende data.',
207 : 'Den uploadede fil er blevet omdøbt til "%1".',
300 : 'Flytning af fil(er) fejlede.',
301 : 'Kopiering af fil(er) fejlede.',
500 : 'Filbrowseren er deaktiveret af sikkerhedsmæssige årsager. Kontakt systemadministratoren eller kontrollér CKFinders konfigurationsfil.',
501 : 'Understøttelse af thumbnails er deaktiveret.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet må ikke være tomt.',
FileExists : 'Fil %erne eksisterer allerede.',
FolderEmpty : 'Mappenavnet må ikke være tomt.',
FileInvChar : 'Filnavnet må ikke indeholde et af følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet må ikke indeholde et af følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Det var ikke muligt at åbne filen i et nyt vindue. Kontrollér konfigurationen i din browser, og deaktivér eventuelle popup-blokkere for denne hjemmeside.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Rediger størrelse %s',
sizeTooBig : 'Kan ikke ændre billedets højde eller bredde til en værdi større end dets originale størrelse (%size).',
resizeSuccess : 'Størrelsen er nu ændret.',
thumbnailNew : 'Opret ny thumbnail',
thumbnailSmall : 'Lille (%s)',
thumbnailMedium : 'Mellem (%s)',
thumbnailLarge : 'Stor (%s)',
newSize : 'Rediger størrelse',
width : 'Bredde',
height : 'Højde',
invalidHeight : 'Ugyldig højde.',
invalidWidth : 'Ugyldig bredde.',
invalidName : 'Ugyldigt filenavn.',
newImage : 'Opret nyt billede.',
noExtensionChange : 'Filtypen kan ikke ændres.',
imageSmall : 'Originalfilen er for lille.',
contextMenuName : 'Rediger størrelse',
lockRatio : 'Lås størrelsesforhold',
resetSize : 'Nulstil størrelse'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Gem',
fileOpenError : 'Filen kan ikke åbnes.',
fileSaveSuccess : 'Filen er nu gemt.',
contextMenuName : 'Rediger',
loadingFile : 'Henter fil, vent venligst...'
},
Maximize :
{
maximize : 'Maximér',
minimize : 'Minimize' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Norwegian Bokmål
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nb'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, utilgjenglig</span>',
confirmCancel : 'Noen av valgene har blitt endret. Er du sikker på at du vil lukke dialogen?',
ok : 'OK',
cancel : 'Avbryt',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Angre',
redo : 'Gjør om',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'no',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Laster...',
FolderNew : 'Skriv inn det nye mappenavnet: ',
FolderRename : 'Skriv inn det nye mappenavnet: ',
FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?',
FolderRenaming : ' (Endrer mappenavn...)',
FolderDeleting : ' (Sletter...)',
// Files
FileRename : 'Skriv inn det nye filnavnet: ',
FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig.',
FileRenaming : 'Endrer filnavn...',
FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?',
FilesLoading : 'Laster...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Last opp',
UploadTip : 'Last opp en ny fil',
Refresh : 'Oppdater',
Settings : 'Innstillinger',
Help : 'Hjelp',
HelpTip : 'Hjelp finnes kun på engelsk',
// Context Menus
Select : 'Velg',
SelectThumbnail : 'Velg Miniatyr',
View : 'Vis fullversjon',
Download : 'Last ned',
NewSubFolder : 'Ny Undermappe',
Rename : 'Endre navn',
Delete : 'Slett',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Lukk',
// Upload Panel
UploadTitle : 'Last opp ny fil',
UploadSelectLbl : 'Velg filen du vil laste opp',
UploadProgressLbl : '(Laster opp filen, vennligst vent...)',
UploadBtn : 'Last opp valgt fil',
UploadBtnCancel : 'Avbryt',
UploadNoFileMsg : 'Du må velge en fil fra din datamaskin.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Innstillinger',
SetView : 'Filvisning:',
SetViewThumb : 'Miniatyrbilder',
SetViewList : 'Liste',
SetDisplay : 'Vis:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Filstørrelse',
SetSort : 'Sorter etter:',
SetSortName : 'Filnavn',
SetSortDate : 'Dato',
SetSortSize : 'Størrelse',
// Status Bar
FilesCountEmpty : '<Tom Mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)',
Errors :
{
10 : 'Ugyldig kommando.',
11 : 'Ressurstypen ble ikke spesifisert i forepørselen.',
12 : 'Ugyldig ressurstype.',
102 : 'Ugyldig fil- eller mappenavn.',
103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.',
104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig forespørsel.',
110 : 'Ukjent feil.',
115 : 'Det finnes allerede en fil eller mappe med dette navnet.',
116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.',
117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1".',
202 : 'Ugyldig fil.',
203 : 'Ugyldig fil. Filen er for stor.',
204 : 'Den opplastede filen er korrupt.',
205 : 'Det finnes ingen midlertidig mappe for filopplastinger.',
206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.',
207 : 'Den opplastede filens navn har blitt endret til "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.',
501 : 'Funksjon for minityrbilder er skrudd av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet kan ikke være tomt.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'Mappenavnet kan ikke være tomt.',
FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Bredde',
height : 'Høyde',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Lås forhold',
resetSize : 'Tilbakestill størrelse'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Lagre',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maksimer',
minimize : 'Minimer'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Lithuanian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['lt'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nėra</span>',
confirmCancel : 'Kai kurie nustatymai buvo pakeisti. Ar tikrai norite uždaryti šį langą?',
ok : 'Gerai',
cancel : 'Atšaukti',
confirmationTitle : 'Patvirtinimas',
messageTitle : 'Informacija',
inputTitle : 'Klausimas',
undo : 'Veiksmas atgal',
redo : 'Veiksmas pirmyn',
skip : 'Praleisti',
skipAll : 'Praleisti viską',
makeDecision : 'Ką pasirinksite?',
rememberDecision: 'Atsiminti mano pasirinkimą'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'lt',
LangCode : 'lt',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy.mm.dd H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Segtuvai',
FolderLoading : 'Prašau palaukite...',
FolderNew : 'Prašau įrašykite naujo segtuvo pavadinimą: ',
FolderRename : 'Prašau įrašykite naujo segtuvo pavadinimą: ',
FolderDelete : 'Ar tikrai norite ištrinti "%1" segtuvą?',
FolderRenaming : ' (Pervadinama...)',
FolderDeleting : ' (Trinama...)',
// Files
FileRename : 'Prašau įrašykite naujo failo pavadinimą: ',
FileRenameExt : 'Ar tikrai norite pakeisti šio failo plėtinį? Failas gali būti nebepanaudojamas',
FileRenaming : 'Pervadinama...',
FileDelete : 'Ar tikrai norite ištrinti failą "%1"?',
FilesLoading : 'Prašau palaukite...',
FilesEmpty : 'Tuščias segtuvas',
FilesMoved : 'Failas %1 perkeltas į %2:%3',
FilesCopied : 'Failas %1 nukopijuotas į %2:%3',
// Basket
BasketFolder : 'Krepšelis',
BasketClear : 'Ištuštinti krepšelį',
BasketRemove : 'Ištrinti krepšelį',
BasketOpenFolder : 'Atidaryti failo segtuvą',
BasketTruncateConfirm : 'Ar tikrai norite ištrinti visus failus iš krepšelio?',
BasketRemoveConfirm : 'Ar tikrai norite ištrinti failą "%1" iš krepšelio?',
BasketEmpty : 'Krepšelyje failų nėra, nuvilkite ir įmeskite juos į krepšelį.',
BasketCopyFilesHere : 'Kopijuoti failus iš krepšelio',
BasketMoveFilesHere : 'Perkelti failus iš krepšelio',
BasketPasteErrorOther : 'Failo %s klaida: %e',
BasketPasteMoveSuccess : 'Atitinkami failai buvo perkelti: %s',
BasketPasteCopySuccess : 'Atitinkami failai buvo nukopijuoti: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Įkelti',
UploadTip : 'Įkelti naują failą',
Refresh : 'Atnaujinti',
Settings : 'Nustatymai',
Help : 'Pagalba',
HelpTip : 'Patarimai',
// Context Menus
Select : 'Pasirinkti',
SelectThumbnail : 'Pasirinkti miniatiūrą',
View : 'Peržiūrėti',
Download : 'Atsisiųsti',
NewSubFolder : 'Naujas segtuvas',
Rename : 'Pervadinti',
Delete : 'Ištrinti',
CopyDragDrop : 'Nukopijuoti failą čia',
MoveDragDrop : 'Perkelti failą čia',
// Dialogs
RenameDlgTitle : 'Pervadinti',
NewNameDlgTitle : 'Naujas pavadinimas',
FileExistsDlgTitle : 'Toks failas jau egzistuoja',
SysErrorDlgTitle : 'Sistemos klaida',
FileOverwrite : 'Užrašyti ant viršaus',
FileAutorename : 'Automatiškai pervadinti',
// Generic
OkBtn : 'Gerai',
CancelBtn : 'Atšaukti',
CloseBtn : 'Uždaryti',
// Upload Panel
UploadTitle : 'Įkelti naują failą',
UploadSelectLbl : 'Pasirinkite failą įkėlimui',
UploadProgressLbl : '(Vykdomas įkėlimas, prašau palaukite...)',
UploadBtn : 'Įkelti pasirinktą failą',
UploadBtnCancel : 'Atšaukti',
UploadNoFileMsg : 'Pasirinkite failą iš savo kompiuterio',
UploadNoFolder : 'Pasirinkite segtuvą prieš įkeliant.',
UploadNoPerms : 'Failų įkėlimas uždraustas.',
UploadUnknError : 'Įvyko klaida siunčiant failą.',
UploadExtIncorrect : 'Šiame segtuve toks failų plėtinys yra uždraustas.',
// Flash Uploads
UploadLabel : 'Įkeliami failai',
UploadTotalFiles : 'Iš viso failų:',
UploadTotalSize : 'Visa apimtis:',
UploadAddFiles : 'Pridėti failus',
UploadClearFiles : 'Išvalyti failus',
UploadCancel : 'Atšaukti nusiuntimą',
UploadRemove : 'Pašalinti',
UploadRemoveTip : 'Pašalinti !f',
UploadUploaded : 'Įkeltas !n%',
UploadProcessing : 'Apdorojama...',
// Settings Panel
SetTitle : 'Nustatymai',
SetView : 'Peržiūrėti:',
SetViewThumb : 'Miniatiūros',
SetViewList : 'Sąrašas',
SetDisplay : 'Rodymas:',
SetDisplayName : 'Failo pavadinimas',
SetDisplayDate : 'Data',
SetDisplaySize : 'Failo dydis',
SetSort : 'Rūšiavimas:',
SetSortName : 'pagal failo pavadinimą',
SetSortDate : 'pagal datą',
SetSortSize : 'pagal apimtį',
// Status Bar
FilesCountEmpty : '<Tuščias segtuvas>',
FilesCountOne : '1 failas',
FilesCountMany : '%1 failai',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Užklausos įvykdyti nepavyko. (Klaida %1)',
Errors :
{
10 : 'Neteisinga komanda.',
11 : 'Resurso rūšis nenurodyta užklausoje.',
12 : 'Neteisinga resurso rūšis.',
102 : 'Netinkamas failas arba segtuvo pavadinimas.',
103 : 'Nepavyko įvykdyti užklausos dėl autorizavimo apribojimų.',
104 : 'Nepavyko įvykdyti užklausos dėl failų sistemos leidimų apribojimų.',
105 : 'Netinkamas failo plėtinys.',
109 : 'Netinkama užklausa.',
110 : 'Nežinoma klaida.',
115 : 'Failas arba segtuvas su tuo pačiu pavadinimu jau yra.',
116 : 'Segtuvas nerastas. Pabandykite atnaujinti.',
117 : 'Failas nerastas. Pabandykite atnaujinti failų sąrašą.',
118 : 'Šaltinio ir nurodomos vietos nuorodos yra vienodos.',
201 : 'Failas su tuo pačiu pavadinimu jau tra. Įkeltas failas buvo pervadintas į "%1"',
202 : 'Netinkamas failas',
203 : 'Netinkamas failas. Failo apimtis yra per didelė.',
204 : 'Įkeltas failas yra pažeistas.',
205 : 'Nėra laikinojo segtuvo skirto failams įkelti.',
206 : 'Įkėlimas bus nutrauktas dėl saugumo sumetimų. Šiame faile yra HTML duomenys.',
207 : 'Įkeltas failas buvo pervadintas į "%1"',
300 : 'Failų perkėlimas nepavyko.',
301 : 'Failų kopijavimas nepavyko.',
500 : 'Failų naršyklė yra išjungta dėl saugumo nustaymų. Prašau susisiekti su sistemų administratoriumi ir patikrinkite CKFinder konfigūracinį failą.',
501 : 'Miniatiūrų palaikymas išjungtas.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Failo pavadinimas negali būti tuščias',
FileExists : 'Failas %s jau egzistuoja',
FolderEmpty : 'Segtuvo pavadinimas negali būti tuščias',
FileInvChar : 'Failo pavadinimas negali turėti bent vieno iš šių simbolių: \n\\ / : * ? " < > |',
FolderInvChar : 'Segtuvo pavadinimas negali turėti bent vieno iš šių simbolių: \n\\ / : * ? " < > |',
PopupBlockView : 'Nepavyko atidaryti failo naujame lange. Prašau pakeiskite savo naršyklės nustatymus, kad būtų leidžiami iškylantys langai šiame tinklapyje.',
XmlError : 'Nepavyko įkrauti XML atsako iš web serverio.',
XmlEmpty : 'Nepavyko įkrauti XML atsako iš web serverio. Serveris gražino tuščią užklausą.',
XmlRawResponse : 'Vientisas atsakas iš serverio: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Keisti matmenis %s',
sizeTooBig : 'Negalima nustatyti aukščio ir pločio į didesnius nei originalaus paveiksliuko (%size).',
resizeSuccess : 'Paveiksliuko matmenys pakeisti.',
thumbnailNew : 'Sukurti naują miniatiūrą',
thumbnailSmall : 'Mažas (%s)',
thumbnailMedium : 'Vidutinis (%s)',
thumbnailLarge : 'Didelis (%s)',
newSize : 'Nustatyti naujus matmenis',
width : 'Plotis',
height : 'Aukštis',
invalidHeight : 'Neteisingas aukštis.',
invalidWidth : 'Neteisingas plotis.',
invalidName : 'Neteisingas pavadinimas.',
newImage : 'Sukurti naują paveiksliuką',
noExtensionChange : 'Failo plėtinys negali būti pakeistas.',
imageSmall : 'Šaltinio paveiksliukas yra per mažas',
contextMenuName : 'Pakeisti matmenis',
lockRatio : 'Išlaikyti matmenų santykį',
resetSize : 'Nustatyti dydį iš naujo'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Išsaugoti',
fileOpenError : 'Nepavyko atidaryti failo.',
fileSaveSuccess : 'Failas sėkmingai išsaugotas.',
contextMenuName : 'Redaguoti',
loadingFile : 'Įkraunamas failas, prašau palaukite...'
},
Maximize :
{
maximize : 'Padidinti',
minimize : 'Sumažinti'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Chinese (Taiwan)
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['zh-tw'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'zh-tw',
LangCode : 'zh-tw',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'mm/dd/yyyy HH:MM',
DateAmPm : ['上午', '下午'],
// Folders
FoldersTitle : '目錄',
FolderLoading : '載入中...',
FolderNew : '請輸入新目錄名稱: ',
FolderRename : '請輸入新目錄名稱: ',
FolderDelete : '確定刪除 "%1" 這個目錄嗎?',
FolderRenaming : ' (修改目錄...)',
FolderDeleting : ' (刪除目錄...)',
// Files
FileRename : '請輸入新檔案名稱: ',
FileRenameExt : '確定變更這個檔案的副檔名嗎? 變更後 , 此檔案可能會無法使用 !',
FileRenaming : '修改檔案名稱...',
FileDelete : '確定要刪除這個檔案 "%1"?',
FilesLoading : '載入中...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : '上傳檔案',
UploadTip : '上傳一個新檔案',
Refresh : '重新整理',
Settings : '偏好設定',
Help : '說明',
HelpTip : '說明',
// Context Menus
Select : '選擇',
SelectThumbnail : 'Select Thumbnail', // MISSING
View : '瀏覽',
Download : '下載',
NewSubFolder : '建立新子目錄',
Rename : '重新命名',
Delete : '刪除',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : '確定',
CancelBtn : '取消',
CloseBtn : '關閉',
// Upload Panel
UploadTitle : '上傳新檔案',
UploadSelectLbl : '請選擇要上傳的檔案',
UploadProgressLbl : '(檔案上傳中 , 請稍候...)',
UploadBtn : '將檔案上傳到伺服器',
UploadBtnCancel : '取消',
UploadNoFileMsg : '請從你的電腦選擇一個檔案.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : '設定',
SetView : '瀏覽方式:',
SetViewThumb : '縮圖預覽',
SetViewList : '清單列表',
SetDisplay : '顯示欄位:',
SetDisplayName : '檔案名稱',
SetDisplayDate : '檔案日期',
SetDisplaySize : '檔案大小',
SetSort : '排序方式:',
SetSortName : '依 檔案名稱',
SetSortDate : '依 檔案日期',
SetSortSize : '依 檔案大小',
// Status Bar
FilesCountEmpty : '<此目錄沒有任何檔案>',
FilesCountOne : '1 個檔案',
FilesCountMany : '%1 個檔案',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : '無法連接到伺服器 ! (錯誤代碼 %1)',
Errors :
{
10 : '不合法的指令.',
11 : '連接過程中 , 未指定資源形態 !',
12 : '連接過程中出現不合法的資源形態 !',
102 : '不合法的檔案或目錄名稱 !',
103 : '無法連接:可能是使用者權限設定錯誤 !',
104 : '無法連接:可能是伺服器檔案權限設定錯誤 !',
105 : '無法上傳:不合法的副檔名 !',
109 : '不合法的請求 !',
110 : '不明錯誤 !',
115 : '檔案或目錄名稱重複 !',
116 : '找不到目錄 ! 請先重新整理 , 然後再試一次 !',
117 : '找不到檔案 ! 請先重新整理 , 然後再試一次 !',
118 : 'Source and target paths are equal.', // MISSING
201 : '伺服器上已有相同的檔案名稱 ! 您上傳的檔案名稱將會自動更改為 "%1".',
202 : '不合法的檔案 !',
203 : '不合法的檔案 ! 檔案大小超過預設值 !',
204 : '您上傳的檔案已經損毀 !',
205 : '伺服器上沒有預設的暫存目錄 !',
206 : '檔案上傳程序因為安全因素已被系統自動取消 ! 可能是上傳的檔案內容包含 HTML 碼 !',
207 : '您上傳的檔案名稱將會自動更改為 "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : '因為安全因素 , 檔案瀏覽器已被停用 ! 請聯絡您的系統管理者並檢查 CKFinder 的設定檔 config.php !',
501 : '縮圖預覽功能已被停用 !'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : '檔案名稱不能空白 !',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : '目錄名稱不能空白 !',
FileInvChar : '檔案名稱不能包含以下字元: \n\\ / : * ? " < > |',
FolderInvChar : '目錄名稱不能包含以下字元: \n\\ / : * ? " < > |',
PopupBlockView : '無法在新視窗開啟檔案 ! 請檢查瀏覽器的設定並且針對這個網站 關閉 <封鎖彈跳視窗> 這個功能 !',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Lock ratio', // MISSING
resetSize : 'Reset size' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maximize', // MISSING
minimize : 'Minimize' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Greek
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['el'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options were changed. Are you sure you want to close the dialog window?', // MISSING
ok : 'OK',
cancel : 'Ακύρωση',
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Αναίρεση',
redo : 'Επαναφορά',
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'el',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['ΜΜ', 'ΠΜ'],
// Folders
FoldersTitle : 'Φάκελοι',
FolderLoading : 'Φόρτωση...',
FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ',
FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ',
FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";',
FolderRenaming : ' (Μετονομασία...)',
FolderDeleting : ' (Διαγραφή...)',
// Files
FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ',
FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί',
FileRenaming : 'Μετονομασία...',
FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?',
FilesLoading : 'Φόρτωση...',
FilesEmpty : 'The folder is empty.', // MISSING
FilesMoved : 'File %1 moved to %2:%3.', // MISSING
FilesCopied : 'File %1 copied to %2:%3.', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from Basket', // MISSING
BasketOpenFolder : 'Open Parent Folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag and drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Μεταφόρτωση',
UploadTip : 'Μεταφόρτωση Νέου Αρχείου',
Refresh : 'Ανανέωση',
Settings : 'Ρυθμίσεις',
Help : 'Βοήθεια',
HelpTip : 'Βοήθεια',
// Context Menus
Select : 'Επιλογή',
SelectThumbnail : 'Επιλογή Μικρογραφίας',
View : 'Προβολή',
Download : 'Λήψη Αρχείου',
NewSubFolder : 'Νέος Υποφάκελος',
Rename : 'Μετονομασία',
Delete : 'Διαγραφή',
CopyDragDrop : 'Copy File Here', // MISSING
MoveDragDrop : 'Move File Here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New Name', // MISSING
FileExistsDlgTitle : 'File Already Exists', // MISSING
SysErrorDlgTitle : 'System Error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Ακύρωση',
CloseBtn : 'Κλείσιμο',
// Upload Panel
UploadTitle : 'Μεταφόρτωση Νέου Αρχείου',
UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί',
UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)',
UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου',
UploadBtnCancel : 'Ακύρωση',
UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας.',
UploadNoFolder : 'Please select a folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Flash Uploads
UploadLabel : 'Files to Upload', // MISSING
UploadTotalFiles : 'Total Files:', // MISSING
UploadTotalSize : 'Total Size:', // MISSING
UploadAddFiles : 'Add Files', // MISSING
UploadClearFiles : 'Clear Files', // MISSING
UploadCancel : 'Cancel Upload', // MISSING
UploadRemove : 'Remove', // MISSING
UploadRemoveTip : 'Remove !f', // MISSING
UploadUploaded : 'Uploaded !n%', // MISSING
UploadProcessing : 'Processing...', // MISSING
// Settings Panel
SetTitle : 'Ρυθμίσεις',
SetView : 'Προβολή:',
SetViewThumb : 'Μικρογραφίες',
SetViewList : 'Λίστα',
SetDisplay : 'Εμφάνιση:',
SetDisplayName : 'Όνομα Αρχείου',
SetDisplayDate : 'Ημερομηνία',
SetDisplaySize : 'Μέγεθος Αρχείου',
SetSort : 'Ταξινόμηση:',
SetSortName : 'βάσει Όνοματος Αρχείου',
SetSortDate : 'βάσει Ημερομήνιας',
SetSortSize : 'βάσει Μεγέθους',
// Status Bar
FilesCountEmpty : '<Κενός Φάκελος>',
FilesCountOne : '1 αρχείο',
FilesCountMany : '%1 αρχεία',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)',
Errors :
{
10 : 'Λανθασμένη Εντολή.',
11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.',
12 : 'Το resource type δεν είναι έγκυρο.',
102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.',
103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.',
104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.',
105 : 'Λανθασμένη Επέκταση Αρχείου.',
109 : 'Λανθασμένη Ενέργεια.',
110 : 'Άγνωστο Λάθος.',
115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.',
116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1".',
202 : 'Λανθασμένο Αρχείο.',
203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.',
204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.',
205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.',
206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.',
207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1".',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).',
501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή.',
FileExists : 'File %s already exists.', // MISSING
FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή.',
FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.',
XmlError : 'It was not possible to properly load the XML response from the web server.', // MISSING
XmlEmpty : 'It was not possible to load the XML response from the web server. The server returned an empty response.', // MISSING
XmlRawResponse : 'Raw response from the server: %s' // MISSING
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create a new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set a new size', // MISSING
width : 'Πλάτος',
height : 'Ύψος',
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create a new image', // MISSING
noExtensionChange : 'File extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small.', // MISSING
contextMenuName : 'Resize', // MISSING
lockRatio : 'Κλείδωμα Αναλογίας',
resetSize : 'Επαναφορά Αρχικού Μεγέθους'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Αποθήκευση',
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
},
Maximize :
{
maximize : 'Maximize', // MISSING
minimize : 'Minimize' // MISSING
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Spanish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['es'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, no disponible</span>',
confirmCancel : 'Algunas opciones se han cambiado\r\n¿Está seguro de querer cerrar el diálogo?',
ok : 'Aceptar',
cancel : 'Cancelar',
confirmationTitle : 'Confirmación',
messageTitle : 'Información',
inputTitle : 'Pregunta',
undo : 'Deshacer',
redo : 'Rehacer',
skip : 'Omitir',
skipAll : 'Omitir todos',
makeDecision : '¿Qué acción debe realizarse?',
rememberDecision: 'Recordar mi decisión'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'es',
LangCode : 'es',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Carpetas',
FolderLoading : 'Cargando...',
FolderNew : 'Por favor, escriba el nombre para la nueva carpeta: ',
FolderRename : 'Por favor, escriba el nuevo nombre para la carpeta: ',
FolderDelete : '¿Está seguro de que quiere borrar la carpeta "%1"?',
FolderRenaming : ' (Renombrando...)',
FolderDeleting : ' (Borrando...)',
// Files
FileRename : 'Por favor, escriba el nuevo nombre del fichero: ',
FileRenameExt : '¿Está seguro de querer cambiar la extensión del fichero? El fichero puede dejar de ser usable.',
FileRenaming : 'Renombrando...',
FileDelete : '¿Está seguro de que quiere borrar el fichero "%1"?',
FilesLoading : 'Cargando...',
FilesEmpty : 'Carpeta vacía',
FilesMoved : 'Fichero %1 movido a %2:%3.',
FilesCopied : 'Fichero %1 copiado a %2:%3.',
// Basket
BasketFolder : 'Cesta',
BasketClear : 'Vaciar cesta',
BasketRemove : 'Quitar de la cesta',
BasketOpenFolder : 'Abrir carpeta padre',
BasketTruncateConfirm : '¿Está seguro de querer quitar todos los ficheros de la cesta?',
BasketRemoveConfirm : '¿Está seguro de querer quitar el fichero "%1" de la cesta?',
BasketEmpty : 'No hay ficheros en la cesta, arrastra y suelta algunos.',
BasketCopyFilesHere : 'Copiar ficheros de la cesta',
BasketMoveFilesHere : 'Mover ficheros de la cesta',
BasketPasteErrorOther : 'Fichero %s error: %e',
BasketPasteMoveSuccess : 'Los siguientes ficheros han sido movidos: %s',
BasketPasteCopySuccess : 'Los siguientes ficheros han sido copiados: %s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Añadir',
UploadTip : 'Añadir nuevo fichero',
Refresh : 'Actualizar',
Settings : 'Configuración',
Help : 'Ayuda',
HelpTip : 'Ayuda',
// Context Menus
Select : 'Seleccionar',
SelectThumbnail : 'Seleccionar el icono',
View : 'Ver',
Download : 'Descargar',
NewSubFolder : 'Nueva Subcarpeta',
Rename : 'Renombrar',
Delete : 'Borrar',
CopyDragDrop : 'Copiar fichero aquí',
MoveDragDrop : 'Mover fichero aquí',
// Dialogs
RenameDlgTitle : 'Renombrar',
NewNameDlgTitle : 'Nuevo nombre',
FileExistsDlgTitle : 'Fichero existente',
SysErrorDlgTitle : 'Error de sistema',
FileOverwrite : 'Sobreescribir',
FileAutorename : 'Auto-renombrar',
// Generic
OkBtn : 'Aceptar',
CancelBtn : 'Cancelar',
CloseBtn : 'Cerrar',
// Upload Panel
UploadTitle : 'Añadir nuevo fichero',
UploadSelectLbl : 'Elija el fichero a subir',
UploadProgressLbl : '(Subida en progreso, por favor espere...)',
UploadBtn : 'Subir el fichero elegido',
UploadBtnCancel : 'Cancelar',
UploadNoFileMsg : 'Por favor, elija un fichero de su ordenador.',
UploadNoFolder : 'Por favor, escoja la carpeta antes de iniciar la subida.',
UploadNoPerms : 'No puede subir ficheros.',
UploadUnknError : 'Error enviando el fichero.',
UploadExtIncorrect : 'La extensión del fichero no está permitida en esta carpeta.',
// Flash Uploads
UploadLabel : 'Ficheros a subir',
UploadTotalFiles : 'Total de ficheros:',
UploadTotalSize : 'Tamaño total:',
UploadAddFiles : 'Añadir ficheros',
UploadClearFiles : 'Borrar ficheros',
UploadCancel : 'Cancelar subida',
UploadRemove : 'Quitar',
UploadRemoveTip : 'Quitar !f',
UploadUploaded : 'Enviado !n%',
UploadProcessing : 'Procesando...',
// Settings Panel
SetTitle : 'Configuración',
SetView : 'Vista:',
SetViewThumb : 'Iconos',
SetViewList : 'Lista',
SetDisplay : 'Mostrar:',
SetDisplayName : 'Nombre de fichero',
SetDisplayDate : 'Fecha',
SetDisplaySize : 'Peso del fichero',
SetSort : 'Ordenar:',
SetSortName : 'por Nombre',
SetSortDate : 'por Fecha',
SetSortSize : 'por Peso',
// Status Bar
FilesCountEmpty : '<Carpeta vacía>',
FilesCountOne : '1 fichero',
FilesCountMany : '%1 ficheros',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'No ha sido posible completar la solicitud. (Error %1)',
Errors :
{
10 : 'Comando incorrecto.',
11 : 'El tipo de recurso no ha sido especificado en la solicitud.',
12 : 'El tipo de recurso solicitado no es válido.',
102 : 'Nombre de fichero o carpeta no válido.',
103 : 'No se ha podido completar la solicitud debido a las restricciones de autorización.',
104 : 'No ha sido posible completar la solicitud debido a restricciones en el sistema de ficheros.',
105 : 'La extensión del archivo no es válida.',
109 : 'Petición inválida.',
110 : 'Error desconocido.',
115 : 'Ya existe un fichero o carpeta con ese nombre.',
116 : 'No se ha encontrado la carpeta. Por favor, actualice y pruebe de nuevo.',
117 : 'No se ha encontrado el fichero. Por favor, actualice la lista de ficheros y pruebe de nuevo.',
118 : 'Las rutas origen y destino son iguales.',
201 : 'Ya existía un fichero con ese nombre. El fichero subido ha sido renombrado como "%1".',
202 : 'Fichero inválido.',
203 : 'Fichero inválido. El peso es demasiado grande.',
204 : 'El fichero subido está corrupto.',
205 : 'La carpeta temporal no está disponible en el servidor para las subidas.',
206 : 'La subida se ha cancelado por razones de seguridad. El fichero contenía código HTML.',
207 : 'El fichero subido ha sido renombrado como "%1".',
300 : 'Ha fallado el mover el(los) fichero(s).',
301 : 'Ha fallado el copiar el(los) fichero(s).',
500 : 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el fichero de configuración de CKFinder.',
501 : 'El soporte para iconos está deshabilitado.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'El nombre del fichero no puede estar vacío.',
FileExists : 'El fichero %s ya existe.',
FolderEmpty : 'El nombre de la carpeta no puede estar vacío.',
FileInvChar : 'El nombre del fichero no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
FolderInvChar : 'El nombre de la carpeta no puede contener ninguno de los caracteres siguientes: \n\\ / : * ? " < > |',
PopupBlockView : 'No ha sido posible abrir el fichero en una nueva ventana. Por favor, configure su navegador y desactive todos los bloqueadores de ventanas para esta página.',
XmlError : 'No ha sido posible cargar correctamente la respuesta XML del servidor.',
XmlEmpty : 'No ha sido posible cargar correctamente la respuesta XML del servidor. El servidor envió una cadena vacía.',
XmlRawResponse : 'Respuesta del servidor: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionar %s',
sizeTooBig : 'No se puede poner la altura o anchura de la imagen mayor que las dimensiones originales (%size).',
resizeSuccess : 'Imagen redimensionada correctamente.',
thumbnailNew : 'Crear nueva minuatura',
thumbnailSmall : 'Pequeña (%s)',
thumbnailMedium : 'Mediana (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Establecer nuevo tamaño',
width : 'Ancho',
height : 'Alto',
invalidHeight : 'Altura inválida.',
invalidWidth : 'Anchura inválida.',
invalidName : 'Nombre no válido.',
newImage : 'Crear nueva imagen',
noExtensionChange : 'La extensión no se puede cambiar.',
imageSmall : 'La imagen original es demasiado pequeña.',
contextMenuName : 'Redimensionar',
lockRatio : 'Proporcional',
resetSize : 'Tamaño Original'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Guardar',
fileOpenError : 'No se puede abrir el fichero.',
fileSaveSuccess : 'Fichero guardado correctamente.',
contextMenuName : 'Editar',
loadingFile : 'Cargando fichero, por favor espere...'
},
Maximize :
{
maximize : 'Maximizar',
minimize : 'Minimizar'
}
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.