code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var QUnit = { // Initialize the configuration options init: function() { config = { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, blocking: false, autorun: false, assertions: [], filters: [], queue: [] }; var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } }, // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; synchronize(function() { if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } config.currentModule = name; config.moduleTestEnvironment = testEnvironment; config.moduleStats = { all: 0, bad: 0 }; QUnit.moduleStart( name, testEnvironment ); }); }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = testName, testEnvironment, testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = config.currentModule + " module: " + name; } if ( !validTest(name) ) { return; } synchronize(function() { QUnit.testStart( testName ); testEnvironment = extend({ setup: function() {}, teardown: function() {} }, config.moduleTestEnvironment); if (testEnvironmentArg) { extend(testEnvironment,testEnvironmentArg); } // allow utility functions to access the current test environment QUnit.current_testEnvironment = testEnvironment; config.assertions = []; config.expected = expected; try { if ( !config.pollution ) { saveGlobal(); } testEnvironment.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } if ( async ) { QUnit.stop(); } try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { start(); } } }); synchronize(function() { try { checkPollution(); testEnvironment.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; config.moduleStats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.appendChild(document.createTextNode(assertion.message || "(no message)")); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "block"; id("qunit-filter-pass").disabled = null; id("qunit-filter-missing").disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } QUnit.testDone( testName, bad, config.assertions.length ); if ( !window.setTimeout && !config.queue.length ) { done(); } }); if ( window.setTimeout && !config.doneTimer ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); } }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { push(expected != actual, actual, expected, message); }, deepEqual: function(a, b, message) { push(QUnit.equiv(a, b), a, b, message); }, notDeepEqual: function(a, b, message) { push(!QUnit.equiv(a, b), a, b, message); }, strictEqual: function(actual, expected, message) { push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { push(expected !== actual, actual, expected, message); }, start: function() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); QUnit.start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return Object.prototype.toString.call( obj ) === "[object "+ type +"]"; }, // Logging callbacks done: function(failures, total) {}, log: function(result, message) {}, testStart: function(name) {}, testDone: function(name, failures, total) {}, moduleStart: function(name, testEnvironment) {}, moduleDone: function(name, failures, total) {} }; // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } else if ( GETParams[i].search('=') > -1 ) { GETParams.splice( i, 1 ); i--; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } addEvent(window, "load", function() { // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { toolbar.style.display = "none"; var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : ""; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "qunit-filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var main = id('main'); if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } QUnit.start(); }); function done() { if ( config.doneTimer && window.clearTimeout ) { window.clearTimeout( config.doneTimer ); config.doneTimer = null; } if ( config.queue.length ) { config.doneTimer = window.setTimeout(function(){ if ( !config.queue.length ) { done(); } else { synchronize( done ); } }, 13); return; } config.autorun = true; // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), html = ['Tests completed in ', +new Date - config.started, ' milliseconds.<br/>', '<span class="passed">', config.stats.all - config.stats.bad, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad,'</span> failed.'].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { var result = id("qunit-testresult"); if ( !result ) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests.nextSibling ); } result.innerHTML = html; } QUnit.done( config.stats.bad, config.stats.all ); } function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) ); } function synchronize( callback ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(); } } function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( old, config.pollution ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.expected++; } var deletedGlobals = diff( config.pollution, old ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); config.expected++; } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (QUnit.is("String", o)) { return "string"; } else if (QUnit.is("Boolean", o)) { return "boolean"; } else if (QUnit.is("Number", o)) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (QUnit.is( "Array", o)) { return "array"; // consider: typeof new Date() === object } else if (QUnit.is( "Date", o)) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (QUnit.is( "RegExp", o)) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (QUnit.is( "Function", o)) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (QUnit.is("Array", obj)) { type = "array"; } else if (QUnit.is("Window", obj) || QUnit.is("global", obj)) { type = "window"; } else if (QUnit.is("HTMLDocument", obj)) { type = "document"; } else if (QUnit.is("HTMLCollection", obj) || QUnit.is("NodeList", obj)) { type = "nodelist"; } else if (/^\[object HTML/.test(Object.prototype.toString.call( obj ))) { type = "node"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '&lt;' : '<', close = this.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); })(this);
JavaScript
/* Copyright 2011, SeaJS v1.0.0 MIT Licensed build time: Aug 1 17:17 */ /** * @fileoverview A CommonJS module loader, focused on web. * @author lifesinger@gmail.com (Frank Wang) */ /** * Base namespace for the framework. */ this.seajs = { _seajs: this.seajs }; /** * @type {string} The version of the framework. It will be replaced * with "major.minor.patch" when building. */ seajs.version = '1.0.0'; // Module status: // 1. downloaded - The script file has been downloaded to the browser. // 2. define()d - The define() has been executed. // 3. memoize()d - The module info has been added to memoizedMods. // 4. require()d - The module.exports is available. /** * The private data. Internal use only. */ seajs._data = { /** * The configuration data. */ config: { /** * Debug mode. It will be turned off automatically when compressing. * @const */ debug: '%DEBUG%' }, /** * Modules that have been memoize()d. * { uri: { dependencies: [], factory: fn, exports: {} }, ... } */ memoizedMods: {}, /** * Store the module information for "real" work in the onload event. */ pendingMods: [], /** * Modules that are needed to load before all other modules. */ preloadMods: [] }; /** * The private utils. Internal use only. */ seajs._util = {}; /** * The inner namespace for methods. Internal use only. */ seajs._fn = {}; /** * @fileoverview The minimal language enhancement. */ (function(util) { var toString = Object.prototype.toString; var AP = Array.prototype; util.isString = function(val) { return toString.call(val) === '[object String]'; }; util.isFunction = function(val) { return toString.call(val) === '[object Function]'; }; util.isArray = Array.isArray || function(val) { return toString.call(val) === '[object Array]'; }; util.indexOf = Array.prototype.indexOf ? function(arr, item) { return arr.indexOf(item); } : function(arr, item) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === item) { return i; } } return -1; }; var forEach = util.forEach = AP.forEach ? function(arr, fn) { arr.forEach(fn); } : function(arr, fn) { for (var i = 0, len = arr.length; i < len; i++) { fn(arr[i], i, arr); } }; util.map = AP.map ? function(arr, fn) { return arr.map(fn); } : function(arr, fn) { var ret = []; forEach(arr, function(item, i, arr) { ret.push(fn(item, i, arr)); }); return ret; }; util.filter = AP.filter ? function(arr, fn) { return arr.filter(fn); } : function(arr, fn) { var ret = []; forEach(arr, function(item, i, arr) { if (fn(item, i, arr)) { ret.push(item); } }); return ret; }; util.now = Date.now || function() { return new Date().getTime(); }; })(seajs._util); /** * @fileoverview The error handler. */ (function(util, data) { var config = data.config; /** * The function to handle inner errors. * * @param {Object} o The error object. */ util.error = function(o) { // Throw errors. if (o.type === 'error') { throw 'Error occurs! ' + dump(o); } // Output debug info. else if (config.debug && typeof console !== 'undefined') { console[o.type](dump(o)); } }; function dump(o) { var out = ['{']; for (var p in o) { if (typeof o[p] === 'number' || typeof o[p] === 'string') { out.push(p + ': ' + o[p]); out.push(', '); } } out.pop(); out.push('}'); return out.join(''); } })(seajs._util, seajs._data); /** * @fileoverview The utils for the framework. */ (function(util, data, global) { var config = data.config; /** * Extracts the directory portion of a path. * dirname('a/b/c.js') ==> 'a/b/' * dirname('d.js') ==> './' * @see http://jsperf.com/regex-vs-split/2 */ function dirname(path) { var s = path.match(/.*(?=\/.*$)/); return (s ? s[0] : '.') + '/'; } /** * Canonicalizes a path. * realpath('./a//b/../c') ==> 'a/c' */ function realpath(path) { // 'file:///a//b/c' ==> 'file:///a/b/c' // 'http://a//b/c' ==> 'http://a/b/c' path = path.replace(/([^:\/])\/+/g, '$1\/'); // 'a/b/c', just return. if (path.indexOf('.') === -1) { return path; } var old = path.split('/'); var ret = [], part, i = 0, len = old.length; for (; i < len; i++) { part = old[i]; if (part === '..') { if (ret.length === 0) { util.error({ message: 'invalid path: ' + path, type: 'error' }); } ret.pop(); } else if (part !== '.') { ret.push(part); } } return ret.join('/'); } /** * Normalizes an url. */ function normalize(url) { url = realpath(url); // Adds the default '.js' extension except that the url ends with #. if (/#$/.test(url)) { url = url.slice(0, -1); } else if (url.indexOf('?') === -1 && !/\.(?:css|js)$/.test(url)) { url += '.js'; } return url; } /** * Parses alias in the module id. Only parse the prefix and suffix. */ function parseAlias(id) { var alias = config['alias']; var parts = id.split('/'); var last = parts.length - 1; parse(parts, 0); if (last) parse(parts, last); function parse(parts, i) { var part = parts[i]; if (alias && alias.hasOwnProperty(part)) { parts[i] = alias[part]; } } return parts.join('/'); } /** * Maps the module id. */ function parseMap(url) { // config.map: [[match, replace], ...] util.forEach(config['map'], function(rule) { if (rule && rule.length === 2) { url = url.replace(rule[0], rule[1]); } }); return url; } /** * Gets the host portion from url. */ function getHost(url) { return url.replace(/^(\w+:\/\/[^/]*)\/?.*$/, '$1'); } var loc = global['location']; var pageUrl = loc.protocol + '//' + loc.host + loc.pathname; // local file in IE: C:\path\to\xx.js if (pageUrl.indexOf('\\') !== -1) { pageUrl = pageUrl.replace(/\\/g, '/'); } var id2UriCache = {}; /** * Converts id to uri. * @param {string} id The module id. * @param {string=} refUrl The referenced uri for relative id. * @param {boolean=} noAlias When set to true, don't pass alias. */ function id2Uri(id, refUrl, noAlias) { // only run once. if (id2UriCache[id]) { return id; } if (!noAlias && config['alias']) { id = parseAlias(id); } refUrl = refUrl || pageUrl; var ret; // absolute id if (id.indexOf('://') !== -1) { ret = id; } // relative id else if (id.indexOf('./') === 0 || id.indexOf('../') === 0) { // Converts './a' to 'a', to avoid unnecessary loop in realpath. id = id.replace(/^\.\//, ''); ret = dirname(refUrl) + id; } // root id else if (id.indexOf('/') === 0) { ret = getHost(refUrl) + id; } // top-level id else { ret = getConfigBase() + '/' + id; } ret = normalize(ret); if (config['map']) { ret = parseMap(ret); } id2UriCache[ret] = true; return ret; } function getConfigBase() { if (!config.base) { util.error({ message: 'the config.base is empty', from: 'id2Uri', type: 'error' }); } return config.base; } /** * Converts ids to uris. * @param {Array.<string>} ids The module ids. * @param {string=} refUri The referenced uri for relative id. */ function ids2Uris(ids, refUri) { return util.map(ids, function(id) { return id2Uri(id, refUri); }); } var memoizedMods = data.memoizedMods; /** * Caches mod info to memoizedMods. */ function memoize(id, url, mod) { var uri; // define('id', [], fn) if (id) { uri = id2Uri(id, url, true); } else { uri = url; } mod.dependencies = ids2Uris(mod.dependencies, uri); memoizedMods[uri] = mod; // guest module in package if (id && url !== uri) { var host = memoizedMods[url]; if (host) { augmentPackageHostDeps(host.dependencies, mod.dependencies); } } } /** * Set mod.ready to true when all the requires of the module is loaded. */ function setReadyState(uris) { util.forEach(uris, function(uri) { if (memoizedMods[uri]) { memoizedMods[uri].ready = true; } }); } /** * Removes the "ready = true" uris from input. */ function getUnReadyUris(uris) { return util.filter(uris, function(uri) { var mod = memoizedMods[uri]; return !mod || !mod.ready; }); } /** * if a -> [b -> [c -> [a, e], d]] * call removeMemoizedCyclicUris(c, [a, e]) * return [e] */ function removeCyclicWaitingUris(uri, deps) { return util.filter(deps, function(dep) { return !isCyclicWaiting(memoizedMods[dep], uri); }); } function isCyclicWaiting(mod, uri) { if (!mod || mod.ready) { return false; } var deps = mod.dependencies || []; if (deps.length) { if (util.indexOf(deps, uri) !== -1) { return true; } else { for (var i = 0; i < deps.length; i++) { if (isCyclicWaiting(memoizedMods[deps[i]], uri)) { return true; } } return false; } } return false; } /** * For example: * sbuild host.js --combo * define('./host', ['./guest'], ...) * define('./guest', ['jquery'], ...) * The jquery is not combined to host.js, so we should add jquery * to host.dependencies */ function augmentPackageHostDeps(hostDeps, guestDeps) { util.forEach(guestDeps, function(guestDep) { if (util.indexOf(hostDeps, guestDep) === -1) { hostDeps.push(guestDep); } }); } util.dirname = dirname; util.id2Uri = id2Uri; util.ids2Uris = ids2Uris; util.memoize = memoize; util.setReadyState = setReadyState; util.getUnReadyUris = getUnReadyUris; util.removeCyclicWaitingUris = removeCyclicWaitingUris; if (data.config.debug) { util.realpath = realpath; util.normalize = normalize; util.parseAlias = parseAlias; util.getHost = getHost; } })(seajs._util, seajs._data, this); /** * @fileoverview DOM utils for fetching script etc. */ (function(util, data) { var head = document.getElementsByTagName('head')[0]; var isWebKit = navigator.userAgent.indexOf('AppleWebKit') !== -1; util.getAsset = function(url, callback, charset) { var isCSS = /\.css(?:\?|$)/i.test(url); var node = document.createElement(isCSS ? 'link' : 'script'); if (charset) node.setAttribute('charset', charset); assetOnload(node, function() { if (callback) callback.call(node); if (isCSS) return; // Don't remove inserted node when debug is on. if (!data.config.debug) { try { // Reduces memory leak. if (node.clearAttributes) { node.clearAttributes(); } else { for (var p in node) delete node[p]; } } catch (x) { } head.removeChild(node); } }); if (isCSS) { node.rel = 'stylesheet'; node.href = url; head.appendChild(node); // keep order } else { node.async = true; node.src = url; head.insertBefore(node, head.firstChild); } return node; }; function assetOnload(node, callback) { if (node.nodeName === 'SCRIPT') { scriptOnload(node, cb); } else { styleOnload(node, cb); } var timer = setTimeout(function() { cb(); util.error({ message: 'time is out', from: 'getAsset', type: 'warn' }); }, data.config.timeout); function cb() { cb.isCalled = true; callback(); clearTimeout(timer); } } function scriptOnload(node, callback) { if (node.addEventListener) { node.addEventListener('load', callback, false); node.addEventListener('error', callback, false); // NOTICE: Nothing will happen in Opera when the file status is 404. In // this case, the callback will be called when time is out. } else { // for IE6-8 node.attachEvent('onreadystatechange', function() { var rs = node.readyState; if (rs === 'loaded' || rs === 'complete') { callback(); } }); } } function styleOnload(node, callback) { // for IE6-9 and Opera if (node.attachEvent) { node.attachEvent('onload', callback); // NOTICE: // 1. "onload" will be fired in IE6-9 when the file is 404, but in // this situation, Opera does nothing, so fallback to timeout. // 2. "onerror" doesn't fire in any browsers! } // polling for Firefox, Chrome, Safari else { setTimeout(function() { poll(node, callback); }, 0); // for cache } } function poll(node, callback) { if (callback.isCalled) { return; } var isLoaded = false; if (isWebKit) { if (node['sheet']) { isLoaded = true; } } // for Firefox else if (node['sheet']) { try { if (node['sheet'].cssRules) { isLoaded = true; } } catch (ex) { if (ex.name === 'NS_ERROR_DOM_SECURITY_ERR') { isLoaded = true; } } } if (isLoaded) { // give time to render. setTimeout(function() { callback(); }, 1); } else { setTimeout(function() { poll(node, callback); }, 1); } } util.assetOnload = assetOnload; var interactiveScript = null; util.getInteractiveScript = function() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } var scripts = head.getElementsByTagName('script'); for (var i = 0; i < scripts.length; i++) { var script = scripts[i]; if (script.readyState === 'interactive') { interactiveScript = script; return script; } } return null; }; util.getScriptAbsoluteSrc = function(node) { return node.hasAttribute ? // non-IE6/7 node.src : // see http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx node.getAttribute('src', 4); }; var noCacheTimeStamp = 'seajs-ts=' + util.now(); util.addNoCacheTimeStamp = function(url) { return url + (url.indexOf('?') === -1 ? '?' : '&') + noCacheTimeStamp; }; util.removeNoCacheTimeStamp = function(url) { var ret = url; if (url.indexOf(noCacheTimeStamp) !== -1) { ret = url.replace(noCacheTimeStamp, '').slice(0, -1); } return ret; }; })(seajs._util, seajs._data); /** * references: * - http://lifesinger.org/lab/2011/load-js-css/ * - ./test/issues/load-css/test.html */ /** * @fileoverview Loads a module and gets it ready to be require()d. */ (function(util, data, fn, global) { /** * Modules that are being downloaded. * { uri: scriptNode, ... } */ var fetchingMods = {}; var memoizedMods = data.memoizedMods; /** * Loads modules to the environment. * @param {Array.<string>} ids An array composed of module id. * @param {function(*)=} callback The callback function. * @param {string=} refUrl The referenced uri for relative id. */ fn.load = function(ids, callback, refUrl) { if (util.isString(ids)) { ids = [ids]; } var uris = util.ids2Uris(ids, refUrl); provide(uris, function() { var require = fn.createRequire({ uri: refUrl }); var args = util.map(uris, function(uri) { return require(uri); }); if (callback) { callback.apply(global, args); } }); }; /** * Provides modules to the environment. * @param {Array.<string>} uris An array composed of module uri. * @param {function()=} callback The callback function. */ function provide(uris, callback) { var unReadyUris = util.getUnReadyUris(uris); if (unReadyUris.length === 0) { return onProvide(); } for (var i = 0, n = unReadyUris.length, remain = n; i < n; i++) { (function(uri) { if (memoizedMods[uri]) { onLoad(); } else { fetch(uri, onLoad); } function onLoad() { var deps = (memoizedMods[uri] || 0).dependencies || []; var m = deps.length; if (m) { // if a -> [b -> [c -> [a, e], d]] // when use(['a', 'b']) // should remove a from c.deps deps = util.removeCyclicWaitingUris(uri, deps); m = deps.length; } if (m) { remain += m; provide(deps, function() { remain -= m; if (remain === 0) onProvide(); }); } if (--remain === 0) onProvide(); } })(unReadyUris[i]); } function onProvide() { util.setReadyState(unReadyUris); callback(); } } /** * Fetches a module file. * @param {string} uri The module uri. * @param {function()} callback The callback function. */ function fetch(uri, callback) { if (fetchingMods[uri]) { util.assetOnload(fetchingMods[uri], cb); } else { // See fn-define.js: "uri = data.pendingModIE" data.pendingModIE = uri; fetchingMods[uri] = util.getAsset( getUrl(uri), cb, data.config.charset ); data.pendingModIE = null; } function cb() { if (data.pendingMods) { util.forEach(data.pendingMods, function(pendingMod) { util.memoize(pendingMod.id, uri, pendingMod); }); data.pendingMods = []; } if (fetchingMods[uri]) { delete fetchingMods[uri]; } if (!memoizedMods[uri]) { util.error({ message: 'can not memoized', from: 'load', uri: uri, type: 'warn' }); } if (callback) { callback(); } } } function getUrl(uri) { var url = uri; // When debug is 2, a unique timestamp will be added to each URL. // This can be useful during testing to prevent the browser from // using a cached version of the file. if (data.config.debug == 2) { url = util.addNoCacheTimeStamp(url); } return url; } })(seajs._util, seajs._data, seajs._fn, this); /** * @fileoverview Module Constructor. */ (function(fn) { /** * Module constructor. * @constructor * @param {string=} id The module id. * @param {Array.<string>|string=} deps The module dependencies. * @param {function()|Object} factory The module factory function. */ fn.Module = function(id, deps, factory) { this.id = id; this.dependencies = deps || []; this.factory = factory; }; })(seajs._fn); /** * @fileoverview Module authoring format. */ (function(util, data, fn) { /** * Defines a module. * @param {string=} id The module id. * @param {Array.<string>|string=} deps The module dependencies. * @param {function()|Object} factory The module factory function. */ fn.define = function(id, deps, factory) { // define(factory) if (arguments.length === 1) { factory = id; if (util.isFunction(factory)) { deps = parseDependencies(factory.toString()); } id = ''; } // define([], factory) else if (util.isArray(id)) { factory = deps; deps = id; id = ''; } var mod = new fn.Module(id, deps, factory); var url; if (document.attachEvent && !window.opera) { // For IE6-9 browsers, the script onload event may not fire right // after the the script is evaluated. Kris Zyp found that it // could query the script nodes and the one that is in "interactive" // mode indicates the current script. Ref: http://goo.gl/JHfFW var script = util.getInteractiveScript(); if (script) { url = util.getScriptAbsoluteSrc(script); // remove no cache timestamp if (data.config.debug == 2) { url = util.removeNoCacheTimeStamp(url); } } // In IE6-9, if the script is in the cache, the "interactive" mode // sometimes does not work. The script code actually executes *during* // the DOM insertion of the script tag, so we can keep track of which // script is being requested in case define() is called during the DOM // insertion. else { url = data.pendingModIE; } // NOTE: If the id-deriving methods above is failed, then falls back // to use onload event to get the module uri. } if (url) { util.memoize(id, url, mod); } else { // Saves information for "real" work in the onload event. data.pendingMods.push(mod); } }; function parseDependencies(code) { // Parse these `requires`: // var a = require('a'); // someMethod(require('b')); // require('c'); // ... // Doesn't parse: // someInstance.require(...); var pattern = /[^.]\brequire\s*\(\s*['"]?([^'")]*)/g; var ret = [], match; code = removeComments(code); while ((match = pattern.exec(code))) { if (match[1]) { ret.push(match[1]); } } return ret; } // http://lifesinger.org/lab/2011/remove-comments-safely/ function removeComments(code) { return code .replace(/(?:^|\n|\r)\s*\/\*[\s\S]*?\*\/\s*(?:\r|\n|$)/g, '\n') .replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '\n'); } })(seajs._util, seajs._data, seajs._fn); /** * @fileoverview The factory for "require". */ (function(util, data, fn) { /** * The factory of "require" function. * @param {Object} sandbox The data related to "require" instance. */ function createRequire(sandbox) { // sandbox: { // uri: '', // deps: [], // parent: sandbox // } function require(id) { var uri = util.id2Uri(id, sandbox.uri); var mod = data.memoizedMods[uri]; // Just return null when: // 1. the module file is 404. // 2. the module file is not written with valid module format. // 3. other error cases. if (!mod) { return null; } // Checks cyclic dependencies. if (isCyclic(sandbox, uri)) { util.error({ message: 'found cyclic dependencies', from: 'require', uri: uri, type: 'warn' }); return mod.exports; } // Initializes module exports. if (!mod.exports) { initExports(mod, { uri: uri, deps: mod.dependencies, parent: sandbox }); } return mod.exports; } require.async = function(ids, callback) { fn.load(ids, callback, sandbox.uri); }; return require; } function initExports(mod, sandbox) { var ret; var factory = mod.factory; // Attaches members to module instance. //mod.dependencies mod.id = sandbox.uri; mod.exports = {}; delete mod.factory; // free delete mod.ready; // free if (util.isFunction(factory)) { checkPotentialErrors(factory, mod.uri); ret = factory(createRequire(sandbox), mod.exports, mod); if (ret !== undefined) { mod.exports = ret; } } else if (factory !== undefined) { mod.exports = factory; } } function isCyclic(sandbox, uri) { if (sandbox.uri === uri) { return true; } if (sandbox.parent) { return isCyclic(sandbox.parent, uri); } return false; } function checkPotentialErrors(factory, uri) { if (factory.toString().search(/\sexports\s*=\s*[^=]/) !== -1) { util.error({ message: 'found invalid setter: exports = {...}', from: 'require', uri: uri, type: 'error' }); } } fn.createRequire = createRequire; })(seajs._util, seajs._data, seajs._fn); /** * @fileoverview The configuration. */ (function(util, data, fn, global) { var config = data.config; // Async inserted script. var loaderScript = document.getElementById('seajsnode'); // Static script. if (!loaderScript) { var scripts = document.getElementsByTagName('script'); loaderScript = scripts[scripts.length - 1]; } var loaderSrc = util.getScriptAbsoluteSrc(loaderScript), loaderDir; if (loaderSrc) { var base = loaderDir = util.dirname(loaderSrc); // When src is "http://test.com/libs/seajs/1.0.0/sea.js", redirect base // to "http://test.com/libs/" var match = base.match(/^(.+\/)seajs\/[\d\.]+\/$/); if (match) { base = match[1]; } config.base = base; } // When script is inline code, src is empty. config.main = loaderScript.getAttribute('data-main') || ''; // The max time to load a script file. config.timeout = 20000; // seajs-debug if (loaderDir && (global.location.search.indexOf('seajs-debug') !== -1 || document.cookie.indexOf('seajs=1') !== -1)) { config.debug = true; data.preloadMods.push(loaderDir + 'plugin-map'); } /** * The function to configure the framework. * config({ * 'base': 'path/to/base', * 'alias': { * 'app': 'biz/xx', * 'jquery': 'jquery-1.5.2', * 'cart': 'cart?t=20110419' * }, * 'map': [ * ['test.cdn.cn', 'localhost'] * ], * charset: 'utf-8', * timeout: 20000, // 20s * debug: false, * main: './init' * }); * * @param {Object} o The config object. */ fn.config = function(o) { for (var k in o) { var sub = config[k]; if (typeof sub === 'object') { mix(sub, o[k]); } else { config[k] = o[k]; } } // Make sure config.base is absolute path. var base = config.base; if (base.indexOf('://') === -1) { config.base = util.id2Uri(base + '#'); } return this; }; function mix(r, s) { for (var k in s) { r[k] = s[k]; } } })(seajs._util, seajs._data, seajs._fn, this); /** * @fileoverview The bootstrap and entrances. */ (function(host, data, fn) { var config = data.config; var preloadMods = data.preloadMods; /** * Loads modules to the environment. * @param {Array.<string>} ids An array composed of module id. * @param {function(*)=} callback The callback function. */ fn.use = function(ids, callback) { var mod = preloadMods[0]; if (mod) { // Loads preloadMods one by one, because the preloadMods // may be dynamically changed. fn.load(mod, function() { if (preloadMods[0] === mod) { preloadMods.shift(); } fn.use(ids, callback); }); } else { fn.load(ids, callback); } }; // main var mainModuleId = config.main; if (mainModuleId) { fn.use([mainModuleId]); } // Parses the pre-call of seajs.config/seajs.use/define. // Ref: test/bootstrap/async-3.html (function(args) { if (args) { var hash = { 0: 'config', 1: 'use', 2: 'define' }; for (var i = 0; i < args.length; i += 2) { fn[hash[args[i]]].apply(host, args[i + 1]); } delete host._seajs; } })((host._seajs || 0)['args']); })(seajs, seajs._data, seajs._fn); /** * @fileoverview The public api of seajs. */ (function(host, data, fn, global) { // SeaJS Loader API: host.config = fn.config; host.use = fn.use; // Module Authoring API: var previousDefine = global.define; global.define = fn.define; // For custom loader name. host.noConflict = function(all) { global.seajs = host._seajs; if (all) { global.define = previousDefine; host.define = fn.define; } return host; }; // Keeps clean! if (!data.config.debug) { delete host._util; delete host._data; delete host._fn; delete host._seajs; } })(seajs, seajs._data, seajs._fn, this);
JavaScript
/** * @fileoverview The map plugin for auto responder. */ define(function() { var config = getConfig(); var loc = this.location; // Force debug to true when load via ?seajs-debug. if (loc.search.indexOf('seajs-debug') !== -1) { config.debug = 1; config.console = 1; saveConfig(config); } // Load the map file if (config.map) { document.title = '[debug] - ' + document.title; seajs._data.preloadMods.push(config.map); } // Display console if (config.console) { displayConsole(config.map); } function displayConsole(mapfile) { var style = '#seajs-debug-console { ' + ' position: fixed; bottom: 10px; right: 10px; z-index: 999999999;' + ' background: #fff; color: #000; font: 12px arial;' + ' border: 2px solid #000; padding: 0 10px 10px;' + '}' + '#seajs-debug-console h3 {' + ' margin: 3px 0 6px -6px; padding: 0;' + ' font-weight: bold; font-size: 14px;' + '}' + '#seajs-debug-console input {' + ' width: 300px; margin-left: 10px;' + '}' + '#seajs-debug-console button {' + ' float: right; margin: 6px 0 0 10px;' + ' padding: 2px 10px;' + ' color: #211922; background: #f9f9f9;' + ' background-image: -webkit-linear-gradient(top, #fefeff, #efefef);' + ' background-image: -moz-linear-gradient(top, #fefeff, #efefef);' + ' text-shadow: 0 1px #eaeaea;' + ' border: 1px solid #bbb;' + ' border-radius: 3px;' + ' cursor: pointer; opacity: .8' + '}' + '#seajs-debug-console button:hover {' + ' background: #e8e8e8; text-shadow: none; opacity: 1' + '}' + '#seajs-debug-console a {' + ' position: relative; top: 10px; text-decoration: none;' + '}'; var html = '<style>' + style + '</style>' + '<div id="seajs-debug-console">' + ' <h3>SeaJS Debug Console</h3>' + ' <label>Map file: <input value="' + mapfile + '"/></label><br/>' + ' <button>Exit</button>' + ' <button>Hide</button>' + ' <button>Refresh</button>' + ' <a href="http://seajs.com/docs/appendix-map-plugin.html"' + ' target="_blank">help</a>' + '</div>'; var div = document.createElement('div'); div.innerHTML = html; document.body.appendChild(div); var buttons = div.getElementsByTagName('button'); // hide buttons[1].onclick = function() { config.console = 0; saveConfig(config); loc.replace(loc.href.replace(/(?:\?|&)seajs-debug/, '')); }; // refresh buttons[2].onclick = function() { var link = div.getElementsByTagName('input')[0].value; if (link.indexOf('://') === -1) { link = 'http://' + link; } config.map = link; saveConfig(config); loc.reload(); }; // exit debug mode buttons[0].onclick = function() { config.debug = 0; saveConfig(config); loc.replace(loc.href.replace(/(?:\?|&)seajs-debug/, '')); }; } function getConfig() { var cookie = '', m; if ((m = document.cookie.match( /(?:^| )seajs(?:(?:=([^;]*))|;|$)/))) { cookie = m[1] ? decodeURIComponent(m[1]) : ''; } var parts = cookie.split('`'); return { debug: Number(parts[0]) || 0, map: parts[1] || '', console: Number(parts[2]) || 0 }; } function saveConfig(o) { var date = new Date(); date.setTime(date.getTime() + 30 * 86400000); // 30 days document.cookie = 'seajs=' + o.debug + '`' + o.map + '`' + o.console + '; expires=' + date.toUTCString(); } });
JavaScript
var qTipTag = "a,label,input"; //Which tag do you want to qTip-ize? Keep it lowercase!// var qTipX = 0; //This is qTip's X offset// var qTipY = 15; //This is qTip's Y offset// //There's No need to edit anything below this line// tooltip = { name : "qTip", offsetX : qTipX, offsetY : qTipY, tip : null } tooltip.init = function () { var tipNameSpaceURI = "http://www.w3.org/1999/xhtml"; if(!tipContainerID){ var tipContainerID = "qTip";} var tipContainer = document.getElementById(tipContainerID); if(!tipContainer) { tipContainer = document.createElementNS ? document.createElementNS(tipNameSpaceURI, "div") : document.createElement("div"); tipContainer.setAttribute("id", tipContainerID); document.getElementsByTagName("body").item(0).appendChild(tipContainer); } if (!document.getElementById) return; this.tip = document.getElementById (this.name); if (this.tip) document.onmousemove = function (evt) {tooltip.move (evt)}; var a, sTitle, elements; var elementList = qTipTag.split(","); for(var j = 0; j < elementList.length; j++) { elements = document.getElementsByTagName(elementList[j]); if(elements) { for (var i = 0; i < elements.length; i ++) { a = elements[i]; sTitle = a.getAttribute("title"); if(sTitle) { a.setAttribute("tiptitle", sTitle); a.removeAttribute("title"); a.removeAttribute("alt"); a.onmouseover = function() {tooltip.show(this.getAttribute('tiptitle'))}; a.onmouseout = function() {tooltip.hide()}; } } } } } tooltip.move = function (evt) { var x=0, y=0; if (document.all) {//IE x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft; y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop; x += window.event.clientX; y += window.event.clientY; } else {//Good Browsers x = evt.pageX; y = evt.pageY; } this.tip.style.left = (x + this.offsetX) + "px"; this.tip.style.top = (y + this.offsetY) + "px"; } tooltip.show = function (text) { if (!this.tip) return; this.tip.innerHTML = text; this.tip.style.display = "block"; } tooltip.hide = function () { if (!this.tip) return; this.tip.innerHTML = ""; this.tip.style.display = "none"; } window.onload = function () { tooltip.init (); }
JavaScript
// Copyright 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Javascript code for the interactive AJAX shell. * * Part of http://code.google.com/p/google-app-engine-samples/. * * Includes a function (shell.runStatement) that sends the current python * statement in the shell prompt text box to the server, and a callback * (shell.done) that displays the results when the XmlHttpRequest returns. * * Also includes cross-browser code (shell.getXmlHttpRequest) to get an * XmlHttpRequest. */ /** * Shell namespace. * @type {Object} */ var shell = {} /** * The shell history. history is an array of strings, ordered oldest to * newest. historyCursor is the current history element that the user is on. * * The last history element is the statement that the user is currently * typing. When a statement is run, it's frozen in the history, a new history * element is added to the end of the array for the new statement, and * historyCursor is updated to point to the new element. * * @type {Array} */ shell.history = ['']; /** * See {shell.history} * @type {number} */ shell.historyCursor = 0; /** * A constant for the XmlHttpRequest 'done' state. * @type Number */ shell.DONE_STATE = 4; /** * A cross-browser function to get an XmlHttpRequest object. * * @return {XmlHttpRequest?} a new XmlHttpRequest */ shell.getXmlHttpRequest = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) { return new ActiveXObject('Microsoft.XMLHTTP'); } } return null; }; /** * This is the prompt textarea's onkeypress handler. Depending on the key that * was pressed, it will run the statement, navigate the history, or update the * current statement in the history. * * @param {Event} event the keypress event * @return {Boolean} false to tell the browser not to submit the form. */ shell.onPromptKeyPress = function(event) { var statement = document.getElementById('statement'); if (this.historyCursor == this.history.length - 1) { // we're on the current statement. update it in the history before doing // anything. this.history[this.historyCursor] = statement.value; } // should we pull something from the history? if (event.ctrlKey && event.keyCode == 38 /* up arrow */) { if (this.historyCursor > 0) { statement.value = this.history[--this.historyCursor]; } return false; } else if (event.ctrlKey && event.keyCode == 40 /* down arrow */) { if (this.historyCursor < this.history.length - 1) { statement.value = this.history[++this.historyCursor]; } return false; } else if (!event.altKey) { // probably changing the statement. update it in the history. this.historyCursor = this.history.length - 1; this.history[this.historyCursor] = statement.value; } // should we submit? if (event.keyCode == 13 /* enter */ && !event.altKey && !event.shiftKey) { return this.runStatement(); } }; /** * The XmlHttpRequest callback. If the request succeeds, it adds the command * and its resulting output to the shell history div. * * @param {XmlHttpRequest} req the XmlHttpRequest we used to send the current * statement to the server */ shell.done = function(req) { if (req.readyState == this.DONE_STATE) { var statement = document.getElementById('statement') statement.className = 'prompt'; // add the command to the shell output var output = document.getElementById('output'); output.value += '\n>>> ' + statement.value; statement.value = ''; // add a new history element this.history.push(''); this.historyCursor = this.history.length - 1; // add the command's result var result = req.responseText.replace(/^\s*|\s*$/g, ''); // trim whitespace if (result != '') output.value += '\n' + result; // scroll to the bottom output.scrollTop = output.scrollHeight; if (output.createTextRange) { var range = output.createTextRange(); range.collapse(false); range.select(); } } }; /** * This is the form's onsubmit handler. It sends the python statement to the * server, and registers shell.done() as the callback to run when it returns. * * @return {Boolean} false to tell the browser not to submit the form. */ shell.runStatement = function() { var form = document.getElementById('form'); // build a XmlHttpRequest var req = this.getXmlHttpRequest(); if (!req) { document.getElementById('ajax-status').innerHTML = "<span class='error'>Your browser doesn't support AJAX. :(</span>"; return false; } req.onreadystatechange = function() { shell.done(req); }; // build the query parameter string var params = ''; for (i = 0; i < form.elements.length; i++) { var elem = form.elements[i]; if (elem.type != 'submit' && elem.type != 'button' && elem.id != 'caret') { var value = escape(elem.value).replace(/\+/g, '%2B'); // escape ignores + params += '&' + elem.name + '=' + value; } } // send the request and tell the user. document.getElementById('statement').className = 'prompt processing'; req.open(form.method, form.action + '?' + params, true); req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); req.send(null); return false; };
JavaScript
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08 ** ** Code licensed under Creative Commons Attribution-ShareAlike License ** ** http://creativecommons.org/licenses/by-sa/2.0/ **/ function XHConn() { var xmlhttp, bComplete = false; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }}} if (!xmlhttp) return null; this.connect = function(sURL, sMethod, sVars, fnDone) { if (!xmlhttp) return false; bComplete = false; sMethod = sMethod.toUpperCase(); try { if (sMethod == "GET") { xmlhttp.open(sMethod, sURL+"?"+sVars, true); sVars = ""; } else { xmlhttp.open(sMethod, sURL, true); xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1"); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && !bComplete) { bComplete = true; fnDone(xmlhttp); }}; xmlhttp.send(sVars); } catch(z) { return false; } return true; }; return this; }
JavaScript
/** * @author Ralph Voigt (info -at- drakedata.com) * @version 1.1 * @date 29.01.2010 * * @name serializeTree * @type jQuery * @homepage http://plugins.jquery.com/project/serializeTree/ * @desc Recursive function to serialize ordered or unordered lists of arbitrary depth and complexity. The resulting array will keep the order of the tree and is suitable to be posted away. * @example $("#myltree").serializeTree("id","myArray",".elementsToExclude") * @param String attribute The attribute of the li-elements to be serialised * @param String levelString The Array to store data in * @param String exclude li-Elements to exclude from being serialised (optional) * @return String The array to be sent to the server via post * Boolean false if the passed variable is not a list or empty * @cat Plugin */ (function( $ ){ jQuery.fn.serializeTree = function (attribute, levelString, exclude) { var dataString = ''; var elems; if (exclude==undefined) elems = this.children(); else elems = this.children().not(exclude); if( elems.length > 0) { elems.each(function() { var curLi = $(this); var toAdd = ''; if( curLi.find('ul').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ul:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else if( curLi.find('ol').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ol:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else { dataString += '&'+levelString+'[]='+curLi.attr(attribute); } if(toAdd) dataString += toAdd; }); } else { dataString += '&'+levelString+'['+this.attr(attribute)+']='; } if(dataString) return dataString; else return false; }; })( jQuery );
JavaScript
/** * @author Ralph Voigt (info -at- drakedata.com) * @version 1.1 * @date 29.01.2010 * * @name serializeTree * @type jQuery * @homepage http://plugins.jquery.com/project/serializeTree/ * @desc Recursive function to serialize ordered or unordered lists of arbitrary depth and complexity. The resulting array will keep the order of the tree and is suitable to be posted away. * @example $("#myltree").serializeTree("id","myArray",".elementsToExclude") * @param String attribute The attribute of the li-elements to be serialised * @param String levelString The Array to store data in * @param String exclude li-Elements to exclude from being serialised (optional) * @return String The array to be sent to the server via post * Boolean false if the passed variable is not a list or empty * @cat Plugin */ (function( $ ){ jQuery.fn.serializeTree = function (attribute, levelString, exclude) { var dataString = ''; var elems; if (exclude==undefined) elems = this.children(); else elems = this.children().not(exclude); if( elems.length > 0) { elems.each(function() { var curLi = $(this); var toAdd = ''; if( curLi.find('ul').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ul:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else if( curLi.find('ol').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ol:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else { dataString += '&'+levelString+'[]='+curLi.attr(attribute); } if(toAdd) dataString += toAdd; }); } else { dataString += '&'+levelString+'['+this.attr(attribute)+']='; } if(dataString) return dataString; else return false; }; })( jQuery );
JavaScript
/** * @author Ralph Voigt (info -at- drakedata.com) * @version 1.1 * @date 29.01.2010 * * @name serializeTree * @type jQuery * @homepage http://plugins.jquery.com/project/serializeTree/ * @desc Recursive function to serialize ordered or unordered lists of arbitrary depth and complexity. The resulting array will keep the order of the tree and is suitable to be posted away. * @example $("#myltree").serializeTree("id","myArray",".elementsToExclude") * @param String attribute The attribute of the li-elements to be serialised * @param String levelString The Array to store data in * @param String exclude li-Elements to exclude from being serialised (optional) * @return String The array to be sent to the server via post * Boolean false if the passed variable is not a list or empty * @cat Plugin */ (function( $ ){ jQuery.fn.serializeTree = function (attribute, levelString, exclude) { var dataString = ''; var elems; if (exclude==undefined) elems = this.children(); else elems = this.children().not(exclude); if( elems.length > 0) { elems.each(function() { var curLi = $(this); var toAdd = ''; if( curLi.find('ul').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ul:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else if( curLi.find('ol').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ol:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else { //dataString += '&'+levelString+'[]='+curLi.attr(attribute); dataString += '&'+levelString+'='+curLi.attr(attribute); } if(toAdd) dataString += toAdd; }); } else { dataString += '&'+levelString+'['+this.attr(attribute)+']='; } if(dataString) return dataString; else return false; }; })( jQuery );
JavaScript
/** * @author Ralph Voigt (info -at- drakedata.com) * @version 1.1 * @date 29.01.2010 * * @name serializeTree * @type jQuery * @homepage http://plugins.jquery.com/project/serializeTree/ * @desc Recursive function to serialize ordered or unordered lists of arbitrary depth and complexity. The resulting array will keep the order of the tree and is suitable to be posted away. * @example $("#myltree").serializeTree("id","myArray",".elementsToExclude") * @param String attribute The attribute of the li-elements to be serialised * @param String levelString The Array to store data in * @param String exclude li-Elements to exclude from being serialised (optional) * @return String The array to be sent to the server via post * Boolean false if the passed variable is not a list or empty * @cat Plugin */ (function( $ ){ jQuery.fn.serializeTree = function (attribute, levelString, exclude) { var dataString = ''; var elems; if (exclude==undefined) elems = this.children(); else elems = this.children().not(exclude); if( elems.length > 0) { elems.each(function() { var curLi = $(this); var toAdd = ''; if( curLi.find('ul').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ul:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else if( curLi.find('ol').length > 0) { levelString += '['+curLi.attr(attribute)+']'; toAdd = $('ol:first', curLi).serializeTree(attribute, levelString, exclude); levelString = levelString.replace(/\[[^\]\[]*\]$/, ''); } else { //dataString += '&'+levelString+'[]='+curLi.attr(attribute); dataString += '&'+levelString+'='+curLi.attr(attribute); } if(toAdd) dataString += toAdd; }); } else { dataString += '&'+levelString+'['+this.attr(attribute)+']='; } if(dataString) return dataString; else return false; }; })( jQuery );
JavaScript
/** * @preserve jquery.layout 1.3.0 - Release Candidate 29.15 * $Date: 2011-06-25 08:00:00 (Sat, 25 Jun 2011) $ * $Rev: 302915 $ * * Copyright (c) 2010 * Fabrizio Balliano (http://www.fabrizioballiano.net) * Kevin Dalman (http://allpro.net) * * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html) * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses. * * Changelog: http://layout.jquery-dev.net/changelog.cfm#1.3.0.rc29.15 * * Docs: http://layout.jquery-dev.net/documentation.html * Tips: http://layout.jquery-dev.net/tips.html * Help: http://groups.google.com/group/jquery-ui-layout */ // NOTE: For best readability, view with a fixed-width font and tabs equal to 4-chars ;(function ($) { /* * GENERIC $.layout METHODS - used by all layouts */ $.layout = { version: "1.3.rc29.15" , revision: 0.032915 // 1.3.0 final = 1.0300 - major(n+).minor(nn)+patch(nn+) // LANGUAGE CUSTOMIZATION , language: { // Tips and messages for resizers, togglers, custom buttons, etc. Open: "Open" // eg: "Open Pane" , Close: "Close" , Resize: "Resize" , Slide: "Slide Open" , Pin: "Pin" , Unpin: "Un-Pin" , noRoomToOpenTip: "Not enough room to show this pane." // Developer error messages , pane: "pane" // description of "layout pane element" , selector: "selector" // description of "jQuery-selector" , errButton: "Error Adding Button \n\nInvalid " , errContainerMissing: "UI Layout Initialization Error\n\nThe specified layout-container does not exist." , errCenterPaneMissing: "UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element." , errContainerHeight: "UI Layout Initialization Warning\n\nThe layout-container \"CONTAINER\" has no height.\n\nTherefore the layout is 0-height and hence 'invisible'!" } // can update code here if $.browser is phased out , browser: { mozilla: !!$.browser.mozilla , webkit: !!$.browser.webkit || !!$.browser.safari // webkit = jQ 1.4 , msie: !!$.browser.msie , isIE6: !!$.browser.msie && $.browser.version == 6 , boxModel: false // page must load first, so will be updated set by _create //, version: $.browser.version - not used } /* * GENERIC UTILITY METHODS */ // calculate and return the scrollbar width, as an integer , scrollbarWidth: function () { return window.scrollbarWidth || $.layout.getScrollbarSize('width'); } , scrollbarHeight: function () { return window.scrollbarHeight || $.layout.getScrollbarSize('height'); } , getScrollbarSize: function (dim) { var $c = $('<div style="position: absolute; top: -10000px; left: -10000px; width: 100px; height: 100px; overflow: scroll;"></div>').appendTo("body"); var d = { width: $c.width() - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight }; $c.remove(); window.scrollbarWidth = d.width; window.scrollbarHeight = d.height; return dim.match(/^(width|height)$/i) ? d[dim] : d; } /** * Returns hash container 'display' and 'visibility' * * @see $.swap() - swaps CSS, runs callback, resets CSS */ , showInvisibly: function ($E, force) { if (!$E) return {}; if (!$E.jquery) $E = $($E); var CSS = { display: $E.css('display') , visibility: $E.css('visibility') }; if (force || CSS.display == "none") { // only if not *already hidden* $E.css({ display: "block", visibility: "hidden" }); // show element 'invisibly' so can be measured return CSS; } else return {}; } /** * Returns data for setting size of an element (container or a pane). * * @see _create(), onWindowResize() for container, plus others for pane * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc */ , getElementDimensions: function ($E) { var d = {} // dimensions hash , x = d.css = {} // CSS hash , i = {} // TEMP insets , b, p // TEMP border, padding , N = $.layout.cssNum , off = $E.offset() ; d.offsetLeft = off.left; d.offsetTop = off.top; $.each("Left,Right,Top,Bottom".split(","), function (idx, e) { // e = edge b = x["border" + e] = $.layout.borderWidth($E, e); p = x["padding"+ e] = $.layout.cssNum($E, "padding"+e); i[e] = b + p; // total offset of content from outer side d["inset"+ e] = p; }); d.offsetWidth = $E.innerWidth(); d.offsetHeight = $E.innerHeight(); d.outerWidth = $E.outerWidth(); d.outerHeight = $E.outerHeight(); d.innerWidth = Math.max(0, d.outerWidth - i.Left - i.Right); d.innerHeight = Math.max(0, d.outerHeight - i.Top - i.Bottom); x.width = $E.width(); x.height = $E.height(); x.top = N($E,"top",true); x.bottom = N($E,"bottom",true); x.left = N($E,"left",true); x.right = N($E,"right",true); //d.visible = $E.is(":visible");// && x.width > 0 && x.height > 0; return d; } , getElementCSS: function ($E, list) { var CSS = {} , style = $E[0].style , props = list.split(",") , sides = "Top,Bottom,Left,Right".split(",") , attrs = "Color,Style,Width".split(",") , p, s, a, i, j, k ; for (i=0; i < props.length; i++) { p = props[i]; if (p.match(/(border|padding|margin)$/)) for (j=0; j < 4; j++) { s = sides[j]; if (p == "border") for (k=0; k < 3; k++) { a = attrs[k]; CSS[p+s+a] = style[p+s+a]; } else CSS[p+s] = style[p+s]; } else CSS[p] = style[p]; }; return CSS } /** * Contains logic to check boxModel & browser, and return the correct width/height for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {number=} outerWidth/outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerWidth/Height of the elem by subtracting padding and borders */ , cssWidth: function ($E, outerWidth) { var b = $.layout.borderWidth , n = $.layout.cssNum ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerWidth <= 0) return 0; if (!$.layout.browser.boxModel) return outerWidth; // strip border and padding from outerWidth to get CSS Width var W = outerWidth - b($E, "Left") - b($E, "Right") - n($E, "paddingLeft") - n($E, "paddingRight") ; return Math.max(0,W); } , cssHeight: function ($E, outerHeight) { var b = $.layout.borderWidth , n = $.layout.cssNum ; // a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed if (outerHeight <= 0) return 0; if (!$.layout.browser.boxModel) return outerHeight; // strip border and padding from outerHeight to get CSS Height var H = outerHeight - b($E, "Top") - b($E, "Bottom") - n($E, "paddingTop") - n($E, "paddingBottom") ; return Math.max(0,H); } /** * Returns the 'current CSS numeric value' for a CSS property - 0 if property does not exist * * @see Called by many methods * @param {Array.<Object>} $E Must pass a jQuery object - first element is processed * @param {string} prop The name of the CSS property, eg: top, width, etc. * @param {boolean=} allowAuto true = return 'auto' if that is value; false = return 0 * @return {(string|number)} Usually used to get an integer value for position (top, left) or size (height, width) */ , cssNum: function ($E, prop, allowAuto) { if (!$E.jquery) $E = $($E); var CSS = $.layout.showInvisibly($E) , p = $.curCSS($E[0], prop, true) , v = allowAuto && p=="auto" ? p : (parseInt(p, 10) || 0); $E.css( CSS ); // RESET return v; } , borderWidth: function (el, side) { if (el.jquery) el = el[0]; var b = "border"+ side.substr(0,1).toUpperCase() + side.substr(1); // left => Left return $.curCSS(el, b+"Style", true) == "none" ? 0 : (parseInt($.curCSS(el, b+"Width", true), 10) || 0); } /** * UTLITY for mouse tracking - FUTURE REFERENCE * * init: if (!window.mouse) { * window.mouse = { x: 0, y: 0 }; * $(document).mousemove( $.layout.trackMouse ); * } * * @param {Object} evt * , trackMouse: function (evt) { window.mouse = { x: evt.clientX, y: evt.clientY }; } */ /** * SUBROUTINE for preventPrematureSlideClose option * * @param {Object} evt * @param {Object=} el */ , isMouseOverElem: function (evt, el) { var $E = $(el || this) , d = $E.offset() , T = d.top , L = d.left , R = L + $E.outerWidth() , B = T + $E.outerHeight() , x = evt.pageX // evt.clientX ? , y = evt.pageY // evt.clientY ? ; // if X & Y are < 0, probably means is over an open SELECT return ($.layout.browser.msie && x < 0 && y < 0) || ((x >= L && x <= R) && (y >= T && y <= B)); } }; $.fn.layout = function (opts) { /* * ########################### * WIDGET CONFIG & OPTIONS * ########################### */ var // LANGUAGE - for tips & messages lang = $.layout.language // internal alias // DEFAULT OPTIONS - CHANGE IF DESIRED , options = { name: "" // Not required, but useful for buttons and used for the state-cookie , containerClass: "ui-layout-container" // layout-container element , scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark) , resizeWithWindow: true // bind thisLayout.resizeAll() to the window.resize event , resizeWithWindowDelay: 200 // delay calling resizeAll because makes window resizing very jerky , resizeWithWindowMaxDelay: 0 // 0 = none - force resize every XX ms while window is being resized , onresizeall_start: null // CALLBACK when resizeAll() STARTS - NOT pane-specific , onresizeall_end: null // CALLBACK when resizeAll() ENDS - NOT pane-specific , onload_start: null // CALLBACK when Layout inits - after options initialized, but before elements , onload_end: null // CALLBACK when Layout inits - after EVERYTHING has been initialized , onunload_start: null // CALLBACK when Layout is destroyed OR onWindowUnload , onunload_end: null // CALLBACK when Layout is destroyed OR onWindowUnload , autoBindCustomButtons: false // search for buttons with ui-layout-button class and auto-bind them , zIndex: null // the PANE zIndex - resizers and masks will be +1 , initPanes: true // false = DO NOT initialize the panes onLoad - will init later , showErrorMessages: true // enables fatal error messages to warn developers of common errors // PANE SETTINGS , defaults: { // default options for 'all panes' - will be overridden by 'per-pane settings' applyDemoStyles: false // NOTE: renamed from applyDefaultStyles for clarity , closable: true // pane can open & close , resizable: true // when open, pane can be resized , slidable: true // when closed, pane can 'slide open' over other panes - closes on mouse-out , initClosed: false // true = init pane as 'closed' , initHidden: false // true = init pane as 'hidden' - no resizer-bar/spacing // SELECTORS //, paneSelector: "" // MUST be pane-specific - jQuery selector for pane , contentSelector: ".ui-layout-content" // INNER div/element to auto-size so only it scrolls, not the entire pane! , contentIgnoreSelector: ".ui-layout-ignore" // element(s) to 'ignore' when measuring 'content' , findNestedContent: false // true = $P.find(contentSelector), false = $P.children(contentSelector) // GENERIC ROOT-CLASSES - for auto-generated classNames , paneClass: "ui-layout-pane" // border-Pane - default: 'ui-layout-pane' , resizerClass: "ui-layout-resizer" // Resizer Bar - default: 'ui-layout-resizer' , togglerClass: "ui-layout-toggler" // Toggler Button - default: 'ui-layout-toggler' , buttonClass: "ui-layout-button" // CUSTOM Buttons - default: 'ui-layout-button-toggle/-open/-close/-pin' // ELEMENT SIZE & SPACING //, size: 100 // MUST be pane-specific -initial size of pane , minSize: 0 // when manually resizing a pane , maxSize: 0 // ditto, 0 = no limit , spacing_open: 6 // space between pane and adjacent panes - when pane is 'open' , spacing_closed: 6 // ditto - when pane is 'closed' , togglerLength_open: 50 // Length = WIDTH of toggler button on north/south sides - HEIGHT on east/west sides , togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden' , togglerAlign_open: "center" // top/left, bottom/right, center, OR... , togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right , togglerTip_open: lang.Close // Toggler tool-tip (title) , togglerTip_closed: lang.Open // ditto , togglerContent_open: "" // text or HTML to put INSIDE the toggler , togglerContent_closed: "" // ditto // RESIZING OPTIONS , resizerDblClickToggle: true // , autoResize: true // IF size is 'auto' or a percentage, then recalc 'pixel size' whenever the layout resizes , autoReopen: true // IF a pane was auto-closed due to noRoom, reopen it when there is room? False = leave it closed , resizerDragOpacity: 1 // option for ui.draggable //, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar , maskIframesOnResize: true // true = all iframes OR = iframe-selector(s) - adds masking-div during resizing/dragging , resizeNestedLayout: true // true = trigger nested.resizeAll() when a 'pane' of this layout is the 'container' for another , resizeWhileDragging: false // true = LIVE Resizing as resizer is dragged , resizeContentWhileDragging: false // true = re-measure header/footer heights as resizer is dragged // TIPS & MESSAGES - also see lang object , noRoomToOpenTip: lang.noRoomToOpenTip , resizerTip: lang.Resize // Resizer tool-tip (title) , sliderTip: lang.Slide // resizer-bar triggers 'sliding' when pane is closed , sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding' , slideTrigger_open: "click" // click, dblclick, mouseenter , slideTrigger_close: "mouseleave"// click, mouseleave , slideDelay_open: 300 // applies only for mouseenter event - 0 = instant open , slideDelay_close: 300 // applies only for mouseleave event (300ms is the minimum!) , hideTogglerOnSlide: false // when pane is slid-open, should the toggler show? , preventQuickSlideClose: $.layout.browser.webkit // Chrome triggers slideClosed as it is opening , preventPrematureSlideClose: false // HOT-KEYS & MISC , showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver , enableCursorHotkey: true // enabled 'cursor' hotkeys //, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character , customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT' // PANE ANIMATION // NOTE: fxSss_open & fxSss_close options (eg: fxName_open) are auto-generated if not passed , fxName: "slide" // ('none' or blank), slide, drop, scale , fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration , fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 } , fxOpacityFix: true // tries to fix opacity in IE to restore anti-aliasing after animation // CALLBACKS , triggerEventsOnLoad: false // true = trigger onopen OR onclose callbacks when layout initializes , triggerEventsWhileDragging: true // true = trigger onresize callback REPEATEDLY if resizeWhileDragging==true , onshow_start: null // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start , onshow_end: null // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end , onhide_start: null // CALLBACK when pane STARTS to Close - BEFORE onclose_start , onhide_end: null // CALLBACK when pane ENDS being Closed - AFTER onclose_end , onopen_start: null // CALLBACK when pane STARTS to Open , onopen_end: null // CALLBACK when pane ENDS being Opened , onclose_start: null // CALLBACK when pane STARTS to Close , onclose_end: null // CALLBACK when pane ENDS being Closed , onresize_start: null // CALLBACK when pane STARTS being Resized ***FOR ANY REASON*** , onresize_end: null // CALLBACK when pane ENDS being Resized ***FOR ANY REASON*** , onsizecontent_start: null // CALLBACK when sizing of content-element STARTS , onsizecontent_end: null // CALLBACK when sizing of content-element ENDS , onswap_start: null // CALLBACK when pane STARTS to Swap , onswap_end: null // CALLBACK when pane ENDS being Swapped , ondrag_start: null // CALLBACK when pane STARTS being ***MANUALLY*** Resized , ondrag_end: null // CALLBACK when pane ENDS being ***MANUALLY*** Resized } , north: { paneSelector: ".ui-layout-north" , size: "auto" // eg: "auto", "30%", 200 , resizerCursor: "n-resize" // custom = url(myCursor.cur) , customHotkey: "" // EITHER a charCode OR a character } , south: { paneSelector: ".ui-layout-south" , size: "auto" , resizerCursor: "s-resize" , customHotkey: "" } , east: { paneSelector: ".ui-layout-east" , size: 200 , resizerCursor: "e-resize" , customHotkey: "" } , west: { paneSelector: ".ui-layout-west" , size: 200 , resizerCursor: "w-resize" , customHotkey: "" } , center: { paneSelector: ".ui-layout-center" , minWidth: 0 , minHeight: 0 } // STATE MANAGMENT , useStateCookie: false // Enable cookie-based state-management - can fine-tune with cookie.autoLoad/autoSave , cookie: { name: "" // If not specified, will use Layout.name, else just "Layout" , autoSave: true // Save a state cookie when page exits? , autoLoad: true // Load the state cookie when Layout inits? // Cookie Options , domain: "" , path: "" , expires: "" // 'days' to keep cookie - leave blank for 'session cookie' , secure: false // List of options to save in the cookie - must be pane-specific , keys: "north.size,south.size,east.size,west.size,"+ "north.isClosed,south.isClosed,east.isClosed,west.isClosed,"+ "north.isHidden,south.isHidden,east.isHidden,west.isHidden" } } // PREDEFINED EFFECTS / DEFAULTS , effects = { // LIST *PREDEFINED EFFECTS* HERE, even if effect has no settings slide: { all: { duration: "fast" } // eg: duration: 1000, easing: "easeOutBounce" , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , drop: { all: { duration: "slow" } // eg: duration: 1000, easing: "easeOutQuint" , north: { direction: "up" } , south: { direction: "down" } , east: { direction: "right"} , west: { direction: "left" } } , scale: { all: { duration: "fast" } } } // DYNAMIC DATA - IS READ-ONLY EXTERNALLY! , state = { // generate unique ID to use for event.namespace so can unbind only events added by 'this layout' id: "layout"+ new Date().getTime() // code uses alias: sID , initialized: false , container: {} // init all keys , north: {} , south: {} , east: {} , west: {} , center: {} , cookie: {} // State Managment data storage } // INTERNAL CONFIG DATA - DO NOT CHANGE THIS! , _c = { allPanes: "north,south,west,east,center" , borderPanes: "north,south,west,east" , altSide: { north: "south" , south: "north" , east: "west" , west: "east" } // CSS used in multiple places , hidden: { visibility: "hidden" } , visible: { visibility: "visible" } // layout element settings , zIndex: { // set z-index values here pane_normal: 1 // normal z-index for panes , resizer_normal: 2 // normal z-index for resizer-bars , iframe_mask: 2 // overlay div used to mask pane(s) during resizing , pane_sliding: 100 // applied to *BOTH* the pane and its resizer when a pane is 'slid open' , pane_animate: 1000 // applied to the pane when being animated - not applied to the resizer , resizer_drag: 10000 // applied to the CLONED resizer-bar when being 'dragged' } , resizers: { cssReq: { position: "absolute" , padding: 0 , margin: 0 , fontSize: "1px" , textAlign: "left" // to counter-act "center" alignment! , overflow: "hidden" // prevent toggler-button from overflowing // SEE c.zIndex.resizer_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#DDD" , border: "none" } } , togglers: { cssReq: { position: "absolute" , display: "block" , padding: 0 , margin: 0 , overflow: "hidden" , textAlign: "center" , fontSize: "1px" , cursor: "pointer" , zIndex: 1 } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true background: "#AAA" } } , content: { cssReq: { position: "relative" /* contain floated or positioned elements */ } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true overflow: "auto" , padding: "10px" } , cssDemoPane: { // DEMO CSS - REMOVE scrolling from 'pane' when it has a content-div overflow: "hidden" , padding: 0 } } , panes: { // defaults for ALL panes - overridden by 'per-pane settings' below cssReq: { position: "absolute" , margin: 0 // SEE c.zIndex.pane_normal } , cssDemo: { // DEMO CSS - applied if: options.PANE.applyDemoStyles=true padding: "10px" , background: "#FFF" , border: "1px solid #BBB" , overflow: "auto" } } , north: { side: "Top" , sizeType: "Height" , dir: "horz" , cssReq: { top: 0 , bottom: "auto" , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } , pins: [] // array of 'pin buttons' to be auto-updated on open/close (classNames) } , south: { side: "Bottom" , sizeType: "Height" , dir: "horz" , cssReq: { top: "auto" , bottom: 0 , left: 0 , right: 0 , width: "auto" // height: DYNAMIC } , pins: [] } , east: { side: "Right" , sizeType: "Width" , dir: "vert" , cssReq: { left: "auto" , right: 0 , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } , pins: [] } , west: { side: "Left" , sizeType: "Width" , dir: "vert" , cssReq: { left: 0 , right: "auto" , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" // width: DYNAMIC } , pins: [] } , center: { dir: "center" , cssReq: { left: "auto" // DYNAMIC , right: "auto" // DYNAMIC , top: "auto" // DYNAMIC , bottom: "auto" // DYNAMIC , height: "auto" , width: "auto" } } } /* * ########################### * INTERNAL HELPER FUNCTIONS * ########################### */ /** * Manages all internal timers */ , timer = { data: {} , set: function (s, fn, ms) { timer.clear(s); timer.data[s] = setTimeout(fn, ms); } , clear: function (s) { var t=timer.data; if (t[s]) {clearTimeout(t[s]); delete t[s];} } } /** * Returns true if passed param is EITHER a simple string OR a 'string object' - otherwise returns false */ , isStr = function (o) { try { return typeof o == "string" || (typeof o == "object" && o.constructor.toString().match(/string/i) !== null); } catch (e) { return false; } } /** * Returns a simple string if passed EITHER a simple string OR a 'string object', * else returns the original object */ , str = function (o) { // trim converts 'String object' to a simple string return isStr(o) ? $.trim(o) : o == undefined || o == null ? "" : o; } /** * min / max * * Aliases for Math methods to simplify coding */ , min = function (x,y) { return Math.min(x,y); } , max = function (x,y) { return Math.max(x,y); } /** * Processes the options passed in and transforms them into the format used by layout() * Missing keys are added, and converts the data if passed in 'flat-format' (no sub-keys) * In flat-format, pane-specific-settings are prefixed like: north__optName (2-underscores) * To update effects, options MUST use nested-keys format, with an effects key ??? * * @see initOptions() * @param {Object} d Data/options passed by user - may be a single level or nested levels * @return {Object} Creates a data struture that perfectly matches 'options', ready to be imported */ , _transformData = function (d) { var a, json = { cookie:{}, defaults:{fxSettings:{}}, north:{fxSettings:{}}, south:{fxSettings:{}}, east:{fxSettings:{}}, west:{fxSettings:{}}, center:{fxSettings:{}} }; d = d || {}; if (d.effects || d.cookie || d.defaults || d.north || d.south || d.west || d.east || d.center) json = $.extend( true, json, d ); // already in json format - add to base keys else // convert 'flat' to 'nest-keys' format - also handles 'empty' user-options $.each( d, function (key,val) { a = key.split("__"); if (!a[1] || json[a[0]]) // check for invalid keys json[ a[1] ? a[0] : "defaults" ][ a[1] ? a[1] : a[0] ] = val; }); return json; } /** * Set an INTERNAL callback to avoid simultaneous animation * Runs only if needed and only if all callbacks are not 'already set' * Called by open() and close() when isLayoutBusy=true * * @param {string} action Either 'open' or 'close' * @param {string} pane A valid border-pane name, eg 'west' * @param {boolean=} param Extra param for callback (optional) */ , _queue = function (action, pane, param) { var tried = []; // if isLayoutBusy, then some pane must be 'moving' $.each(_c.borderPanes.split(","), function (i, p) { if (_c[p].isMoving) { bindCallback(p); // TRY to bind a callback return false; // BREAK } }); // if pane does NOT have a callback, then add one, else follow the callback chain... function bindCallback (p) { var c = _c[p]; if (!c.doCallback) { c.doCallback = true; c.callback = action +","+ pane +","+ (param ? 1 : 0); } else { // try to 'chain' this callback tried.push(p); var cbPane = c.callback.split(",")[1]; // 2nd param of callback is 'pane' // ensure callback target NOT 'itself' and NOT 'target pane' and NOT already tried (avoid loop) if (cbPane != pane && !$.inArray(cbPane, tried) >= 0) bindCallback(cbPane); // RECURSE } } } /** * RUN the INTERNAL callback for this pane - if one exists * * @param {string} pane A valid border-pane name, eg 'west' */ , _dequeue = function (pane) { var c = _c[pane]; // RESET flow-control flags _c.isLayoutBusy = false; delete c.isMoving; if (!c.doCallback || !c.callback) return; c.doCallback = false; // RESET logic flag // EXECUTE the callback var cb = c.callback.split(",") , param = (cb[2] > 0 ? true : false) ; if (cb[0] == "open") open( cb[1], param ); else if (cb[0] == "close") close( cb[1], param ); if (!c.doCallback) c.callback = null; // RESET - unless callback above enabled it again! } /** * Executes a Callback function after a trigger event, like resize, open or close * * @param {?string} pane This is passed only so we can pass the 'pane object' to the callback * @param {(string|function())} v_fn Accepts a function name, OR a comma-delimited array: [0]=function name, [1]=argument */ , _execCallback = function (pane, v_fn) { if (!v_fn) return; var fn; try { if (typeof v_fn == "function") fn = v_fn; else if (!isStr(v_fn)) return; else if (v_fn.match(/,/)) { // function name cannot contain a comma, so must be a function name AND a 'name' parameter var args = v_fn.split(","); fn = eval(args[0]); if (typeof fn=="function" && args.length > 1) return fn(args[1]); // pass the argument parsed from 'list' } else // just the name of an external function? fn = eval(v_fn); if (typeof fn=="function") { if (pane && $Ps[pane]) // pass data: pane-name, pane-element, pane-state, pane-options, and layout-name return fn( pane, $Ps[pane], state[pane], options[pane], options.name ); else // must be a layout/container callback - pass suitable info return fn( Instance, state, options, options.name ); } } catch (ex) {} } /** * cure iframe display issues in IE & other browsers */ , _fixIframe = function (pane) { if ($.layout.browser.mozilla) return; // skip FireFox - it auto-refreshes iframes onShow var $P = $Ps[pane]; // if the 'pane' is an iframe, do it if (state[pane].tagName == "IFRAME") $P.css(_c.hidden).css(_c.visible); else // ditto for any iframes INSIDE the pane $P.find('IFRAME').css(_c.hidden).css(_c.visible); } /** * cssW / cssH / cssSize / cssMinDims * * Contains logic to check boxModel & browser, and return the correct width/height for the current browser/doctype * * @see initPanes(), sizeMidPanes(), initHandles(), sizeHandles() * @param {(string|!Object)} el Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object * @param {number=} outerWidth (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerWidth of el by subtracting padding and borders */ , cssW = function (el, outerWidth) { var str = isStr(el) , $E = str ? $Ps[el] : $(el) ; if (!$E.length) return 0; if (isNaN(outerWidth)) // not specified outerWidth = str ? getPaneSize(el) : $E.outerWidth(); return $.layout.cssWidth($E, outerWidth); } /** * @param {(string|!Object)} el Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object * @param {number=} outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight el by subtracting padding and borders */ , cssH = function (el, outerHeight) { var str = isStr(el) , $E = str ? $Ps[el] : $(el) ; if (!$E.length) return 0; if (isNaN(outerHeight)) // not specified outerHeight = str ? getPaneSize(el) : $E.outerHeight(); return $.layout.cssHeight($E, outerHeight); } /** * @param {string} pane Can accept ONLY a 'pane' (east, west, etc) * @param {number=} outerSize (optional) Can pass a width, allowing calculations BEFORE element is resized * @return {number} Returns the innerHeight/Width of el by subtracting padding and borders */ , cssSize = function (pane, outerSize) { if (_c[pane].dir=="horz") // pane = north or south return cssH(pane, outerSize); else // pane = east or west return cssW(pane, outerSize); } /** * @param {string} pane Can accept ONLY a 'pane' (east, west, etc) * @return {Object} Returns hash of minWidth & minHeight */ , cssMinDims = function (pane) { // minWidth/Height means CSS width/height = 1px var dir = _c[pane].dir , d = { minWidth: 1001 - cssW(pane, 1000) , minHeight: 1001 - cssH(pane, 1000) } ; if (dir == "horz") d.minSize = d.minHeight; if (dir == "vert") d.minSize = d.minWidth; return d; } // TODO: see if these methods can be made more useful... // TODO: *maybe* return cssW/H from these so caller can use this info /** * @param {(string|!Object)} el * @param {number=} outerWidth * @param {boolean=} autoHide */ , setOuterWidth = function (el, outerWidth, autoHide) { var $E = el, w; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); w = cssW($E, outerWidth); $E.css({ width: w }); if (w > 0) { if (autoHide && $E.data('autoHidden') && $E.innerHeight() > 0) { $E.show().data('autoHidden', false); if (!$.layout.browser.mozilla) // FireFox refreshes iframes - IE does not // make hidden, then visible to 'refresh' display after animation $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); } /** * @param {(string|!Object)} el * @param {number=} outerHeight * @param {boolean=} autoHide */ , setOuterHeight = function (el, outerHeight, autoHide) { var $E = el, h; if (isStr(el)) $E = $Ps[el]; // west else if (!el.jquery) $E = $(el); h = cssH($E, outerHeight); $E.css({ height: h, visibility: "visible" }); // may have been 'hidden' by sizeContent if (h > 0 && $E.innerWidth() > 0) { if (autoHide && $E.data('autoHidden')) { $E.show().data('autoHidden', false); if (!$.layout.browser.mozilla) // FireFox refreshes iframes - IE does not $E.css(_c.hidden).css(_c.visible); } } else if (autoHide && !$E.data('autoHidden')) $E.hide().data('autoHidden', true); } /** * @param {(string|!Object)} el * @param {number=} outerSize * @param {boolean=} autoHide */ , setOuterSize = function (el, outerSize, autoHide) { if (_c[pane].dir=="horz") // pane = north or south setOuterHeight(el, outerSize, autoHide); else // pane = east or west setOuterWidth(el, outerSize, autoHide); } /** * Converts any 'size' params to a pixel/integer size, if not already * If 'auto' or a decimal/percentage is passed as 'size', a pixel-size is calculated * /** * @param {string} pane * @param {(string|number)=} size * @param {string=} dir * @return {number} */ , _parseSize = function (pane, size, dir) { if (!dir) dir = _c[pane].dir; if (isStr(size) && size.match(/%/)) size = parseInt(size, 10) / 100; // convert % to decimal if (size === 0) return 0; else if (size >= 1) return parseInt(size, 10); else if (size > 0) { // percentage, eg: .25 var o = options, avail; if (dir=="horz") // north or south or center.minHeight avail = sC.innerHeight - ($Ps.north ? o.north.spacing_open : 0) - ($Ps.south ? o.south.spacing_open : 0); else if (dir=="vert") // east or west or center.minWidth avail = sC.innerWidth - ($Ps.west ? o.west.spacing_open : 0) - ($Ps.east ? o.east.spacing_open : 0); return Math.floor(avail * size); } else if (pane=="center") return 0; else { // size < 0 || size=='auto' || size==Missing || size==Invalid // auto-size the pane var $P = $Ps[pane] , dim = (dir == "horz" ? "height" : "width") , vis = $.layout.showInvisibly($P) // show pane invisibly if hidden , s = $P.css(dim); // SAVE current size ; $P.css(dim, "auto"); size = (dim == "height") ? $P.outerHeight() : $P.outerWidth(); // MEASURE $P.css(dim, s).css(vis); // RESET size & visibility return size; } } /** * Calculates current 'size' (outer-width or outer-height) of a border-pane - optionally with 'pane-spacing' added * * @param {(string|!Object)} pane * @param {boolean=} inclSpace * @return {number} Returns EITHER Width for east/west panes OR Height for north/south panes - adjusted for boxModel & browser */ , getPaneSize = function (pane, inclSpace) { var $P = $Ps[pane] , o = options[pane] , s = state[pane] , oSp = (inclSpace ? o.spacing_open : 0) , cSp = (inclSpace ? o.spacing_closed : 0) ; if (!$P || s.isHidden) return 0; else if (s.isClosed || (s.isSliding && inclSpace)) return cSp; else if (_c[pane].dir == "horz") return $P.outerHeight() + oSp; else // dir == "vert" return $P.outerWidth() + oSp; } /** * Calculate min/max pane dimensions and limits for resizing * * @param {string} pane * @param {boolean=} slide */ , setSizeLimits = function (pane, slide) { if (!isInitialized()) return; var o = options[pane] , s = state[pane] , c = _c[pane] , dir = c.dir , side = c.side.toLowerCase() , type = c.sizeType.toLowerCase() , isSliding = (slide != undefined ? slide : s.isSliding) // only open() passes 'slide' param , $P = $Ps[pane] , paneSpacing = o.spacing_open // measure the pane on the *opposite side* from this pane , altPane = _c.altSide[pane] , altS = state[altPane] , $altP = $Ps[altPane] , altPaneSize = (!$altP || altS.isVisible===false || altS.isSliding ? 0 : (dir=="horz" ? $altP.outerHeight() : $altP.outerWidth())) , altPaneSpacing = ((!$altP || altS.isHidden ? 0 : options[altPane][ altS.isClosed !== false ? "spacing_closed" : "spacing_open" ]) || 0) // limitSize prevents this pane from 'overlapping' opposite pane , containerSize = (dir=="horz" ? sC.innerHeight : sC.innerWidth) , minCenterDims = cssMinDims("center") , minCenterSize = dir=="horz" ? max(options.center.minHeight, minCenterDims.minHeight) : max(options.center.minWidth, minCenterDims.minWidth) // if pane is 'sliding', then ignore center and alt-pane sizes - because 'overlays' them , limitSize = (containerSize - paneSpacing - (isSliding ? 0 : (_parseSize("center", minCenterSize, dir) + altPaneSize + altPaneSpacing))) , minSize = s.minSize = max( _parseSize(pane, o.minSize), cssMinDims(pane).minSize ) , maxSize = s.maxSize = min( (o.maxSize ? _parseSize(pane, o.maxSize) : 100000), limitSize ) , r = s.resizerPosition = {} // used to set resizing limits , top = sC.insetTop , left = sC.insetLeft , W = sC.innerWidth , H = sC.innerHeight , rW = o.spacing_open // subtract resizer-width to get top/left position for south/east ; switch (pane) { case "north": r.min = top + minSize; r.max = top + maxSize; break; case "west": r.min = left + minSize; r.max = left + maxSize; break; case "south": r.min = top + H - maxSize - rW; r.max = top + H - minSize - rW; break; case "east": r.min = left + W - maxSize - rW; r.max = left + W - minSize - rW; break; }; } /** * Returns data for setting the size/position of center pane. Also used to set Height for east/west panes * * @return JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height */ , calcNewCenterPaneDims = function () { var d = { top: getPaneSize("north", true) // true = include 'spacing' value for pane , bottom: getPaneSize("south", true) , left: getPaneSize("west", true) , right: getPaneSize("east", true) , width: 0 , height: 0 }; // NOTE: sC = state.container // calc center-pane outer dimensions d.width = sC.innerWidth - d.left - d.right; // outerWidth d.height = sC.innerHeight - d.bottom - d.top; // outerHeight // add the 'container border/padding' to get final positions relative to the container d.top += sC.insetTop; d.bottom += sC.insetBottom; d.left += sC.insetLeft; d.right += sC.insetRight; return d; } /** * Returns data for setting size of an element (container or a pane). * * @see _create(), onWindowResize() for container, plus others for pane * @return JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc */ , elDims = function ($E) { return $.layout.getElementDimensions($E); } , elCSS = function ($E, list) { return $.layout.getElementCSS($E, list); } /** * @param {!Object} el * @param {boolean=} allStates */ , getHoverClasses = function (el, allStates) { var $El = $(el) , type = $El.data("layoutRole") , pane = $El.data("layoutEdge") , o = options[pane] , root = o[type +"Class"] , _pane = "-"+ pane // eg: "-west" , _open = "-open" , _closed = "-closed" , _slide = "-sliding" , _hover = "-hover " // NOTE the trailing space , _state = $El.hasClass(root+_closed) ? _closed : _open , _alt = _state == _closed ? _open : _closed , classes = (root+_hover) + (root+_pane+_hover) + (root+_state+_hover) + (root+_pane+_state+_hover) ; if (allStates) // when 'removing' classes, also remove alternate-state classes classes += (root+_alt+_hover) + (root+_pane+_alt+_hover); if (type=="resizer" && $El.hasClass(root+_slide)) classes += (root+_slide+_hover) + (root+_pane+_slide+_hover); return $.trim(classes); } , addHover = function (evt, el) { var $E = $(el || this); if (evt && $E.data("layoutRole") == "toggler") evt.stopPropagation(); // prevent triggering 'slide' on Resizer-bar $E.addClass( getHoverClasses($E) ); } , removeHover = function (evt, el) { var $E = $(el || this); $E.removeClass( getHoverClasses($E, true) ); } , onResizerEnter = function (evt) { $('body').disableSelection(); addHover(evt, this); } , onResizerLeave = function (evt, el) { var e = el || this // el is only passed when called by the timer , pane = $(e).data("layoutEdge") , name = pane +"ResizerLeave" ; timer.clear(pane+"_openSlider"); // cancel slideOpen timer, if set timer.clear(name); // cancel enableSelection timer - may re/set below if (!el) { // 1st call - mouseleave event removeHover(evt, this); // do this on initial call // this method calls itself on a timer because it needs to allow // enough time for dragging to kick-in and set the isResizing flag // dragging has a 100ms delay set, so this delay must be higher timer.set(name, function(){ onResizerLeave(evt, e); }, 200); } // if user is resizing, then dragStop will enableSelection() when done else if (!state[pane].isResizing) // 2nd call - by timer $('body').enableSelection(); } /* * ########################### * INITIALIZATION METHODS * ########################### */ /** * Initialize the layout - called automatically whenever an instance of layout is created * * @see none - triggered onInit * @return mixed true = fully initialized | false = panes not initialized (yet) | 'cancel' = abort */ , _create = function () { // initialize config/options initOptions(); var o = options; $.layout.browser.boxModel = $.support.boxModel; // update options with saved state, if option enabled if (o.useStateCookie && o.cookie.autoLoad) loadCookie(); // Update options from state-cookie // TEMP state so isInitialized returns true during init process state.creatingLayout = true; // options & state have been initialized, so now run beforeLoad callback // onload will CANCEL layout creation if it returns false if (false === _execCallback(null, o.onload_start)) return 'cancel'; // initialize the container element _initContainer(); // bind hotkey function - keyDown - if required initHotkeys(); // search for and bind custom-buttons if (o.autoBindCustomButtons) initButtons(); // bind window.onunload $(window).bind("unload."+ sID, unload); // if layout elements are hidden, then layout WILL NOT complete initialization! // initLayoutElements will set initialized=true and run the onload callback IF successful if (o.initPanes) _initLayoutElements(); delete state.creatingLayout; return state.initialized; } /** * Initialize the layout IF not already * * @see All methods in Instance run this test * @return boolean true = layoutElements have been initialized | false = panes are not initialized (yet) */ , isInitialized = function () { if (state.initialized || state.creatingLayout) return true; // already initialized else return _initLayoutElements(); // try to init panes NOW } /** * Initialize the layout - called automatically whenever an instance of layout is created * * @see _create() & isInitialized * @return An object pointer to the instance created */ , _initLayoutElements = function () { // initialize config/options var o = options; // CANNOT init panes inside a hidden container! if (!$N.is(":visible")) return false; // a center pane is required, so make sure it exists if (!getPane('center').length) { if (o.showErrorMessages) alert( lang.errCenterPaneMissing ); return false; } // TEMP state so isInitialized returns true during init process state.creatingLayout = true; // update Container dims $.extend(sC, elDims( $N )); // initialize all layout elements initPanes(); // size & position panes - calls initHandles() - which calls initResizable() sizeContent(); // AFTER panes & handles have been initialized, size 'content' divs if (o.scrollToBookmarkOnLoad) { var l = self.location; if (l.hash) l.replace( l.hash ); // scrollTo Bookmark } // bind resizeAll() for 'this layout instance' to window.resize event if (o.resizeWithWindow && !$N.data("layoutRole")) // skip if 'nested' inside a pane $(window).bind("resize."+ sID, windowResize); delete state.creatingLayout; state.initialized = true; _execCallback(null, o.onload_end || o.onload); return true; // elements initialized successfully } , windowResize = function () { var delay = Number(options.resizeWithWindowDelay); if (delay < 10) delay = 100; // MUST have a delay! // resizing uses a delay-loop because the resize event fires repeatly - except in FF, but delay anyway timer.clear("winResize"); // if already running timer.set("winResize", function(){ timer.clear("winResize"); timer.clear("winResizeRepeater"); var dims = elDims( $N ); // only trigger resizeAll() if container has changed size if (dims.innerWidth !== sC.innerWidth || dims.innerHeight !== sC.innerHeight) resizeAll(); }, delay); // ALSO set fixed-delay timer, if not already running if (!timer.data["winResizeRepeater"]) setWindowResizeRepeater(); } , setWindowResizeRepeater = function () { var delay = Number(options.resizeWithWindowMaxDelay); if (delay > 0) timer.set("winResizeRepeater", function(){ setWindowResizeRepeater(); resizeAll(); }, delay); } , unload = function () { var o = options; state.cookie = getState(); // save state in case onunload has custom state-management _execCallback(null, o.onunload_start); if (o.useStateCookie && o.cookie.autoSave) saveCookie(); _execCallback(null, o.onunload_end || o.onunload); } /** * Validate and initialize container CSS and events * * @see _create() */ , _initContainer = function () { var tag = sC.tagName = $N[0].tagName , o = options , fullPage= (tag == "BODY") , props = "overflow,position,margin,padding,border" , CSS = {} , hid = "hidden" // used A LOT! , isVis = $N.is(":visible") ; // sC -> state.container sC.selector = $N.selector.split(".slice")[0]; sC.ref = tag +"/"+ sC.selector; // used in messages $N .data("layout", Instance) .data("layoutContainer", sID) // unique identifier for internal use .addClass(o.containerClass) ; // SAVE original container CSS for use in destroy() if (!$N.data("layoutCSS")) { // handle props like overflow different for BODY & HTML - has 'system default' values if (fullPage) { CSS = $.extend( elCSS($N, props), { height: $N.css("height") , overflow: $N.css("overflow") , overflowX: $N.css("overflowX") , overflowY: $N.css("overflowY") }); // ALSO SAVE <HTML> CSS var $H = $("html"); $H.data("layoutCSS", { height: "auto" // FF would return a fixed px-size! , overflow: $H.css("overflow") , overflowX: $H.css("overflowX") , overflowY: $H.css("overflowY") }); } else // handle props normally for non-body elements CSS = elCSS($N, props+",top,bottom,left,right,width,height,overflow,overflowX,overflowY"); $N.data("layoutCSS", CSS); } try { // format html/body if this is a full page layout if (fullPage) { $("html").css({ height: "100%" , overflow: hid , overflowX: hid , overflowY: hid }); $("body").css({ position: "relative" , height: "100%" , overflow: hid , overflowX: hid , overflowY: hid , margin: 0 , padding: 0 // TODO: test whether body-padding could be handled? , border: "none" // a body-border creates problems because it cannot be measured! }); // set current layout-container dimensions $.extend(sC, elDims( $N )); } else { // set required CSS for overflow and position // ENSURE container will not 'scroll' CSS = { overflow: hid, overflowX: hid, overflowY: hid } var p = $N.css("position") , h = $N.css("height") ; // if this is a NESTED layout, then container/outer-pane ALREADY has position and height if (!$N.data("layoutRole")) { if (!p || !p.match(/fixed|absolute|relative/)) CSS.position = "relative"; // container MUST have a 'position' /* if (!h || h=="auto") CSS.height = "100%"; // container MUST have a 'height' */ } $N.css( CSS ); // set current layout-container dimensions if (isVis) { $.extend(sC, elDims( $N )); if (o.showErrorMessages && sC.innerHeight < 2) alert( lang.errContainerHeight.replace(/CONTAINER/, sC.ref) ); } } } catch (ex) {} } /** * Bind layout hotkeys - if options enabled * * @see _create() and addPane() * @param {string=} panes The edge(s) to process, blank = all */ , initHotkeys = function (panes) { if (!panes || panes == "all") panes = _c.borderPanes; // bind keyDown to capture hotkeys, if option enabled for ANY pane $.each(panes.split(","), function (i, pane) { var o = options[pane]; if (o.enableCursorHotkey || o.customHotkey) { $(document).bind("keydown."+ sID, keyDown); // only need to bind this ONCE return false; // BREAK - binding was done } }); } /** * Build final OPTIONS data * * @see _create() */ , initOptions = function () { // simplify logic by making sure passed 'opts' var has basic keys opts = _transformData( opts ); // TODO: create a compatibility add-on for new UI widget that will transform old option syntax var newOpts = { applyDefaultStyles: "applyDemoStyles" }; renameOpts(opts.defaults); $.each(_c.allPanes.split(","), function (i, pane) { renameOpts(opts[pane]); }); // update default effects, if case user passed key if (opts.effects) { $.extend( effects, opts.effects ); delete opts.effects; } $.extend( options.cookie, opts.cookie ); // see if any 'global options' were specified var globals = "name,containerClass,zIndex,scrollToBookmarkOnLoad,resizeWithWindow,resizeWithWindowDelay,resizeWithWindowMaxDelay,"+ "onresizeall,onresizeall_start,onresizeall_end,onload,onload_start,onload_end,onunload,onunload_start,onunload_end,"+ "autoBindCustomButtons,useStateCookie,showErrorMessages"; $.each(globals.split(","), function (i, key) { if (opts[key] !== undefined) options[key] = opts[key]; else if (opts.defaults[key] !== undefined) { options[key] = opts.defaults[key]; delete opts.defaults[key]; } }); // remove any 'defaults' that MUST be set 'per-pane' $.each("paneSelector,resizerCursor,customHotkey".split(","), function (i, key) { delete opts.defaults[key]; } // is OK if key does not exist ); // now update options.defaults $.extend( true, options.defaults, opts.defaults ); // merge config for 'center-pane' - border-panes handled in the loop below _c.center = $.extend( true, {}, _c.panes, _c.center ); // update config.zIndex values if zIndex option specified var z = options.zIndex; if (z === 0 || z > 0) { _c.zIndex.pane_normal = z; _c.zIndex.resizer_normal = z+1; _c.zIndex.iframe_mask = z+1; } // merge options for 'center-pane' - border-panes handled in the loop below $.extend( options.center, opts.center ); // Most 'default options' do not apply to 'center', so add only those that DO var o_Center = $.extend( true, {}, options.defaults, opts.defaults, options.center ); // TEMP data var optionsCenter = ("paneClass,contentSelector,applyDemoStyles,triggerEventsOnLoad,showOverflowOnHover," + "onresize,onresize_start,onresize_end,resizeNestedLayout,resizeContentWhileDragging,findNestedContent," + "onsizecontent,onsizecontent_start,onsizecontent_end").split(","); $.each(optionsCenter, function (i, key) { options.center[key] = o_Center[key]; } ); var o, defs = options.defaults; // create a COMPLETE set of options for EACH border-pane $.each(_c.borderPanes.split(","), function (i, pane) { // apply 'pane-defaults' to CONFIG.[PANE] _c[pane] = $.extend( true, {}, _c.panes, _c[pane] ); // apply 'pane-defaults' + user-options to OPTIONS.PANE o = options[pane] = $.extend( true, {}, options.defaults, options[pane], opts.defaults, opts[pane] ); // make sure we have base-classes if (!o.paneClass) o.paneClass = "ui-layout-pane"; if (!o.resizerClass) o.resizerClass = "ui-layout-resizer"; if (!o.togglerClass) o.togglerClass = "ui-layout-toggler"; // create FINAL fx options for each pane, ie: options.PANE.fxName/fxSpeed/fxSettings[_open|_close] $.each(["_open","_close",""], function (i,n) { var sName = "fxName"+n , sSpeed = "fxSpeed"+n , sSettings = "fxSettings"+n ; // recalculate fxName according to specificity rules o[sName] = opts[pane][sName] // opts.west.fxName_open || opts[pane].fxName // opts.west.fxName || opts.defaults[sName] // opts.defaults.fxName_open || opts.defaults.fxName // opts.defaults.fxName || o[sName] // options.west.fxName_open || o.fxName // options.west.fxName || defs[sName] // options.defaults.fxName_open || defs.fxName // options.defaults.fxName || "none" ; // validate fxName to be sure is a valid effect var fxName = o[sName]; if (fxName == "none" || !$.effects || !$.effects[fxName] || (!effects[fxName] && !o[sSettings] && !o.fxSettings)) fxName = o[sName] = "none"; // effect not loaded, OR undefined FX AND fxSettings not passed // set vars for effects subkeys to simplify logic var fx = effects[fxName] || {} // effects.slide , fx_all = fx.all || {} // effects.slide.all , fx_pane = fx[pane] || {} // effects.slide.west ; // RECREATE the fxSettings[_open|_close] keys using specificity rules o[sSettings] = $.extend( {} , fx_all // effects.slide.all , fx_pane // effects.slide.west , defs.fxSettings || {} // options.defaults.fxSettings , defs[sSettings] || {} // options.defaults.fxSettings_open , o.fxSettings // options.west.fxSettings , o[sSettings] // options.west.fxSettings_open , opts.defaults.fxSettings // opts.defaults.fxSettings , opts.defaults[sSettings] || {} // opts.defaults.fxSettings_open , opts[pane].fxSettings // opts.west.fxSettings , opts[pane][sSettings] || {} // opts.west.fxSettings_open ); // recalculate fxSpeed according to specificity rules o[sSpeed] = opts[pane][sSpeed] // opts.west.fxSpeed_open || opts[pane].fxSpeed // opts.west.fxSpeed (pane-default) || opts.defaults[sSpeed] // opts.defaults.fxSpeed_open || opts.defaults.fxSpeed // opts.defaults.fxSpeed || o[sSpeed] // options.west.fxSpeed_open || o[sSettings].duration // options.west.fxSettings_open.duration || o.fxSpeed // options.west.fxSpeed || o.fxSettings.duration // options.west.fxSettings.duration || defs.fxSpeed // options.defaults.fxSpeed || defs.fxSettings.duration// options.defaults.fxSettings.duration || fx_pane.duration // effects.slide.west.duration || fx_all.duration // effects.slide.all.duration || "normal" // DEFAULT ; }); }); function renameOpts (O) { for (var key in newOpts) { if (O[key] != undefined) { O[newOpts[key]] = O[key]; delete O[key]; } } } } /** * Initialize module objects, styling, size and position for all panes * * @see _create() * @param {string} pane The pane to process */ , getPane = function (pane) { var sel = options[pane].paneSelector if (sel.substr(0,1)==="#") // ID selector // NOTE: elements selected 'by ID' DO NOT have to be 'children' return $N.find(sel).eq(0); else { // class or other selector var $P = $N.children(sel).eq(0); // look for the pane nested inside a 'form' element return $P.length ? $P : $N.children("form:first").children(sel).eq(0); } } , initPanes = function () { // NOTE: do north & south FIRST so we can measure their height - do center LAST $.each(_c.allPanes.split(","), function (idx, pane) { addPane( pane, true ); }); // init the pane-handles NOW in case we have to hide or close the pane below initHandles(); // now that all panes have been initialized and initially-sized, // make sure there is really enough space available for each pane $.each(_c.borderPanes.split(","), function (i, pane) { if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN setSizeLimits(pane); makePaneFit(pane); // pane may be Closed, Hidden or Resized by makePaneFit() } }); // size center-pane AGAIN in case we 'closed' a border-pane in loop above sizeMidPanes("center"); // Chrome fires callback BEFORE it completes resizing, so add a delay before handling children setTimeout(function(){ $.each(_c.allPanes.split(","), function (i, pane) { var o = options[pane]; if ($Ps[pane] && state[pane].isVisible) { // pane is OPEN // trigger onResize callbacks for all panes with triggerEventsOnLoad = true if (o.triggerEventsOnLoad) _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } }); }, 50 ); // 50ms delay is enough if (options.showErrorMessages && $N.innerHeight() < 2) alert( lang.errContainerHeight.replace(/CONTAINER/, sC.ref) ); } /** * Remove a pane from the layout - subroutine of destroy() * * @see initPanes() * @param {string} pane The pane to process */ , addPane = function (pane, force) { if (!force && !isInitialized()) return; var o = options[pane] , s = state[pane] , c = _c[pane] , fx = s.fx , dir = c.dir , spacing = o.spacing_open || 0 , isCenter = (pane == "center") , CSS = {} , $P = $Ps[pane] , size, minSize, maxSize ; // if pane-pointer already exists, remove the old one first if ($P) removePane( pane ); else $Cs[pane] = false; // init $P = $Ps[pane] = getPane(pane); if (!$P.length) { $Ps[pane] = false; // logic return; } // SAVE original Pane CSS if (!$P.data("layoutCSS")) { var props = "position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border"; $P.data("layoutCSS", elCSS($P, props)); } // add basic classes & attributes $P .data("parentLayout", Instance) .data("layoutRole", "pane") .data("layoutEdge", pane) .css(c.cssReq).css("zIndex", _c.zIndex.pane_normal) .css(o.applyDemoStyles ? c.cssDemo : {}) // demo styles .addClass( o.paneClass +" "+ o.paneClass+"-"+pane ) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector' .bind("mouseenter."+ sID, addHover ) .bind("mouseleave."+ sID, removeHover ) ; // see if this pane has a 'scrolling-content element' initContent(pane, false); // false = do NOT sizeContent() - called later if (!isCenter) { // call _parseSize AFTER applying pane classes & styles - but before making visible (if hidden) // if o.size is auto or not valid, then MEASURE the pane and use that as its 'size' size = s.size = _parseSize(pane, o.size); minSize = _parseSize(pane,o.minSize) || 1; maxSize = _parseSize(pane,o.maxSize) || 100000; if (size > 0) size = max(min(size, maxSize), minSize); // state for border-panes s.isClosed = false; // true = pane is closed s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes s.isResizing= false; // true = pane is in process of being resized s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible! } // state common to ALL panes s.tagName = $P[0].tagName; s.edge = pane // useful if pane is (or about to be) 'swapped' - easy find out where it is (or is going) s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically s.isVisible = true; // false = pane is invisible - closed OR hidden - simplify logic // set css-position to account for container borders & padding switch (pane) { case "north": CSS.top = sC.insetTop; CSS.left = sC.insetLeft; CSS.right = sC.insetRight; break; case "south": CSS.bottom = sC.insetBottom; CSS.left = sC.insetLeft; CSS.right = sC.insetRight; break; case "west": CSS.left = sC.insetLeft; // top, bottom & height set by sizeMidPanes() break; case "east": CSS.right = sC.insetRight; // ditto break; case "center": // top, left, width & height set by sizeMidPanes() } if (dir == "horz") // north or south pane CSS.height = max(1, cssH(pane, size)); else if (dir == "vert") // east or west pane CSS.width = max(1, cssW(pane, size)); //else if (isCenter) {} $P.css(CSS); // apply size -- top, bottom & height will be set by sizeMidPanes if (dir != "horz") sizeMidPanes(pane, true); // true = skipCallback // close or hide the pane if specified in settings if (o.initClosed && o.closable && !o.initHidden) close(pane, true, true); // true, true = force, noAnimation else if (o.initHidden || o.initClosed) hide(pane); // will be completely invisible - no resizer or spacing else if (!s.noRoom) // make the pane visible - in case was initially hidden $P.css("display","block"); // ELSE setAsOpen() - called later by initHandles() // RESET visibility now - pane will appear IF display:block $P.css("visibility","visible"); // check option for auto-handling of pop-ups & drop-downs if (o.showOverflowOnHover) $P.hover( allowOverflow, resetOverflow ); // if adding a pane AFTER initialization, then... if (state.initialized) { initHandles( pane ); initHotkeys( pane ); resizeAll(); // will sizeContent if pane is visible if (s.isVisible) { // pane is OPEN if (o.triggerEventsOnLoad) _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } } } /** * Initialize module objects, styling, size and position for all resize bars and toggler buttons * * @see _create() * @param {string=} panes The edge(s) to process, blank = all */ , initHandles = function (panes) { if (!panes || panes == "all") panes = _c.borderPanes; // create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV $.each(panes.split(","), function (i, pane) { var $P = $Ps[pane]; $Rs[pane] = false; // INIT $Ts[pane] = false; if (!$P) return; // pane does not exist - skip var o = options[pane] , s = state[pane] , c = _c[pane] , rClass = o.resizerClass , tClass = o.togglerClass , side = c.side.toLowerCase() , spacing = (s.isVisible ? o.spacing_open : o.spacing_closed) , _pane = "-"+ pane // used for classNames , _state = (s.isVisible ? "-open" : "-closed") // used for classNames // INIT RESIZER BAR , $R = $Rs[pane] = $("<div></div>") // INIT TOGGLER BUTTON , $T = (o.closable ? $Ts[pane] = $("<div></div>") : false) ; //if (s.isVisible && o.resizable) ... handled by initResizable if (!s.isVisible && o.slidable) $R.attr("title", o.sliderTip).css("cursor", o.sliderCursor); $R // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer" .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-resizer" : "")) .data("parentLayout", Instance) .data("layoutRole", "resizer") .data("layoutEdge", pane) .css(_c.resizers.cssReq).css("zIndex", _c.zIndex.resizer_normal) .css(o.applyDemoStyles ? _c.resizers.cssDemo : {}) // add demo styles .addClass(rClass +" "+ rClass+_pane) .appendTo($N) // append DIV to container ; if ($T) { $T // if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "#paneLeft-toggler" .attr("id", (o.paneSelector.substr(0,1)=="#" ? o.paneSelector.substr(1) + "-toggler" : "")) .data("parentLayout", Instance) .data("layoutRole", "toggler") .data("layoutEdge", pane) .css(_c.togglers.cssReq) // add base/required styles .css(o.applyDemoStyles ? _c.togglers.cssDemo : {}) // add demo styles .addClass(tClass +" "+ tClass+_pane) .appendTo($R) // append SPAN to resizer DIV ; // ADD INNER-SPANS TO TOGGLER if (o.togglerContent_open) // ui-layout-open $("<span>"+ o.togglerContent_open +"</span>") .data("layoutRole", "togglerContent") .data("layoutEdge", pane) .addClass("content content-open") .css("display","none") .appendTo( $T ) //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-open instead! ; if (o.togglerContent_closed) // ui-layout-closed $("<span>"+ o.togglerContent_closed +"</span>") .data("layoutRole", "togglerContent") .data("layoutEdge", pane) .addClass("content content-closed") .css("display","none") .appendTo( $T ) //.hover( addHover, removeHover ) // use ui-layout-toggler-west-hover .content-closed instead! ; // ADD TOGGLER.click/.hover enableClosable(pane); } // add Draggable events initResizable(pane); // ADD CLASSNAMES & SLIDE-BINDINGS - eg: class="resizer resizer-west resizer-open" if (s.isVisible) setAsOpen(pane); // onOpen will be called, but NOT onResize else { setAsClosed(pane); // onClose will be called bindStartSlidingEvent(pane, true); // will enable events IF option is set } }); // SET ALL HANDLE DIMENSIONS sizeHandles("all"); } /** * Initialize scrolling ui-layout-content div - if exists * * @see initPane() - or externally after an Ajax injection * @param {string} pane The pane to process * @param {boolean=} resize Size content after init, default = true */ , initContent = function (pane, resize) { if (!isInitialized()) return; var o = options[pane] , sel = o.contentSelector , $P = $Ps[pane] , $C ; if (sel) $C = $Cs[pane] = (o.findNestedContent) ? $P.find(sel).eq(0) // match 1-element only : $P.children(sel).eq(0) ; if ($C && $C.length) { // SAVE original Pane CSS if (!$C.data("layoutCSS")) $C.data("layoutCSS", elCSS($C, "height")); $C.css( _c.content.cssReq ); if (o.applyDemoStyles) { $C.css( _c.content.cssDemo ); // add padding & overflow: auto to content-div $P.css( _c.content.cssDemoPane ); // REMOVE padding/scrolling from pane } state[pane].content = {}; // init content state if (resize !== false) sizeContent(pane); // sizeContent() is called AFTER init of all elements } else $Cs[pane] = false; } /** * Searches for .ui-layout-button-xxx elements and auto-binds them as layout-buttons * * @see _create() */ , initButtons = function () { var pre = "ui-layout-button-", name; $.each("toggle,open,close,pin,toggle-slide,open-slide".split(","), function (i, action) { $.each(_c.borderPanes.split(","), function (ii, pane) { $("."+pre+action+"-"+pane).each(function(){ // if button was previously 'bound', data.layoutName was set, but is blank if layout has no 'name' name = $(this).data("layoutName") || $(this).attr("layoutName"); if (name == undefined || name == options.name) bindButton(this, action, pane); }); }); }); } /** * Add resize-bars to all panes that specify it in options * -dependancy: $.fn.resizable - will skip if not found * * @see _create() * @param {string=} panes The edge(s) to process, blank = all */ , initResizable = function (panes) { var draggingAvailable = (typeof $.fn.draggable == "function") , $Frames, side // set in start() ; if (!panes || panes == "all") panes = _c.borderPanes; $.each(panes.split(","), function (idx, pane) { var o = options[pane] , s = state[pane] , c = _c[pane] , side = (c.dir=="horz" ? "top" : "left") , r, live // set in start because may change ; if (!draggingAvailable || !$Ps[pane] || !o.resizable) { o.resizable = false; return true; // skip to next } var $P = $Ps[pane] , $R = $Rs[pane] , base = o.resizerClass // 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process , resizerClass = base+"-drag" // resizer-drag , resizerPaneClass = base+"-"+pane+"-drag" // resizer-north-drag // 'helper' class is applied to the CLONED resizer-bar while it is being dragged , helperClass = base+"-dragging" // resizer-dragging , helperPaneClass = base+"-"+pane+"-dragging" // resizer-north-dragging , helperLimitClass = base+"-dragging-limit" // resizer-drag , helperPaneLimitClass = base+"-"+pane+"-dragging-limit" // resizer-north-drag , helperClassesSet = false // logic var ; if (!s.isClosed) $R .attr("title", o.resizerTip) .css("cursor", o.resizerCursor) // n-resize, s-resize, etc ; $R.bind("mouseenter."+ sID, onResizerEnter) .bind("mouseleave."+ sID, onResizerLeave); $R.draggable({ containment: $N[0] // limit resizing to layout container , axis: (c.dir=="horz" ? "y" : "x") // limit resizing to horz or vert axis , delay: 0 , distance: 1 // basic format for helper - style it using class: .ui-draggable-dragging , helper: "clone" , opacity: o.resizerDragOpacity , addClasses: false // avoid ui-state-disabled class when disabled //, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed , zIndex: _c.zIndex.resizer_drag , start: function (e, ui) { // REFRESH options & state pointers in case we used swapPanes o = options[pane]; s = state[pane]; // re-read options live = o.resizeWhileDragging; // ondrag_start callback - will CANCEL hide if returns false // TODO: dragging CANNOT be cancelled like this, so see if there is a way? if (false === _execCallback(pane, o.ondrag_start)) return false; _c.isLayoutBusy = true; // used by sizePane() logic during a liveResize s.isResizing = true; // prevent pane from closing while resizing timer.clear(pane+"_closeSlider"); // just in case already triggered // SET RESIZER LIMITS - used in drag() setSizeLimits(pane); // update pane/resizer state r = s.resizerPosition; $R.addClass( resizerClass +" "+ resizerPaneClass ); // add drag classes helperClassesSet = false; // reset logic var - see drag() // MASK PANES WITH IFRAMES OR OTHER TROUBLESOME ELEMENTS $Frames = $(o.maskIframesOnResize === true ? "iframe" : o.maskIframesOnResize).filter(":visible"); var id, i=0; // ID incrementer - used when 'resizing' masks during dynamic resizing $Frames.each(function() { id = "ui-layout-mask-"+ (++i); $(this).data("layoutMaskID", id); // tag iframe with corresponding maskID $('<div id="'+ id +'" class="ui-layout-mask ui-layout-mask-'+ pane +'"/>') .css({ background: "#fff" , opacity: "0.001" , zIndex: _c.zIndex.iframe_mask , position: "absolute" , width: this.offsetWidth+"px" , height: this.offsetHeight+"px" }) .css($(this).position()) // top & left -- changed from offset() .appendTo(this.parentNode) // put mask-div INSIDE pane to avoid zIndex issues ; }); // DISABLE TEXT SELECTION (probably already done by resizer.mouseOver) $('body').disableSelection(); } , drag: function (e, ui) { if (!helperClassesSet) { // can only add classes after clone has been added to the DOM //$(".ui-draggable-dragging") ui.helper .addClass( helperClass +" "+ helperPaneClass ) // add helper classes .css({ right: "auto", bottom: "auto" }) // fix dir="rtl" issue .children().css("visibility","hidden") // hide toggler inside dragged resizer-bar ; helperClassesSet = true; // draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane! if (s.isSliding) $Ps[pane].css("zIndex", _c.zIndex.pane_sliding); } // CONTAIN RESIZER-BAR TO RESIZING LIMITS var limit = 0; if (ui.position[side] < r.min) { ui.position[side] = r.min; limit = -1; } else if (ui.position[side] > r.max) { ui.position[side] = r.max; limit = 1; } // ADD/REMOVE dragging-limit CLASS if (limit) { ui.helper.addClass( helperLimitClass +" "+ helperPaneLimitClass ); // at dragging-limit window.defaultStatus = "Panel has reached its " + ((limit>0 && pane.match(/north|west/)) || (limit<0 && pane.match(/south|east/)) ? "maximum" : "minimum") +" size"; } else { ui.helper.removeClass( helperLimitClass +" "+ helperPaneLimitClass ); // not at dragging-limit window.defaultStatus = ""; } // DYNAMICALLY RESIZE PANES IF OPTION ENABLED if (live) resizePanes(e, ui, pane); } , stop: function (e, ui) { $('body').enableSelection(); // RE-ENABLE TEXT SELECTION window.defaultStatus = ""; // clear 'resizing limit' message from statusbar $R.removeClass( resizerClass +" "+ resizerPaneClass ); // remove drag classes from Resizer s.isResizing = false; _c.isLayoutBusy = false; // set BEFORE resizePanes so other logic can pick it up resizePanes(e, ui, pane, true); // true = resizingDone } }); /** * resizePanes * * Sub-routine called from stop() and optionally drag() * * @param {!Object} evt * @param {!Object} ui * @param {string} pane * @param {boolean=} resizingDone */ var resizePanes = function (evt, ui, pane, resizingDone) { var dragPos = ui.position , c = _c[pane] , resizerPos, newSize , i = 0 // ID incrementer ; switch (pane) { case "north": resizerPos = dragPos.top; break; case "west": resizerPos = dragPos.left; break; case "south": resizerPos = sC.offsetHeight - dragPos.top - o.spacing_open; break; case "east": resizerPos = sC.offsetWidth - dragPos.left - o.spacing_open; break; }; if (resizingDone) { // Remove OR Resize MASK(S) created in drag.start $("div.ui-layout-mask").each(function() { this.parentNode.removeChild(this); }); //$("div.ui-layout-mask").remove(); // TODO: Is this less efficient? // ondrag_start callback - will CANCEL hide if returns false if (false === _execCallback(pane, o.ondrag_end || o.ondrag)) return false; } else $Frames.each(function() { $("#"+ $(this).data("layoutMaskID")) // get corresponding mask by ID .css($(this).position()) // update top & left .css({ // update width & height width: this.offsetWidth +"px" , height: this.offsetHeight+"px" }) ; }); // remove container margin from resizer position to get the pane size newSize = resizerPos - sC["inset"+ c.side]; manualSizePane(pane, newSize); } }); } /** * Destroy this layout and reset all elements */ , destroy = function () { // UNBIND layout events and remove global object $(window).unbind("."+ sID); $(document).unbind("."+ sID); // loop all panes to remove layout classes, attributes and bindings $.each(_c.allPanes.split(","), function (i, pane) { removePane( pane, false, true ); // true = skipResize }); // reset layout-container $N .removeData("layout") .removeData("layoutContainer") .removeClass(options.containerClass) ; // do NOT reset container CSS if is a 'pane' in an outer-layout - ie, THIS layout is 'nested' if (!$N.data("layoutEdge") && $N.data("layoutCSS")) // RESET CSS $N.css( $N.data("layoutCSS") ).removeData("layoutCSS"); // for full-page layouts, also reset the <HTML> CSS if (sC.tagName == "BODY" && ($N = $("html")).data("layoutCSS")) // RESET <HTML> CSS $N.css( $N.data("layoutCSS") ).removeData("layoutCSS"); // trigger state-management and onunload callback unload(); } /** * Remove a pane from the layout - subroutine of destroy() * * @see destroy() * @param {string} pane The pane to process * @param {boolean=} remove Remove the DOM element? default = false * @param {boolean=} skipResize Skip calling resizeAll()? default = false */ , removePane = function (pane, remove, skipResize) { if (!isInitialized()) return; if (!$Ps[pane]) return; // NO SUCH PANE var $P = $Ps[pane] , $C = $Cs[pane] , $R = $Rs[pane] , $T = $Ts[pane] // create list of ALL pane-classes that need to be removed , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" , root = options[pane].paneClass // default="ui-layout-pane" , pRoot = root +"-"+ pane // eg: "ui-layout-pane-west" , classes = [ root, root+_open, root+_closed, root+_sliding, // generic classes pRoot, pRoot+_open, pRoot+_closed, pRoot+_sliding ] // pane-specific classes ; $.merge(classes, getHoverClasses($P, true)); // ADD hover-classes if (!$P || !$P.length) { } // pane has already been deleted! else if (remove && !$P.data("layoutContainer") && (!$C || !$C.length || !$C.data("layoutContainer"))) $P.remove(); else { $P .removeClass( classes.join(" ") ) // remove ALL pane-classes .removeData("layoutParent") .removeData("layoutRole") .removeData("layoutEdge") .removeData("autoHidden") // in case set .unbind("."+ sID) // remove ALL Layout events // TODO: remove these extra unbind commands when jQuery is fixed //.unbind("mouseenter"+ sID) //.unbind("mouseleave"+ sID) ; // do NOT reset CSS if this pane is STILL the container of a nested layout! // the nested layout will reset its 'container' when/if it is destroyed if (!$P.data("layoutContainer")) $P.css( $P.data("layoutCSS") ).removeData("layoutCSS"); // DITTO for the Content elem if ($C && $C.length && !$C.data("layoutContainer")) $C.css( $C.data("layoutCSS") ).removeData("layoutCSS"); } // REMOVE pane resizer and toggler elements if ($T && $T.length) $T.remove(); if ($R && $R.length) $R.remove(); // CLEAR all pointers and data $Ps[pane] = $Cs[pane] = $Rs[pane] = $Ts[pane] = false; // skip resize & state-clear when called from destroy() if (!skipResize) { resizeAll(); state[pane] = {}; } } /* * ########################### * ACTION METHODS * ########################### */ /** * Completely 'hides' a pane, including its spacing - as if it does not exist * The pane is not actually 'removed' from the source, so can use 'show' to un-hide it * * @param {string} pane The pane being hidden, ie: north, south, east, or west * @param {boolean=} noAnimation */ , hide = function (pane, noAnimation) { if (!isInitialized()) return; var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || s.isHidden) return; // pane does not exist OR is already hidden // onhide_start callback - will CANCEL hide if returns false if (state.initialized && false === _execCallback(pane, o.onhide_start)) return; s.isSliding = false; // just in case // now hide the elements if ($R) $R.hide(); // hide resizer-bar if (!state.initialized || s.isClosed) { s.isClosed = true; // to trigger open-animation on show() s.isHidden = true; s.isVisible = false; $P.hide(); // no animation when loading page sizeMidPanes(_c[pane].dir == "horz" ? "all" : "center"); if (state.initialized || o.triggerEventsOnLoad) _execCallback(pane, o.onhide_end || o.onhide); } else { s.isHiding = true; // used by onclose close(pane, false, noAnimation); // adjust all panes to fit } } /** * Show a hidden pane - show as 'closed' by default unless openPane = true * * @param {string} pane The pane being opened, ie: north, south, east, or west * @param {boolean=} openPane * @param {boolean=} noAnimation * @param {boolean=} noAlert */ , show = function (pane, openPane, noAnimation, noAlert) { if (!isInitialized()) return; var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] ; if (!$P || !s.isHidden) return; // pane does not exist OR is not hidden // onshow_start callback - will CANCEL show if returns false if (false === _execCallback(pane, o.onshow_start)) return; s.isSliding = false; // just in case s.isShowing = true; // used by onopen/onclose //s.isHidden = false; - will be set by open/close - if not cancelled // now show the elements //if ($R) $R.show(); - will be shown by open/close if (openPane === false) close(pane, true); // true = force else open(pane, false, noAnimation, noAlert); // adjust all panes to fit } /** * Toggles a pane open/closed by calling either open or close * * @param {string} pane The pane being toggled, ie: north, south, east, or west * @param {boolean=} slide */ , toggle = function (pane, slide) { if (!isInitialized()) return; if (!isStr(pane)) { pane.stopImmediatePropagation(); // pane = event pane = $(this).data("layoutEdge"); // bound to $R.dblclick } var s = state[str(pane)]; if (s.isHidden) show(pane); // will call 'open' after unhiding it else if (s.isClosed) open(pane, !!slide); else close(pane); } /** * Utility method used during init or other auto-processes * * @param {string} pane The pane being closed * @param {boolean=} setHandles */ , _closePane = function (pane, setHandles) { var $P = $Ps[pane] , s = state[pane] ; $P.hide(); s.isClosed = true; s.isVisible = false; // UNUSED: if (setHandles) setAsClosed(pane, true); // true = force } /** * Close the specified pane (animation optional), and resize all other panes as needed * * @param {string} pane The pane being closed, ie: north, south, east, or west * @param {boolean=} force * @param {boolean=} noAnimation * @param {boolean=} skipCallback */ , close = function (pane, force, noAnimation, skipCallback) { if (!state.initialized && $Ps[pane]) { _closePane(pane); // INIT pane as closed return; } if (!isInitialized()) return; var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none") // transfer logic vars to temp vars , isShowing = s.isShowing , isHiding = s.isHiding , wasSliding = s.isSliding ; // now clear the logic vars delete s.isShowing; delete s.isHiding; if (!$P || (!o.closable && !isShowing && !isHiding)) return; // invalid request // (!o.resizable && !o.closable) ??? else if (!force && s.isClosed && !isShowing) return; // already closed if (_c.isLayoutBusy) { // layout is 'busy' - probably with an animation _queue("close", pane, force); // set a callback for this action, if possible return; // ABORT } // onclose_start callback - will CANCEL hide if returns false // SKIP if just 'showing' a hidden pane as 'closed' if (!isShowing && false === _execCallback(pane, o.onclose_start)) return; // SET flow-control flags _c[pane].isMoving = true; _c.isLayoutBusy = true; s.isClosed = true; s.isVisible = false; // update isHidden BEFORE sizing panes if (isHiding) s.isHidden = true; else if (isShowing) s.isHidden = false; if (s.isSliding) // pane is being closed, so UNBIND trigger events bindStopSlidingEvents(pane, false); // will set isSliding=false else // resize panes adjacent to this one sizeMidPanes(_c[pane].dir == "horz" ? "all" : "center", false); // false = NOT skipCallback // if this pane has a resizer bar, move it NOW - before animation setAsClosed(pane); // CLOSE THE PANE if (doFX) { // animate the close lockPaneForFX(pane, true); // need to set left/top so animation will work $P.hide( o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () { lockPaneForFX(pane, false); // undo close_2(); }); } else { // hide the pane without animation $P.hide(); close_2(); }; // SUBROUTINE function close_2 () { if (s.isClosed) { // make sure pane was not 'reopened' before animation finished! bindStartSlidingEvent(pane, true); // will enable if o.slidable = true // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.altSide[pane]; if (state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane ); } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad)) { // onclose callback - UNLESS just 'showing' a hidden pane as 'closed' if (!isShowing) _execCallback(pane, o.onclose_end || o.onclose); // onhide OR onshow callback if (isShowing) _execCallback(pane, o.onshow_end || o.onshow); if (isHiding) _execCallback(pane, o.onhide_end || o.onhide); } } // execute internal flow-control callback _dequeue(pane); } } /** * @param {string} pane The pane just closed, ie: north, south, east, or west */ , setAsClosed = function (pane) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side.toLowerCase() , inset = "inset"+ _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _sliding= "-sliding" , _closed = "-closed" ; $R .css(side, sC[inset]) // move the resizer .removeClass( rClass+_open +" "+ rClass+_pane+_open ) .removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) .addClass( rClass+_closed +" "+ rClass+_pane+_closed ) .unbind("dblclick."+ sID) ; // DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvent? if (o.resizable && typeof $.fn.draggable == "function") $R .draggable("disable") .removeClass("ui-state-disabled") // do NOT apply disabled styling - not suitable here .css("cursor", "default") .attr("title","") ; // if pane has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_open +" "+ tClass+_pane+_open ) .addClass( tClass+_closed +" "+ tClass+_pane+_closed ) .attr("title", o.togglerTip_closed) // may be blank ; // toggler-content - if exists $T.children(".content-open").hide(); $T.children(".content-closed").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, false); if (state.initialized) { // resize 'length' and position togglers for adjacent panes sizeHandles("all"); } } /** * Open the specified pane (animation optional), and resize all other panes as needed * * @param {string} pane The pane being opened, ie: north, south, east, or west * @param {boolean=} slide * @param {boolean=} noAnimation * @param {boolean=} noAlert */ , open = function (pane, slide, noAnimation, noAlert) { if (!isInitialized()) return; var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , doFX = !noAnimation && s.isClosed && (o.fxName_open != "none") // transfer logic var to temp var , isShowing = s.isShowing ; // now clear the logic var delete s.isShowing; if (!$P || (!o.resizable && !o.closable && !isShowing)) return; // invalid request else if (s.isVisible && !s.isSliding) return; // already open // pane can ALSO be unhidden by just calling show(), so handle this scenario if (s.isHidden && !isShowing) { show(pane, true); return; } if (_c.isLayoutBusy) { // layout is 'busy' - probably with an animation _queue("open", pane, slide); // set a callback for this action, if possible return; // ABORT } setSizeLimits(pane, slide); // update pane-state // onopen_start callback - will CANCEL hide if returns false if (false === _execCallback(pane, o.onopen_start)) return; // make sure there is enough space available to open the pane setSizeLimits(pane, slide); // update pane-state if (s.minSize > s.maxSize) { // INSUFFICIENT ROOM FOR PANE TO OPEN! syncPinBtns(pane, false); // make sure pin-buttons are reset if (!noAlert && o.noRoomToOpenTip) alert(o.noRoomToOpenTip); return; // ABORT } // SET flow-control flags _c[pane].isMoving = true; _c.isLayoutBusy = true; if (slide) // START Sliding - will set isSliding=true bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane else if (s.isSliding) // PIN PANE (stop sliding) - open pane 'normally' instead bindStopSlidingEvents(pane, false); // UNBIND trigger events - will set isSliding=false else if (o.slidable) bindStartSlidingEvent(pane, false); // UNBIND trigger events s.noRoom = false; // will be reset by makePaneFit if 'noRoom' makePaneFit(pane); s.isVisible = true; s.isClosed = false; // update isHidden BEFORE sizing panes - WHY??? Old? if (isShowing) s.isHidden = false; if (doFX) { // ANIMATE lockPaneForFX(pane, true); // need to set left/top so animation will work $P.show( o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() { lockPaneForFX(pane, false); // undo open_2(); // continue }); } else {// no animation $P.show(); // just show pane and... open_2(); // continue }; // SUBROUTINE function open_2 () { if (s.isVisible) { // make sure pane was not closed or hidden before animation finished! // cure iframe display issues _fixIframe(pane); // NOTE: if isSliding, then other panes are NOT 'resized' if (!s.isSliding) // resize all panes adjacent to this one sizeMidPanes(_c[pane].dir=="vert" ? "center" : "all", false); // false = NOT skipCallback // set classes, position handles and execute callbacks... setAsOpen(pane); } // internal flow-control callback _dequeue(pane); }; } /** * @param {string} pane The pane just opened, ie: north, south, east, or west * @param {boolean=} skipCallback */ , setAsOpen = function (pane, skipCallback) { var $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , o = options[pane] , s = state[pane] , side = _c[pane].side.toLowerCase() , inset = "inset"+ _c[pane].side , rClass = o.resizerClass , tClass = o.togglerClass , _pane = "-"+ pane // used for classNames , _open = "-open" , _closed = "-closed" , _sliding= "-sliding" ; $R .css(side, sC[inset] + getPaneSize(pane)) // move the resizer .removeClass( rClass+_closed +" "+ rClass+_pane+_closed ) .addClass( rClass+_open +" "+ rClass+_pane+_open ) ; if (s.isSliding) $R.addClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) else // in case 'was sliding' $R.removeClass( rClass+_sliding +" "+ rClass+_pane+_sliding ) if (o.resizerDblClickToggle) $R.bind("dblclick", toggle ); removeHover( 0, $R ); // remove hover classes if (o.resizable && typeof $.fn.draggable == "function") $R .draggable("enable") .css("cursor", o.resizerCursor) .attr("title", o.resizerTip) ; else if (!s.isSliding) $R.css("cursor", "default"); // n-resize, s-resize, etc // if pane also has a toggler button, adjust that too if ($T) { $T .removeClass( tClass+_closed +" "+ tClass+_pane+_closed ) .addClass( tClass+_open +" "+ tClass+_pane+_open ) .attr("title", o.togglerTip_open) // may be blank ; removeHover( 0, $T ); // remove hover classes // toggler-content - if exists $T.children(".content-closed").hide(); $T.children(".content-open").css("display","block"); } // sync any 'pin buttons' syncPinBtns(pane, !s.isSliding); // update pane-state dimensions - BEFORE resizing content $.extend(s, elDims($P)); if (state.initialized) { // resize resizer & toggler sizes for all panes sizeHandles("all"); // resize content every time pane opens - to be sure sizeContent(pane, true); // true = remeasure headers/footers, even if 'isLayoutBusy' } if (!skipCallback && (state.initialized || o.triggerEventsOnLoad) && $P.is(":visible")) { // onopen callback _execCallback(pane, o.onopen_end || o.onopen); // onshow callback - TODO: should this be here? if (s.isShowing) _execCallback(pane, o.onshow_end || o.onshow); // ALSO call onresize because layout-size *may* have changed while pane was closed if (state.initialized) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } } } /** * slideOpen / slideClose / slideToggle * * Pass-though methods for sliding */ , slideOpen = function (evt_or_pane) { if (!isInitialized()) return; var evt = isStr(evt_or_pane) ? null : evt_or_pane , pane = evt ? $(this).data("layoutEdge") : evt_or_pane , s = state[pane] , delay = options[pane].slideDelay_open ; // prevent event from triggering on NEW resizer binding created below if (evt) evt.stopImmediatePropagation(); if (s.isClosed && evt && evt.type == "mouseenter" && delay > 0) // trigger = mouseenter - use a delay timer.set(pane+"_openSlider", open_NOW, delay); else open_NOW(); // will unbind events if is already open /** * SUBROUTINE for timed open */ function open_NOW (evt) { if (!s.isClosed) // skip if no longer closed! bindStopSlidingEvents(pane, true); // BIND trigger events to close sliding-pane else if (!_c[pane].isMoving) open(pane, true); // true = slide - open() will handle binding }; } , slideClose = function (evt_or_pane) { if (!isInitialized()) return; var evt = isStr(evt_or_pane) ? null : evt_or_pane , pane = evt ? $(this).data("layoutEdge") : evt_or_pane , o = options[pane] , s = state[pane] , delay = _c[pane].isMoving ? 1000 : 300 // MINIMUM delay - option may override ; if (s.isClosed || s.isResizing) return; // skip if already closed OR in process of resizing else if (o.slideTrigger_close == "click") close_NOW(); // close immediately onClick else if (o.preventQuickSlideClose && _c.isLayoutBusy) return; // handle Chrome quick-close on slide-open else if (o.preventPrematureSlideClose && evt && $.layout.isMouseOverElem(evt, $Ps[pane])) return; // handle incorrect mouseleave trigger, like when over a SELECT-list in IE else if (evt) // trigger = mouseleave - use a delay // 1 sec delay if 'opening', else .3 sec timer.set(pane+"_closeSlider", close_NOW, max(o.slideDelay_close, delay)); else // called programically close_NOW(); /** * SUBROUTINE for timed close */ function close_NOW () { if (s.isClosed) // skip 'close' if already closed! bindStopSlidingEvents(pane, false); // UNBIND trigger events - TODO: is this needed here? else if (!_c[pane].isMoving) close(pane); // close will handle unbinding }; } , slideToggle = function (pane) { toggle(pane, true); } /** * Must set left/top on East/South panes so animation will work properly * * @param {string} pane The pane to lock, 'east' or 'south' - any other is ignored! * @param {boolean} doLock true = set left/top, false = remove */ , lockPaneForFX = function (pane, doLock) { var $P = $Ps[pane]; if (doLock) { $P.css({ zIndex: _c.zIndex.pane_animate }); // overlay all elements during animation if (pane=="south") $P.css({ top: sC.insetTop + sC.innerHeight - $P.outerHeight() }); else if (pane=="east") $P.css({ left: sC.insetLeft + sC.innerWidth - $P.outerWidth() }); } else { // animation DONE - RESET CSS // TODO: see if this can be deleted. It causes a quick-close when sliding in Chrome $P.css({ zIndex: (state[pane].isSliding ? _c.zIndex.pane_sliding : _c.zIndex.pane_normal) }); if (pane=="south") $P.css({ top: "auto" }); else if (pane=="east") $P.css({ left: "auto" }); // fix anti-aliasing in IE - only needed for animations that change opacity var o = options[pane]; if ($.layout.browser.msie && o.fxOpacityFix && o.fxName_open != "slide" && $P.css("filter") && $P.css("opacity") == 1) $P[0].style.removeAttribute('filter'); } } /** * Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger * * @see open(), close() * @param {string} pane The pane to enable/disable, 'north', 'south', etc. * @param {boolean} enable Enable or Disable sliding? */ , bindStartSlidingEvent = function (pane, enable) { var o = options[pane] , $P = $Ps[pane] , $R = $Rs[pane] , trigger = o.slideTrigger_open.toLowerCase() ; if (!$R || (enable && !o.slidable)) return; // make sure we have a valid event if (trigger.match(/mouseover/)) trigger = o.slideTrigger_open = "mouseenter"; else if (!trigger.match(/click|dblclick|mouseenter/)) trigger = o.slideTrigger_open = "click"; $R // add or remove trigger event [enable ? "bind" : "unbind"](trigger +'.'+ sID, slideOpen) // set the appropriate cursor & title/tip .css("cursor", enable ? o.sliderCursor : "default") .attr("title", enable ? o.sliderTip : "") ; } /** * Add or remove 'mouseleave' events to 'slide close' when pane is 'sliding' open or closed * Also increases zIndex when pane is sliding open * See bindStartSlidingEvent for code to control 'slide open' * * @see slideOpen(), slideClose() * @param {string} pane The pane to process, 'north', 'south', etc. * @param {boolean} enable Enable or Disable events? */ , bindStopSlidingEvents = function (pane, enable) { var o = options[pane] , s = state[pane] , z = _c.zIndex , trigger = o.slideTrigger_close.toLowerCase() , action = (enable ? "bind" : "unbind") , $P = $Ps[pane] , $R = $Rs[pane] ; s.isSliding = enable; // logic timer.clear(pane+"_closeSlider"); // just in case // remove 'slideOpen' trigger event from resizer // ALSO will raise the zIndex of the pane & resizer if (enable) bindStartSlidingEvent(pane, false); // RE/SET zIndex - increases when pane is sliding-open, resets to normal when not $P.css("zIndex", enable ? z.pane_sliding : z.pane_normal); $R.css("zIndex", enable ? z.pane_sliding : z.resizer_normal); // make sure we have a valid event if (!trigger.match(/click|mouseleave/)) trigger = o.slideTrigger_close = "mouseleave"; // also catches 'mouseout' // add/remove slide triggers $R[action](trigger, slideClose); // base event on resize // need extra events for mouseleave if (trigger == "mouseleave") { // also close on pane.mouseleave $P[action]("mouseleave."+ sID, slideClose); // cancel timer when mouse moves between 'pane' and 'resizer' $R[action]("mouseenter."+ sID, cancelMouseOut); $P[action]("mouseenter."+ sID, cancelMouseOut); } if (!enable) timer.clear(pane+"_closeSlider"); else if (trigger == "click" && !o.resizable) { // IF pane is not resizable (which already has a cursor and tip) // then set the a cursor & title/tip on resizer when sliding $R.css("cursor", enable ? o.sliderCursor : "default"); $R.attr("title", enable ? o.togglerTip_open : ""); // use Toggler-tip, eg: "Close Pane" } // SUBROUTINE for mouseleave timer clearing function cancelMouseOut (evt) { timer.clear(pane+"_closeSlider"); evt.stopPropagation(); } } /** * Hides/closes a pane if there is insufficient room - reverses this when there is room again * MUST have already called setSizeLimits() before calling this method * * @param {string} pane The pane being resized * @param {boolean=} isOpening Called from onOpen? * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force */ , makePaneFit = function (pane, isOpening, skipCallback, force) { var o = options[pane] , s = state[pane] , c = _c[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isSidePane = c.dir=="vert" , hasRoom = false ; // special handling for center & east/west panes if (pane == "center" || (isSidePane && s.noVerticalRoom)) { // see if there is enough room to display the pane // ERROR: hasRoom = s.minHeight <= s.maxHeight && (isSidePane || s.minWidth <= s.maxWidth); hasRoom = (s.maxHeight > 0); if (hasRoom && s.noRoom) { // previously hidden due to noRoom, so show now $P.show(); if ($R) $R.show(); s.isVisible = true; s.noRoom = false; if (isSidePane) s.noVerticalRoom = false; _fixIframe(pane); } else if (!hasRoom && !s.noRoom) { // not currently hidden, so hide now $P.hide(); if ($R) $R.hide(); s.isVisible = false; s.noRoom = true; } } // see if there is enough room to fit the border-pane if (pane == "center") { // ignore center in this block } else if (s.minSize <= s.maxSize) { // pane CAN fit hasRoom = true; if (s.size > s.maxSize) // pane is too big - shrink it sizePane(pane, s.maxSize, skipCallback, force); else if (s.size < s.minSize) // pane is too small - enlarge it sizePane(pane, s.minSize, skipCallback, force); else if ($R && $P.is(":visible")) { // make sure resizer-bar is positioned correctly // handles situation where nested layout was 'hidden' when initialized var side = c.side.toLowerCase() , pos = s.size + sC["inset"+ c.side] ; if ($.layout.cssNum($R, side) != pos) $R.css( side, pos ); } // if was previously hidden due to noRoom, then RESET because NOW there is room if (s.noRoom) { // s.noRoom state will be set by open or show if (s.wasOpen && o.closable) { if (o.autoReopen) open(pane, false, true, true); // true = noAnimation, true = noAlert else // leave the pane closed, so just update state s.noRoom = false; } else show(pane, s.wasOpen, true, true); // true = noAnimation, true = noAlert } } else { // !hasRoom - pane CANNOT fit if (!s.noRoom) { // pane not set as noRoom yet, so hide or close it now... s.noRoom = true; // update state s.wasOpen = !s.isClosed && !s.isSliding; if (s.isClosed){} // SKIP else if (o.closable) // 'close' if possible close(pane, true, true); // true = force, true = noAnimation else // 'hide' pane if cannot just be closed hide(pane, true); // true = noAnimation } } } /** * sizePane / manualSizePane * sizePane is called only by internal methods whenever a pane needs to be resized * manualSizePane is an exposed flow-through method allowing extra code when pane is 'manually resized' * * @param {string} pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} skipCallback Should the onresize callback be run? */ , manualSizePane = function (pane, size, skipCallback) { if (!isInitialized()) return; // ANY call to sizePane will disabled autoResize var o = options[pane] // if resizing callbacks have been delayed and resizing is now DONE, force resizing to complete... , forceResize = o.resizeWhileDragging && !_c.isLayoutBusy // && !o.triggerEventsWhileDragging ; o.autoResize = false; // flow-through... sizePane(pane, size, skipCallback, forceResize); } /** * @param {string} pane The pane being resized * @param {number} size The *desired* new size for this pane - will be validated * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force Force resizing even if does not seem necessary */ , sizePane = function (pane, size, skipCallback, force) { if (!isInitialized()) return; var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , side = _c[pane].side.toLowerCase() , dimName = _c[pane].sizeType.toLowerCase() , inset = "inset"+ _c[pane].side , skipResizeWhileDragging = _c.isLayoutBusy && !o.triggerEventsWhileDragging , oldSize ; // calculate 'current' min/max sizes setSizeLimits(pane); // update pane-state oldSize = s.size; size = _parseSize(pane, size); // handle percentages & auto size = max(size, _parseSize(pane, o.minSize)); size = min(size, s.maxSize); if (size < s.minSize) { // not enough room for pane! makePaneFit(pane, false, skipCallback); // will hide or close pane return; } // IF newSize is same as oldSize, then nothing to do - abort if (!force && size == oldSize) return; // onresize_start callback CANNOT cancel resizing because this would break the layout! if (!skipCallback && state.initialized && s.isVisible) _execCallback(pane, o.onresize_start); // resize the pane, and make sure its visible $P.css( dimName, max(1, cssSize(pane, size)) ); /* var edge = _c[pane].sizeType.toLowerCase() , test = [{ target: size , attempt: size , actual: edge=='width' ? $P.outerWidth() : $P.outerHeight() }] , lastTest = test[0] , thisTest = {} ; while (lastTest.actual != size) { test.push( {} ); thisTest = test[ test.length - 1 ]; if (lastTest.actual > size) thisTest.attempt = Math.max(1, lastTest.attempt - (lastTest.actual - size)); else // lastTest.actual < size thisTest.attempt = Math.max(1, lastTest.attempt + (size - lastTest.actual)); $P.css( edge, cssSize(pane, thisTest.attempt) ); thisTest.actual = edge=='width' ? $P.outerWidth() : $P.outerHeight() // after 3 tries, is as close as its gonna get! if (test.length == 3) break; else lastTest = thisTest; } debugData( test, pane ); */ // update pane-state dimensions s.size = size; $.extend(s, elDims($P)); // reposition the resizer-bar if ($R && $P.is(":visible")) $R.css( side, size + sC[inset] ); sizeContent(pane); if (!skipCallback && !skipResizeWhileDragging && state.initialized && s.isVisible) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } // resize all the adjacent panes, and adjust their toggler buttons // when skipCallback passed, it means the controlling method will handle 'other panes' if (!skipCallback) { // also no callback if live-resize is in progress and NOT triggerEventsWhileDragging if (!s.isSliding) sizeMidPanes(_c[pane].dir=="horz" ? "all" : "center", skipResizeWhileDragging, force); sizeHandles("all"); } // if opposite-pane was autoClosed, see if it can be autoOpened now var altPane = _c.altSide[pane]; if (size < oldSize && state[ altPane ].noRoom) { setSizeLimits( altPane ); makePaneFit( altPane, false, skipCallback ); } } /** * @see initPanes(), sizePane(), resizeAll(), open(), close(), hide() * @param {string} panes The pane(s) being resized, comma-delmited string * @param {boolean=} skipCallback Should the onresize callback be run? * @param {boolean=} force */ , sizeMidPanes = function (panes, skipCallback, force) { if (!panes || panes == "all") panes = "east,west,center"; $.each(panes.split(","), function (i, pane) { if (!$Ps[pane]) return; // NO PANE - skip var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , isCenter= (pane=="center") , hasRoom = true , CSS = {} , newCenter = calcNewCenterPaneDims() ; // update pane-state dimensions $.extend(s, elDims($P)); if (pane == "center") { if (!force && s.isVisible && newCenter.width == s.outerWidth && newCenter.height == s.outerHeight) return true; // SKIP - pane already the correct size // set state for makePaneFit() logic $.extend(s, cssMinDims(pane), { maxWidth: newCenter.width , maxHeight: newCenter.height }); CSS = newCenter; // convert OUTER width/height to CSS width/height CSS.width = cssW(pane, CSS.width); CSS.height = cssH(pane, CSS.height); hasRoom = CSS.width > 0 && CSS.height > 0; // during layout init, try to shrink east/west panes to make room for center if (!hasRoom && !state.initialized && o.minWidth > 0) { var reqPx = o.minWidth - s.outerWidth , minE = options.east.minSize || 0 , minW = options.west.minSize || 0 , sizeE = state.east.size , sizeW = state.west.size , newE = sizeE , newW = sizeW ; if (reqPx > 0 && state.east.isVisible && sizeE > minE) { newE = max( sizeE-minE, sizeE-reqPx ); reqPx -= sizeE-newE; } if (reqPx > 0 && state.west.isVisible && sizeW > minW) { newW = max( sizeW-minW, sizeW-reqPx ); reqPx -= sizeW-newW; } // IF we found enough extra space, then resize the border panes as calculated if (reqPx == 0) { if (sizeE != minE) sizePane('east', newE, true); // true = skipCallback - initPanes will handle when done if (sizeW != minW) sizePane('west', newW, true); // now start over! sizeMidPanes('center', skipCallback, force); return; // abort this loop } } } else { // for east and west, set only the height, which is same as center height // set state.min/maxWidth/Height for makePaneFit() logic if (s.isVisible && !s.noVerticalRoom) $.extend(s, elDims($P), cssMinDims(pane)) if (!force && !s.noVerticalRoom && newCenter.height == s.outerHeight) return true; // SKIP - pane already the correct size // east/west have same top, bottom & height as center CSS.top = newCenter.top; CSS.bottom = newCenter.bottom; CSS.height = cssH(pane, newCenter.height); s.maxHeight = max(0, CSS.height); hasRoom = (s.maxHeight > 0); if (!hasRoom) s.noVerticalRoom = true; // makePaneFit() logic } if (hasRoom) { // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized) _execCallback(pane, o.onresize_start); $P.css(CSS); // apply the CSS to pane if (s.noRoom && !s.isClosed && !s.isHidden) makePaneFit(pane); // will re-open/show auto-closed/hidden pane if (s.isVisible) { $.extend(s, elDims($P)); // update pane dimensions if (state.initialized) sizeContent(pane); // also resize the contents, if exists } } else if (!s.noRoom && s.isVisible) // no room for pane makePaneFit(pane); // will hide or close pane if (!s.isVisible) return true; // DONE - next pane /* * Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes * Normally these panes have only 'left' & 'right' positions so pane auto-sizes * ALSO required when pane is an IFRAME because will NOT default to 'full width' */ if (pane == "center") { // finished processing midPanes var b = $.layout.browser; var fix = b.isIE6 || (b.msie && !b.boxModel); if ($Ps.north && (fix || state.north.tagName=="IFRAME")) $Ps.north.css("width", cssW($Ps.north, sC.innerWidth)); if ($Ps.south && (fix || state.south.tagName=="IFRAME")) $Ps.south.css("width", cssW($Ps.south, sC.innerWidth)); } // resizeAll passes skipCallback because it triggers callbacks after ALL panes are resized if (!skipCallback && state.initialized) { _execCallback(pane, o.onresize_end || o.onresize); resizeNestedLayout(pane); } }); } /** * @see window.onresize(), callbacks or custom code */ , resizeAll = function () { if (!state.initialized) { _initLayoutElements(); return; // no need to resize since we just initialized! } var oldW = sC.innerWidth , oldH = sC.innerHeight ; // cannot size layout when 'container' is hidden or collapsed if (!$N.is(":visible:") ) return; $.extend( state.container, elDims( $N ) ); // UPDATE container dimensions if (!sC.outerHeight) return; // onresizeall_start will CANCEL resizing if returns false // state.container has already been set, so user can access this info for calcuations if (false === _execCallback(null, options.onresizeall_start)) return false; var // see if container is now 'smaller' than before shrunkH = (sC.innerHeight < oldH) , shrunkW = (sC.innerWidth < oldW) , $P, o, s, dir ; // NOTE special order for sizing: S-N-E-W $.each(["south","north","east","west"], function (i, pane) { if (!$Ps[pane]) return; // no pane - SKIP s = state[pane]; o = options[pane]; dir = _c[pane].dir; if (o.autoResize && s.size != o.size) // resize pane to original size set in options sizePane(pane, o.size, true, true); // true=skipCallback, true=forceResize else { setSizeLimits(pane); makePaneFit(pane, false, true, true); // true=skipCallback, true=forceResize } }); sizeMidPanes("all", true, true); // true=skipCallback, true=forceResize sizeHandles("all"); // reposition the toggler elements // trigger all individual pane callbacks AFTER layout has finished resizing o = options; // reuse alias $.each(_c.allPanes.split(","), function (i, pane) { $P = $Ps[pane]; if (!$P) return; // SKIP if (state[pane].isVisible) { // undefined for non-existent panes _execCallback(pane, o[pane].onresize_end || o[pane].onresize); // callback - if exists resizeNestedLayout(pane); } }); _execCallback(null, o.onresizeall_end || o.onresizeall); // onresizeall callback, if exists } /** * Whenever a pane resizes or opens that has a nested layout, trigger resizeAll * * @param {string} pane The pane just resized or opened */ , resizeNestedLayout = function (pane) { var $P = $Ps[pane] , $C = $Cs[pane] , d = "layoutContainer" ; if (options[pane].resizeNestedLayout) { if ($P.data( d )) $P.layout().resizeAll(); else if ($C && $C.data( d )) $C.layout().resizeAll(); } } /** * IF pane has a content-div, then resize all elements inside pane to fit pane-height * * @param {string=} panes The pane(s) being resized * @param {boolean=} remeasure Should the content (header/footer) be remeasured? */ , sizeContent = function (panes, remeasure) { if (!isInitialized()) return; if (!panes || panes == "all") panes = _c.allPanes; $.each(panes.split(","), function (idx, pane) { var $P = $Ps[pane] , $C = $Cs[pane] , o = options[pane] , s = state[pane] , m = s.content // m = measurements ; if (!$P || !$C || !$P.is(":visible")) return true; // NOT VISIBLE - skip // onsizecontent_start will CANCEL resizing if returns false if (false === _execCallback(null, o.onsizecontent_start)) return; // skip re-measuring offsets if live-resizing if (!_c.isLayoutBusy || m.top == undefined || remeasure || o.resizeContentWhileDragging) { _measure(); // if any footers are below pane-bottom, they may not measure correctly, // so allow pane overflow and re-measure if (m.hiddenFooters > 0 && $P.css("overflow") == "hidden") { $P.css("overflow", "visible"); _measure(); // remeasure while overflowing $P.css("overflow", "hidden"); } } // NOTE: spaceAbove/Below *includes* the pane paddingTop/Bottom, but not pane.borders var newH = s.innerHeight - (m.spaceAbove - s.css.paddingTop) - (m.spaceBelow - s.css.paddingBottom); if (!$C.is(":visible") || m.height != newH) { // size the Content element to fit new pane-size - will autoHide if not enough room setOuterHeight($C, newH, true); // true=autoHide m.height = newH; // save new height }; if (state.initialized) { _execCallback(pane, o.onsizecontent_end || o.onsizecontent); resizeNestedLayout(pane); } function _below ($E) { return max(s.css.paddingBottom, (parseInt($E.css("marginBottom"), 10) || 0)); }; function _measure () { var ignore = options[pane].contentIgnoreSelector , $Fs = $C.nextAll().not(ignore || ':lt(0)') // not :lt(0) = ALL , $Fs_vis = $Fs.filter(':visible') , $F = $Fs_vis.filter(':last') ; m = { top: $C[0].offsetTop , height: $C.outerHeight() , numFooters: $Fs.length , hiddenFooters: $Fs.length - $Fs_vis.length , spaceBelow: 0 // correct if no content footer ($E) } m.spaceAbove = m.top; // just for state - not used in calc m.bottom = m.top + m.height; if ($F.length) //spaceBelow = (LastFooter.top + LastFooter.height) [footerBottom] - Content.bottom + max(LastFooter.marginBottom, pane.paddingBotom) m.spaceBelow = ($F[0].offsetTop + $F.outerHeight()) - m.bottom + _below($F); else // no footer - check marginBottom on Content element itself m.spaceBelow = _below($C); }; }); } /** * Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary * * @see initHandles(), open(), close(), resizeAll() * @param {string=} panes The pane(s) being resized */ , sizeHandles = function (panes) { if (!panes || panes == "all") panes = _c.borderPanes; $.each(panes.split(","), function (i, pane) { var o = options[pane] , s = state[pane] , $P = $Ps[pane] , $R = $Rs[pane] , $T = $Ts[pane] , $TC ; if (!$P || !$R) return; var dir = _c[pane].dir , _state = (s.isClosed ? "_closed" : "_open") , spacing = o["spacing"+ _state] , togAlign = o["togglerAlign"+ _state] , togLen = o["togglerLength"+ _state] , paneLen , offset , CSS = {} ; if (spacing == 0) { $R.hide(); return; } else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason $R.show(); // in case was previously hidden // Resizer Bar is ALWAYS same width/height of pane it is attached to if (dir == "horz") { // north/south paneLen = $P.outerWidth(); // s.outerWidth || s.resizerLength = paneLen; $R.css({ width: max(1, cssW($R, paneLen)) // account for borders & padding , height: max(0, cssH($R, spacing)) // ditto , left: $.layout.cssNum($P, "left") }); } else { // east/west paneLen = $P.outerHeight(); // s.outerHeight || s.resizerLength = paneLen; $R.css({ height: max(1, cssH($R, paneLen)) // account for borders & padding , width: max(0, cssW($R, spacing)) // ditto , top: sC.insetTop + getPaneSize("north", true) // TODO: what if no North pane? //, top: $.layout.cssNum($Ps["center"], "top") }); } // remove hover classes removeHover( o, $R ); if ($T) { if (togLen == 0 || (s.isSliding && o.hideTogglerOnSlide)) { $T.hide(); // always HIDE the toggler when 'sliding' return; } else $T.show(); // in case was previously hidden if (!(togLen > 0) || togLen == "100%" || togLen > paneLen) { togLen = paneLen; offset = 0; } else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed if (isStr(togAlign)) { switch (togAlign) { case "top": case "left": offset = 0; break; case "bottom": case "right": offset = paneLen - togLen; break; case "middle": case "center": default: offset = Math.floor((paneLen - togLen) / 2); // 'default' catches typos } } else { // togAlign = number var x = parseInt(togAlign, 10); // if (togAlign >= 0) offset = x; else offset = paneLen - togLen + x; // NOTE: x is negative! } } if (dir == "horz") { // north/south var width = cssW($T, togLen); $T.css({ width: max(0, width) // account for borders & padding , height: max(1, cssH($T, spacing)) // ditto , left: offset // TODO: VERIFY that toggler positions correctly for ALL values , top: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginLeft", Math.floor((width-$TC.outerWidth())/2)); // could be negative }); } else { // east/west var height = cssH($T, togLen); $T.css({ height: max(0, height) // account for borders & padding , width: max(1, cssW($T, spacing)) // ditto , top: offset // POSITION the toggler , left: 0 }); // CENTER the toggler content SPAN $T.children(".content").each(function(){ $TC = $(this); $TC.css("marginTop", Math.floor((height-$TC.outerHeight())/2)); // could be negative }); } // remove ALL hover classes removeHover( 0, $T ); } // DONE measuring and sizing this resizer/toggler, so can be 'hidden' now if (!state.initialized && (o.initHidden || s.noRoom)) { $R.hide(); if ($T) $T.hide(); } }); } , enableClosable = function (pane) { if (!isInitialized()) return; var $T = $Ts[pane], o = options[pane]; if (!$T) return; o.closable = true; $T .bind("click."+ sID, function(evt){ evt.stopPropagation(); toggle(pane); }) .bind("mouseenter."+ sID, addHover) .bind("mouseleave."+ sID, removeHover) .css("visibility", "visible") .css("cursor", "pointer") .attr("title", state[pane].isClosed ? o.togglerTip_closed : o.togglerTip_open) // may be blank .show() ; } , disableClosable = function (pane, hide) { if (!isInitialized()) return; var $T = $Ts[pane]; if (!$T) return; options[pane].closable = false; // is closable is disable, then pane MUST be open! if (state[pane].isClosed) open(pane, false, true); $T .unbind("."+ sID) .css("visibility", hide ? "hidden" : "visible") // instead of hide(), which creates logic issues .css("cursor", "default") .attr("title", "") ; } , enableSlidable = function (pane) { if (!isInitialized()) return; var $R = $Rs[pane], o = options[pane]; if (!$R || !$R.data('draggable')) return; options[pane].slidable = true; if (s.isClosed) bindStartSlidingEvent(pane, true); } , disableSlidable = function (pane) { if (!isInitialized()) return; var $R = $Rs[pane]; if (!$R) return; options[pane].slidable = false; if (state[pane].isSliding) close(pane, false, true); else { bindStartSlidingEvent(pane, false); $R .css("cursor", "default") .attr("title", "") ; removeHover(null, $R[0]); // in case currently hovered } } , enableResizable = function (pane) { if (!isInitialized()) return; var $R = $Rs[pane], o = options[pane]; if (!$R || !$R.data('draggable')) return; o.resizable = true; $R .draggable("enable") .bind("mouseenter."+ sID, onResizerEnter) .bind("mouseleave."+ sID, onResizerLeave) ; if (!state[pane].isClosed) $R .css("cursor", o.resizerCursor) .attr("title", o.resizerTip) ; } , disableResizable = function (pane) { if (!isInitialized()) return; var $R = $Rs[pane]; if (!$R || !$R.data('draggable')) return; options[pane].resizable = false; $R .draggable("disable") .unbind("."+ sID) .css("cursor", "default") .attr("title", "") ; removeHover(null, $R[0]); // in case currently hovered } /** * Move a pane from source-side (eg, west) to target-side (eg, east) * If pane exists on target-side, move that to source-side, ie, 'swap' the panes * * @param {string} pane1 The pane/edge being swapped * @param {string} pane2 ditto */ , swapPanes = function (pane1, pane2) { if (!isInitialized()) return; // change state.edge NOW so callbacks can know where pane is headed... state[pane1].edge = pane2; state[pane2].edge = pane1; // run these even if NOT state.initialized var cancelled = false; if (false === _execCallback(pane1, options[pane1].onswap_start)) cancelled = true; if (!cancelled && false === _execCallback(pane2, options[pane2].onswap_start)) cancelled = true; if (cancelled) { state[pane1].edge = pane1; // reset state[pane2].edge = pane2; return; } var oPane1 = copy( pane1 ) , oPane2 = copy( pane2 ) , sizes = {} ; sizes[pane1] = oPane1 ? oPane1.state.size : 0; sizes[pane2] = oPane2 ? oPane2.state.size : 0; // clear pointers & state $Ps[pane1] = false; $Ps[pane2] = false; state[pane1] = {}; state[pane2] = {}; // ALWAYS remove the resizer & toggler elements if ($Ts[pane1]) $Ts[pane1].remove(); if ($Ts[pane2]) $Ts[pane2].remove(); if ($Rs[pane1]) $Rs[pane1].remove(); if ($Rs[pane2]) $Rs[pane2].remove(); $Rs[pane1] = $Rs[pane2] = $Ts[pane1] = $Ts[pane2] = false; // transfer element pointers and data to NEW Layout keys move( oPane1, pane2 ); move( oPane2, pane1 ); // cleanup objects oPane1 = oPane2 = sizes = null; // make panes 'visible' again if ($Ps[pane1]) $Ps[pane1].css(_c.visible); if ($Ps[pane2]) $Ps[pane2].css(_c.visible); // fix any size discrepancies caused by swap resizeAll(); // run these even if NOT state.initialized _execCallback(pane1, options[pane1].onswap_end || options[pane1].onswap); _execCallback(pane2, options[pane2].onswap_end || options[pane2].onswap); return; function copy (n) { // n = pane var $P = $Ps[n] , $C = $Cs[n] ; return !$P ? false : { pane: n , P: $P ? $P[0] : false , C: $C ? $C[0] : false , state: $.extend({}, state[n]) , options: $.extend({}, options[n]) } }; function move (oPane, pane) { if (!oPane) return; var P = oPane.P , C = oPane.C , oldPane = oPane.pane , c = _c[pane] , side = c.side.toLowerCase() , inset = "inset"+ c.side // save pane-options that should be retained , s = $.extend({}, state[pane]) , o = options[pane] // RETAIN side-specific FX Settings - more below , fx = { resizerCursor: o.resizerCursor } , re, size, pos ; $.each("fxName,fxSpeed,fxSettings".split(","), function (i, k) { fx[k] = o[k]; fx[k +"_open"] = o[k +"_open"]; fx[k +"_close"] = o[k +"_close"]; }); // update object pointers and attributes $Ps[pane] = $(P) .data("layoutEdge", pane) .css(_c.hidden) .css(c.cssReq) ; $Cs[pane] = C ? $(C) : false; // set options and state options[pane] = $.extend({}, oPane.options, fx); state[pane] = $.extend({}, oPane.state); // change classNames on the pane, eg: ui-layout-pane-east ==> ui-layout-pane-west re = new RegExp(o.paneClass +"-"+ oldPane, "g"); P.className = P.className.replace(re, o.paneClass +"-"+ pane); // ALWAYS regenerate the resizer & toggler elements initHandles(pane); // create the required resizer & toggler // if moving to different orientation, then keep 'target' pane size if (c.dir != _c[oldPane].dir) { size = sizes[pane] || 0; setSizeLimits(pane); // update pane-state size = max(size, state[pane].minSize); // use manualSizePane to disable autoResize - not useful after panes are swapped manualSizePane(pane, size, true); // true = skipCallback } else // move the resizer here $Rs[pane].css(side, sC[inset] + (state[pane].isVisible ? getPaneSize(pane) : 0)); // ADD CLASSNAMES & SLIDE-BINDINGS if (oPane.state.isVisible && !s.isVisible) setAsOpen(pane, true); // true = skipCallback else { setAsClosed(pane); bindStartSlidingEvent(pane, true); // will enable events IF option is set } // DESTROY the object oPane = null; }; } ; // END var DECLARATIONS /** * Capture keys when enableCursorHotkey - toggle pane if hotkey pressed * * @see document.keydown() */ function keyDown (evt) { if (!evt) return true; var code = evt.keyCode; if (code < 33) return true; // ignore special keys: ENTER, TAB, etc var PANE = { 38: "north" // Up Cursor - $.ui.keyCode.UP , 40: "south" // Down Cursor - $.ui.keyCode.DOWN , 37: "west" // Left Cursor - $.ui.keyCode.LEFT , 39: "east" // Right Cursor - $.ui.keyCode.RIGHT } , ALT = evt.altKey // no worky! , SHIFT = evt.shiftKey , CTRL = evt.ctrlKey , CURSOR = (CTRL && code >= 37 && code <= 40) , o, k, m, pane ; if (CURSOR && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey pane = PANE[code]; else if (CTRL || SHIFT) // check to see if this matches a custom-hotkey $.each(_c.borderPanes.split(","), function (i, p) { // loop each pane to check its hotkey o = options[p]; k = o.customHotkey; m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT" if ((SHIFT && m=="SHIFT") || (CTRL && m=="CTRL") || (CTRL && SHIFT)) { // Modifier matches if (k && code == (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches pane = p; return false; // BREAK } } }); // validate pane if (!pane || !$Ps[pane] || !options[pane].closable || state[pane].isHidden) return true; toggle(pane); evt.stopPropagation(); evt.returnValue = false; // CANCEL key return false; }; /* * ###################################### * UTILITY METHODS * called externally or by initButtons * ###################################### */ /** * Change/reset a pane overflow setting & zIndex to allow popups/drop-downs to work * * @param {Object=} el (optional) Can also be 'bound' to a click, mouseOver, or other event */ function allowOverflow (el) { if (!isInitialized()) return; if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] ; // if pane is already raised, then reset it before doing it again! // this would happen if allowOverflow is attached to BOTH the pane and an element if (s.cssSaved) resetOverflow(pane); // reset previous CSS before continuing // if pane is raised by sliding or resizing, or its closed, then abort if (s.isSliding || s.isResizing || s.isClosed) { s.cssSaved = false; return; } var newCSS = { zIndex: (_c.zIndex.pane_normal + 2) } , curCSS = {} , of = $P.css("overflow") , ofX = $P.css("overflowX") , ofY = $P.css("overflowY") ; // determine which, if any, overflow settings need to be changed if (of != "visible") { curCSS.overflow = of; newCSS.overflow = "visible"; } if (ofX && !ofX.match(/visible|auto/)) { curCSS.overflowX = ofX; newCSS.overflowX = "visible"; } if (ofY && !ofY.match(/visible|auto/)) { curCSS.overflowY = ofX; newCSS.overflowY = "visible"; } // save the current overflow settings - even if blank! s.cssSaved = curCSS; // apply new CSS to raise zIndex and, if necessary, make overflow 'visible' $P.css( newCSS ); // make sure the zIndex of all other panes is normal $.each(_c.allPanes.split(","), function(i, p) { if (p != pane) resetOverflow(p); }); }; function resetOverflow (el) { if (!isInitialized()) return; if (this && this.tagName) el = this; // BOUND to element var $P; if (isStr(el)) $P = $Ps[el]; else if ($(el).data("layoutRole")) $P = $(el); else $(el).parents().each(function(){ if ($(this).data("layoutRole")) { $P = $(this); return false; // BREAK } }); if (!$P || !$P.length) return; // INVALID var pane = $P.data("layoutEdge") , s = state[pane] , CSS = s.cssSaved || {} ; // reset the zIndex if (!s.isSliding && !s.isResizing) $P.css("zIndex", _c.zIndex.pane_normal); // reset Overflow - if necessary $P.css( CSS ); // clear var s.cssSaved = false; }; /** * Helper function to validate params received by addButton utilities * * Two classes are added to the element, based on the buttonClass... * The type of button is appended to create the 2nd className: * - ui-layout-button-pin * - ui-layout-pane-button-toggle * - ui-layout-pane-button-open * - ui-layout-pane-button-close * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @return {Array.<Object>} If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise returns null */ function getBtn (selector, pane, action) { var $E = $(selector) , err = options.showErrorMessages; if (!$E.length) { // element not found if (err) alert(lang.errButton + lang.selector +": "+ selector); } else if (_c.borderPanes.indexOf(pane) == -1) { // invalid 'pane' sepecified if (err) alert(lang.errButton + lang.pane +": "+ pane); } else { // VALID var btn = options[pane].buttonClass +"-"+ action; $E .addClass( btn +" "+ btn +"-"+ pane ) .data("layoutName", options.name) // add layout identifier - even if blank! ; return $E; } return null; // INVALID }; /** * NEW syntax for binding layout-buttons - will eventually replace addToggleBtn, addOpenBtn, etc. * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} action * @param {string} pane */ function bindButton (selector, action, pane) { switch (action.toLowerCase()) { case "toggle": addToggleBtn(selector, pane); break; case "open": addOpenBtn(selector, pane); break; case "close": addCloseBtn(selector, pane); break; case "pin": addPinBtn(selector, pane); break; case "toggle-slide": addToggleBtn(selector, pane, true); break; case "open-slide": addOpenBtn(selector, pane, true); break; } }; /** * Add a custom Toggler button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ function addToggleBtn (selector, pane, slide) { var $E = getBtn(selector, pane, "toggle"); if ($E) $E.click(function (evt) { toggle(pane, !!slide); evt.stopPropagation(); }); }; /** * Add a custom Open button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. * @param {boolean=} slide true = slide-open, false = pin-open */ function addOpenBtn (selector, pane, slide) { var $E = getBtn(selector, pane, "open"); if ($E) $E .attr("title", lang.Open) .click(function (evt) { open(pane, !!slide); evt.stopPropagation(); }) ; }; /** * Add a custom Close button for a pane * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the button is for: 'north', 'south', etc. */ function addCloseBtn (selector, pane) { var $E = getBtn(selector, pane, "close"); if ($E) $E .attr("title", lang.Close) .click(function (evt) { close(pane); evt.stopPropagation(); }) ; }; /** * addPinBtn * * Add a custom Pin button for a pane * * Four classes are added to the element, based on the paneClass for the associated pane... * Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin: * - ui-layout-pane-pin * - ui-layout-pane-west-pin * - ui-layout-pane-pin-up * - ui-layout-pane-west-pin-up * * @param {(string|!Object)} selector jQuery selector (or element) for button, eg: ".ui-layout-north .toggle-button" * @param {string} pane Name of the pane the pin is for: 'north', 'south', etc. */ function addPinBtn (selector, pane) { var $E = getBtn(selector, pane, "pin"); if ($E) { var s = state[pane]; $E.click(function (evt) { setPinState($(this), pane, (s.isSliding || s.isClosed)); if (s.isSliding || s.isClosed) open( pane ); // change from sliding to open else close( pane ); // slide-closed evt.stopPropagation(); }); // add up/down pin attributes and classes setPinState($E, pane, (!s.isClosed && !s.isSliding)); // add this pin to the pane data so we can 'sync it' automatically // PANE.pins key is an array so we can store multiple pins for each pane _c[pane].pins.push( selector ); // just save the selector string } }; /** * INTERNAL function to sync 'pin buttons' when pane is opened or closed * Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes * * @see open(), close() * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin True means set the pin 'down', False means 'up' */ function syncPinBtns (pane, doPin) { $.each(_c[pane].pins, function (i, selector) { setPinState($(selector), pane, doPin); }); }; /** * Change the class of the pin button to make it look 'up' or 'down' * * @see addPinBtn(), syncPinBtns() * @param {Array.<Object>} $Pin The pin-span element in a jQuery wrapper * @param {string} pane These are the params returned to callbacks by layout() * @param {boolean} doPin true = set the pin 'down', false = set it 'up' */ function setPinState ($Pin, pane, doPin) { var updown = $Pin.attr("pin"); if (updown && doPin == (updown=="down")) return; // already in correct state var pin = options[pane].buttonClass +"-pin" , side = pin +"-"+ pane , UP = pin +"-up "+ side +"-up" , DN = pin +"-down "+side +"-down" ; $Pin .attr("pin", doPin ? "down" : "up") // logic .attr("title", doPin ? lang.Unpin : lang.Pin) .removeClass( doPin ? UP : DN ) .addClass( doPin ? DN : UP ) ; }; /* * LAYOUT STATE MANAGEMENT * * @example .layout({ cookie: { name: "myLayout", keys: "west.isClosed,east.isClosed" } }) * @example .layout({ cookie__name: "myLayout", cookie__keys: "west.isClosed,east.isClosed" }) * @example myLayout.getState( "west.isClosed,north.size,south.isHidden" ); * @example myLayout.saveCookie( "west.isClosed,north.size,south.isHidden", {expires: 7} ); * @example myLayout.deleteCookie(); * @example myLayout.loadCookie(); * @example var hSaved = myLayout.state.cookie; */ function isCookiesEnabled () { // TODO: is the cookieEnabled property common enough to be useful??? return (navigator.cookieEnabled != 0); }; /** * Read & return data from the cookie - as JSON * * @param {Object=} opts */ function getCookie (opts) { var o = $.extend( {}, options.cookie, opts || {} ) , name = o.name || options.name || "Layout" , c = document.cookie , cs = c ? c.split(';') : [] , pair // loop var ; for (var i=0, n=cs.length; i < n; i++) { pair = $.trim(cs[i]).split('='); // name=value pair if (pair[0] == name) // found the layout cookie // convert cookie string back to a hash return decodeJSON( decodeURIComponent(pair[1]) ); } return ""; }; /** * Get the current layout state and save it to a cookie * * @param {(string|Array)=} keys * @param {Object=} opts */ function saveCookie (keys, opts) { var o = $.extend( {}, options.cookie, opts || {} ) , name = o.name || options.name || "Layout" , params = '' , date = '' , clear = false ; if (o.expires.toUTCString) date = o.expires; else if (typeof o.expires == 'number') { date = new Date(); if (o.expires > 0) date.setDate(date.getDate() + o.expires); else { date.setYear(1970); clear = true; } } if (date) params += ';expires='+ date.toUTCString(); if (o.path) params += ';path='+ o.path; if (o.domain) params += ';domain='+ o.domain; if (o.secure) params += ';secure'; if (clear) { state.cookie = {}; // clear data document.cookie = name +'='+ params; // expire the cookie } else { state.cookie = getState(keys || o.keys); // read current panes-state document.cookie = name +'='+ encodeURIComponent( encodeJSON(state.cookie) ) + params; // write cookie } return $.extend({}, state.cookie); // return COPY of state.cookie }; /** * Remove the state cookie */ function deleteCookie () { saveCookie('', { expires: -1 }); }; /** * Get data from the cookie and USE IT to loadState * * @param {Object=} opts */ function loadCookie (opts) { var o = getCookie(opts); // READ the cookie if (o) { state.cookie = $.extend({}, o); // SET state.cookie loadState(o); // LOAD the retrieved state } return o; }; /** * Update layout options from the cookie, if one exists * * @param {Object=} opts * @param {boolean=} animate */ function loadState (opts, animate) { opts = _transformData(opts); $.extend( true, options, opts ); // update layout options // if layout has already been initialized, then UPDATE layout state if (state.initialized) { var pane, o, s, h, c, a = !animate; $.each(_c.allPanes.split(","), function (idx, pane) { o = opts[ pane ]; if (typeof o != 'object') return; // no key, continue s = o.size; c = o.initClosed; h = o.initHidden; if (s > 0 || s=="auto") sizePane(pane, s); if (h === true) hide(pane, a); else if (c === false) open(pane, false, a ); else if (c === true) close(pane, false, a); else if (h === false) show(pane, false, a); }); } }; /** * Get the *current layout state* and return it as a hash * * @param {(string|Array)=} keys */ function getState (keys) { var data = {} , alt = { isClosed: 'initClosed', isHidden: 'initHidden' } , pair, pane, key, val ; if (!keys) keys = options.cookie.keys; // if called by user if ($.isArray(keys)) keys = keys.join(","); // convert keys to an array and change delimiters from '__' to '.' keys = keys.replace(/__/g, ".").split(','); // loop keys and create a data hash for (var i=0,n=keys.length; i < n; i++) { pair = keys[i].split("."); pane = pair[0]; key = pair[1]; if (_c.allPanes.indexOf(pane) < 0) continue; // bad pane! val = state[ pane ][ key ]; if (val == undefined) continue; if (key=="isClosed" && state[pane]["isSliding"]) val = true; // if sliding, then *really* isClosed ( data[pane] || (data[pane]={}) )[ alt[key] ? alt[key] : key ] = val; } return data; }; /** * Stringify a JSON hash so can save in a cookie or db-field */ function encodeJSON (JSON) { return parse( JSON ); function parse (h) { var D=[], i=0, k, v, t; // k = key, v = value for (k in h) { v = h[k]; t = typeof v; if (t == 'string') // STRING - add quotes v = '"'+ v +'"'; else if (t == 'object') // SUB-KEY - recurse into it v = parse(v); D[i++] = '"'+ k +'":'+ v; } return "{"+ D.join(",") +"}"; }; }; /** * Convert stringified JSON back to a hash object */ function decodeJSON (str) { try { return window["eval"]("("+ str +")") || {}; } catch (e) { return {}; } }; /* * ##################### * CREATE/RETURN LAYOUT * ##################### */ // validate that container exists var $N = $(this).eq(0); // FIRST matching Container element if (!$N.length) { if (options.showErrorMessages) alert( lang.errContainerMissing ); return null; }; // Users retreive Instance of a layout with: $N.layout() OR $N.data("layout") // return the Instance-pointer if layout has already been initialized if ($N.data("layoutContainer") && $N.data("layout")) return $N.data("layout"); // cached pointer // init global vars var $Ps = {} // Panes x5 - set in initPanes() , $Cs = {} // Content x5 - set in initPanes() , $Rs = {} // Resizers x4 - set in initHandles() , $Ts = {} // Togglers x4 - set in initHandles() // aliases for code brevity , sC = state.container // alias for easy access to 'container dimensions' , sID = state.id // alias for unique layout ID/namespace - eg: "layout435" ; // create Instance object to expose data & option Properties, and primary action Methods var Instance = { options: options // property - options hash , state: state // property - dimensions hash , container: $N // property - object pointers for layout container , panes: $Ps // property - object pointers for ALL Panes: panes.north, panes.center , contents: $Cs // property - object pointers for ALL Content: content.north, content.center , resizers: $Rs // property - object pointers for ALL Resizers, eg: resizers.north , togglers: $Ts // property - object pointers for ALL Togglers, eg: togglers.north , toggle: toggle // method - pass a 'pane' ("north", "west", etc) , hide: hide // method - ditto , show: show // method - ditto , open: open // method - ditto , close: close // method - ditto , slideOpen: slideOpen // method - ditto , slideClose: slideClose // method - ditto , slideToggle: slideToggle // method - ditto , initContent: initContent // method - ditto , sizeContent: sizeContent // method - ditto , sizePane: manualSizePane // method - pass a 'pane' AND an 'outer-size' in pixels or percent, or 'auto' , swapPanes: swapPanes // method - pass TWO 'panes' - will swap them , resizeAll: resizeAll // method - no parameters , initPanes: isInitialized // method - no parameters , destroy: destroy // method - no parameters , addPane: addPane // method - pass a 'pane' , removePane: removePane // method - pass a 'pane' to remove from layout, add 'true' to delete the pane-elem , setSizeLimits: setSizeLimits // method - pass a 'pane' - update state min/max data , bindButton: bindButton // utility - pass element selector, 'action' and 'pane' (E, "toggle", "west") , addToggleBtn: addToggleBtn // utility - pass element selector and 'pane' (E, "west") , addOpenBtn: addOpenBtn // utility - ditto , addCloseBtn: addCloseBtn // utility - ditto , addPinBtn: addPinBtn // utility - ditto , allowOverflow: allowOverflow // utility - pass calling element (this) , resetOverflow: resetOverflow // utility - ditto , encodeJSON: encodeJSON // method - pass a JSON object , decodeJSON: decodeJSON // method - pass a string of encoded JSON , getState: getState // method - returns hash of current layout-state , getCookie: getCookie // method - update options from cookie - returns hash of cookie data , saveCookie: saveCookie // method - optionally pass keys-list and cookie-options (hash) , deleteCookie: deleteCookie // method , loadCookie: loadCookie // method - update options from cookie - returns hash of cookie data , loadState: loadState // method - pass a hash of state to use to update options , cssWidth: cssW // utility - pass element and target outerWidth , cssHeight: cssH // utility - ditto , enableClosable: enableClosable , disableClosable: disableClosable , enableSlidable: enableSlidable , disableSlidable: disableSlidable , enableResizable: enableResizable , disableResizable: disableResizable }; // create the border layout NOW if (_create() === 'cancel') // onload_start callback returned false to CANCEL layout creation return null; else // true OR false -- if layout-elements did NOT init (hidden or do not exist), can auto-init later return Instance; // return the Instance object } })( jQuery );
JavaScript
/* */ $(document).ready( function() { $('body').layout( { defaults: { size: "auto", spacing_open: 0, spacing_closed: 0, closable: false, resizable:false, slidable: false } } ); } );
JavaScript
(function($) { $.extend({ tablesorterPager: new function() { function updatePageDisplay(c) { var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages); } function setPageSize(table,size) { var c = table.config; c.size = size; c.totalPages = Math.ceil(c.totalRows / c.size); c.pagerPositionSet = false; moveToPage(table); fixPosition(table); } function fixPosition(table) { var c = table.config; if(!c.pagerPositionSet && c.positionFixed) { var c = table.config, o = $(table); if(o.offset) { c.container.css({ top: o.offset().top + o.height() + 'px', position: 'absolute' }); } c.pagerPositionSet = true; } } function moveToFirstPage(table) { var c = table.config; c.page = 0; moveToPage(table); } function moveToLastPage(table) { var c = table.config; c.page = (c.totalPages-1); moveToPage(table); } function moveToNextPage(table) { var c = table.config; c.page++; if(c.page >= (c.totalPages-1)) { c.page = (c.totalPages-1); } moveToPage(table); } function moveToPrevPage(table) { var c = table.config; c.page--; if(c.page <= 0) { c.page = 0; } moveToPage(table); } function moveToPage(table) { var c = table.config; if(c.page < 0 || c.page > (c.totalPages-1)) { c.page = 0; } renderTable(table,c.rowsCopy); } function renderTable(table,rows) { var c = table.config; var l = rows.length; var s = (c.page * c.size); var e = (s + c.size); if(e > rows.length ) { e = rows.length; } var tableBody = $(table.tBodies[0]); // clear the table body $.tablesorter.clearTableBody(table); for(var i = s; i < e; i++) { //tableBody.append(rows[i]); var o = rows[i]; var l = o.length; for(var j=0; j < l; j++) { tableBody[0].appendChild(o[j]); } } fixPosition(table,tableBody); $(table).trigger("applyWidgets"); if( c.page >= c.totalPages ) { moveToLastPage(table); } updatePageDisplay(c); } this.appender = function(table,rows) { var c = table.config; c.rowsCopy = rows; c.totalRows = rows.length; c.totalPages = Math.ceil(c.totalRows / c.size); renderTable(table,rows); }; this.defaults = { size: 10, offset: 0, page: 0, totalRows: 0, totalPages: 0, container: null, cssNext: '.next', cssPrev: '.prev', cssFirst: '.first', cssLast: '.last', cssPageDisplay: '.pagedisplay', cssPageSize: '.pagesize', seperator: "/", positionFixed: false, appender: this.appender }; this.construct = function(settings) { return this.each(function() { config = $.extend(this.config, $.tablesorterPager.defaults, settings); var table = this, pager = config.container; $(this).trigger("appendCache"); config.size = parseInt($(".pagesize",pager).val()); $(config.cssFirst,pager).click(function() { moveToFirstPage(table); return false; }); $(config.cssNext,pager).click(function() { moveToNextPage(table); return false; }); $(config.cssPrev,pager).click(function() { moveToPrevPage(table); return false; }); $(config.cssLast,pager).click(function() { moveToLastPage(table); return false; }); $(config.cssPageSize,pager).change(function() { setPageSize(table,parseInt($(this).val())); return false; }); }); }; } }); // extend plugin scope $.fn.extend({ tablesorterPager: $.tablesorterPager.construct }); })(jQuery);
JavaScript
var classesNav; var devdocNav; var sidenav; var cookie_namespace = 'android_developer'; var NAV_PREF_TREE = "tree"; var NAV_PREF_PANELS = "panels"; var nav_pref; var isMobile = false; // true if mobile, so we can adjust some layout var basePath = getBaseUri(location.pathname); var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1)); /****** ON LOAD SET UP STUFF *********/ var navBarIsFixed = false; $(document).ready(function() { if (devsite) { // move the lang selector into the overflow menu $("#moremenu .mid div.header:last").after($("#language").detach()); } // init the fullscreen toggle click event $('#nav-swap .fullscreen').click(function(){ if ($(this).hasClass('disabled')) { toggleFullscreen(true); } else { toggleFullscreen(false); } }); // initialize the divs with custom scrollbars $('.scroll-pane').jScrollPane( {verticalGutter:0} ); // add HRs below all H2s (except for a few other h2 variants) $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>'); // set search's onkeyup handler here so we can show suggestions // even while search results are visible $("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)}); // set up the search close button $('.search .close').click(function() { $searchInput = $('#search_autocomplete'); $searchInput.attr('value', ''); $(this).addClass("hide"); $("#search-container").removeClass('active'); $("#search_autocomplete").blur(); search_focus_changed($searchInput.get(), false); // see search_autocomplete.js hideResults(); // see search_autocomplete.js }); $('.search').click(function() { if (!$('#search_autocomplete').is(":focused")) { $('#search_autocomplete').focus(); } }); // Set up quicknav var quicknav_open = false; $("#btn-quicknav").click(function() { if (quicknav_open) { $(this).removeClass('active'); quicknav_open = false; collapse(); } else { $(this).addClass('active'); quicknav_open = true; expand(); } }) var expand = function() { $('#header-wrap').addClass('quicknav'); $('#quicknav').stop().show().animate({opacity:'1'}); } var collapse = function() { $('#quicknav').stop().animate({opacity:'0'}, 100, function() { $(this).hide(); $('#header-wrap').removeClass('quicknav'); }); } //Set up search $("#search_autocomplete").focus(function() { $("#search-container").addClass('active'); }) $("#search-container").mouseover(function() { $("#search-container").addClass('active'); $("#search_autocomplete").focus(); }) $("#search-container").mouseout(function() { if ($("#search_autocomplete").is(":focus")) return; if ($("#search_autocomplete").val() == '') { setTimeout(function(){ $("#search-container").removeClass('active'); $("#search_autocomplete").blur(); },250); } }) $("#search_autocomplete").blur(function() { if ($("#search_autocomplete").val() == '') { $("#search-container").removeClass('active'); } }) // prep nav expandos var pagePath = document.location.pathname; // account for intl docs by removing the intl/*/ path if (pagePath.indexOf("/intl/") == 0) { pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last / } if (pagePath.indexOf(SITE_ROOT) == 0) { if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') { pagePath += 'index.html'; } } if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') { // If running locally, SITE_ROOT will be a relative path, so account for that by // finding the relative URL to this page. This will allow us to find links on the page // leading back to this page. var pathParts = pagePath.split('/'); var relativePagePathParts = []; var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3; for (var i = 0; i < upDirs; i++) { relativePagePathParts.push('..'); } for (var i = 0; i < upDirs; i++) { relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]); } relativePagePathParts.push(pathParts[pathParts.length - 1]); pagePath = relativePagePathParts.join('/'); } else { // Otherwise the page path is already an absolute URL } // select current page in sidenav and set up prev/next links if they exist var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]'); var $selListItem; if ($selNavLink.length) { $selListItem = $selNavLink.closest('li'); $selListItem.addClass('selected'); // Traverse up the tree and expand all parent nav-sections $selNavLink.parents('li.nav-section').each(function() { $(this).addClass('expanded'); $(this).children('ul').show(); }); // set up prev links var $prevLink = []; var $prevListItem = $selListItem.prev('li'); var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true : false; // navigate across topic boundaries only in design docs if ($prevListItem.length) { if ($prevListItem.hasClass('nav-section')) { // jump to last topic of previous section $prevLink = $prevListItem.find('a:last'); } else if (!$selListItem.hasClass('nav-section')) { // jump to previous topic in this section $prevLink = $prevListItem.find('a:eq(0)'); } } else { // jump to this section's index page (if it exists) var $parentListItem = $selListItem.parents('li'); $prevLink = $selListItem.parents('li').find('a'); // except if cross boundaries aren't allowed, and we're at the top of a section already // (and there's another parent) if (!crossBoundaries && $parentListItem.hasClass('nav-section') && $selListItem.hasClass('nav-section')) { $prevLink = []; } } // set up next links var $nextLink = []; var startClass = false; var training = $(".next-class-link").length; // decides whether to provide "next class" link var isCrossingBoundary = false; if ($selListItem.hasClass('nav-section')) { // we're on an index page, jump to the first topic $nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)'); // if there aren't any children, go to the next section (required for About pages) if($nextLink.length == 0) { $nextLink = $selListItem.next('li').find('a'); } else if ($('.topic-start-link').length) { // as long as there's a child link and there is a "topic start link" (we're on a landing) // then set the landing page "start link" text to be the first doc title $('.topic-start-link').text($nextLink.text().toUpperCase()); } // If the selected page has a description, then it's a class or article homepage if ($selListItem.find('a[description]').length) { // this means we're on a class landing page startClass = true; } } else { // jump to the next topic in this section (if it exists) $nextLink = $selListItem.next('li').find('a:eq(0)'); if (!$nextLink.length) { isCrossingBoundary = true; // no more topics in this section, jump to the first topic in the next section $nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)'); if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course) $nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)'); } } } if (startClass) { $('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide"); // if there's no training bar (below the start button), // then we need to add a bottom border to button if (!$("#tb").length) { $('.start-class-link').css({'border-bottom':'1px solid #DADADA'}); } } else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries $('.content-footer.next-class').show(); $('.next-page-link').attr('href','') .removeClass("hide").addClass("disabled") .click(function() { return false; }); $('.next-class-link').attr('href',$nextLink.attr('href')) .removeClass("hide").append($nextLink.html()); $('.next-class-link').find('.new').empty(); } else { $('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide"); } if (!startClass && $prevLink.length) { var prevHref = $prevLink.attr('href'); if (prevHref == SITE_ROOT + 'index.html') { // Don't show Previous when it leads to the homepage } else { $('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide"); } } // If this is a training 'article', there should be no prev/next nav // ... if the grandparent is the "nav" ... and it has no child list items... if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') && !$selListItem.find('li').length) { $('.next-page-link,.prev-page-link').attr('href','').addClass("disabled") .click(function() { return false; }); } } // Set up the course landing pages for Training with class names and descriptions if ($('body.trainingcourse').length) { var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a'); var $classDescriptions = $classLinks.attr('description'); var $olClasses = $('<ol class="class-list"></ol>'); var $liClass; var $imgIcon; var $h2Title; var $pSummary; var $olLessons; var $liLesson; $classLinks.each(function(index) { $liClass = $('<li></li>'); $h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>'); $pSummary = $('<p class="description">' + $(this).attr('description') + '</p>'); $olLessons = $('<ol class="lesson-list"></ol>'); $lessons = $(this).closest('li').find('ul li a'); if ($lessons.length) { $imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>'); $lessons.each(function(index) { $olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>'); }); } else { $imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>'); $pSummary.addClass('article'); } $liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons); $olClasses.append($liClass); }); $('.jd-descr').append($olClasses); } // Set up expand/collapse behavior $('#nav li.nav-section .nav-section-header').click(function() { var section = $(this).closest('li.nav-section'); if (section.hasClass('expanded')) { /* hide me */ // if (section.hasClass('selected') || section.find('li').hasClass('selected')) { // /* but not if myself or my descendents are selected */ // return; // } section.children('ul').slideUp(250, function() { section.closest('li').removeClass('expanded'); resizeNav(); }); } else { /* show me */ // first hide all other siblings var $others = $('li.nav-section.expanded', $(this).closest('ul')); $others.removeClass('expanded').children('ul').slideUp(250); // now expand me section.closest('li').addClass('expanded'); section.children('ul').slideDown(250, function() { resizeNav(); }); } }); $(".scroll-pane").scroll(function(event) { event.preventDefault(); return false; }); /* Resize nav height when window height changes */ $(window).resize(function() { if ($('#side-nav').length == 0) return; var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]'); setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed // make sidenav behave when resizing the window and side-scolling is a concern if (navBarIsFixed) { if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) { updateSideNavPosition(); } else { updateSidenavFullscreenWidth(); } } resizeNav(); }); // Set up fixed navbar var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll $(window).scroll(function(event) { if ($('#side-nav').length == 0) return; if (event.target.nodeName == "DIV") { // Dump scroll event if the target is a DIV, because that means the event is coming // from a scrollable div and so there's no need to make adjustments to our layout return; } var scrollTop = $(window).scrollTop(); var headerHeight = $('#header').outerHeight(); var subheaderHeight = $('#nav-x').outerHeight(); var searchResultHeight = $('#searchResults').is(":visible") ? $('#searchResults').outerHeight() : 0; var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight; // we set the navbar fixed when the scroll position is beyond the height of the site header... var navBarShouldBeFixed = scrollTop > totalHeaderHeight; // ... except if the document content is shorter than the sidenav height. // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing) if ($("#doc-col").height() < $("#side-nav").height()) { navBarShouldBeFixed = false; } var scrollLeft = $(window).scrollLeft(); // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match if (navBarIsFixed && (scrollLeft != prevScrollLeft)) { updateSideNavPosition(); prevScrollLeft = scrollLeft; } // Don't continue if the header is sufficently far away // (to avoid intensive resizing that slows scrolling) if (navBarIsFixed && navBarShouldBeFixed) { return; } if (navBarIsFixed != navBarShouldBeFixed) { if (navBarShouldBeFixed) { // make it fixed var width = $('#devdoc-nav').width(); $('#devdoc-nav') .addClass('fixed') .css({'width':width+'px'}) .prependTo('#body-content'); // add neato "back to top" button $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'}); // update the sidenaav position for side scrolling updateSideNavPosition(); } else { // make it static again $('#devdoc-nav') .removeClass('fixed') .css({'width':'auto','margin':''}) .prependTo('#side-nav'); $('#devdoc-nav a.totop').hide(); } navBarIsFixed = navBarShouldBeFixed; } resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance }); var navBarLeftPos; if ($('#devdoc-nav').length) { setNavBarLeftPos(); } // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away // from the page) $('.nav-section-header').find('a:eq(0)').click(function(evt) { window.location.href = $(this).attr('href'); return false; }); // Set up play-on-hover <video> tags. $('video.play-on-hover').bind('click', function(){ $(this).get(0).load(); // in case the video isn't seekable $(this).get(0).play(); }); // Set up tooltips var TOOLTIP_MARGIN = 10; $('acronym,.tooltip-link').each(function() { var $target = $(this); var $tooltip = $('<div>') .addClass('tooltip-box') .append($target.attr('title')) .hide() .appendTo('body'); $target.removeAttr('title'); $target.hover(function() { // in var targetRect = $target.offset(); targetRect.width = $target.width(); targetRect.height = $target.height(); $tooltip.css({ left: targetRect.left, top: targetRect.top + targetRect.height + TOOLTIP_MARGIN }); $tooltip.addClass('below'); $tooltip.show(); }, function() { // out $tooltip.hide(); }); }); // Set up <h2> deeplinks $('h2').click(function() { var id = $(this).attr('id'); if (id) { document.location.hash = id; } }); //Loads the +1 button var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); // Revise the sidenav widths to make room for the scrollbar // which avoids the visible width from changing each time the bar appears var $sidenav = $("#side-nav"); var sidenav_width = parseInt($sidenav.innerWidth()); $("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller if ($(".scroll-pane").length > 1) { // Check if there's a user preference for the panel heights var cookieHeight = readCookie("reference_height"); if (cookieHeight) { restoreHeight(cookieHeight); } } resizeNav(); /* init the language selector based on user cookie for lang */ loadLangPref(); changeNavLang(getLangPref()); /* setup event handlers to ensure the overflow menu is visible while picking lang */ $("#language select") .mousedown(function() { $("div.morehover").addClass("hover"); }) .blur(function() { $("div.morehover").removeClass("hover"); }); /* some global variable setup */ resizePackagesNav = $("#resize-packages-nav"); classesNav = $("#classes-nav"); devdocNav = $("#devdoc-nav"); var cookiePath = ""; if (location.href.indexOf("/reference/") != -1) { cookiePath = "reference_"; } else if (location.href.indexOf("/guide/") != -1) { cookiePath = "guide_"; } else if (location.href.indexOf("/tools/") != -1) { cookiePath = "tools_"; } else if (location.href.indexOf("/training/") != -1) { cookiePath = "training_"; } else if (location.href.indexOf("/design/") != -1) { cookiePath = "design_"; } else if (location.href.indexOf("/distribute/") != -1) { cookiePath = "distribute_"; } }); function toggleFullscreen(enable) { var delay = 20; var enabled = true; var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]'); if (enable) { // Currently NOT USING fullscreen; enable fullscreen stylesheet.removeAttr('disabled'); $('#nav-swap .fullscreen').removeClass('disabled'); $('#devdoc-nav').css({left:''}); setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch enabled = true; } else { // Currently USING fullscreen; disable fullscreen stylesheet.attr('disabled', 'disabled'); $('#nav-swap .fullscreen').addClass('disabled'); setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch enabled = false; } writeCookie("fullscreen", enabled, null, null); setNavBarLeftPos(); resizeNav(delay); updateSideNavPosition(); setTimeout(initSidenavHeightResize,delay); } function setNavBarLeftPos() { navBarLeftPos = $('#body-content').offset().left; } function updateSideNavPosition() { var newLeft = $(window).scrollLeft() - navBarLeftPos; $('#devdoc-nav').css({left: -newLeft}); $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))}); } // TODO: use $(document).ready instead function addLoadEvent(newfun) { var current = window.onload; if (typeof window.onload != 'function') { window.onload = newfun; } else { window.onload = function() { current(); newfun(); } } } var agent = navigator['userAgent'].toLowerCase(); // If a mobile phone, set flag and do mobile setup if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod (agent.indexOf("blackberry") != -1) || (agent.indexOf("webos") != -1) || (agent.indexOf("mini") != -1)) { // opera mini browsers isMobile = true; } /* loads the lists.js file to the page. Loading this in the head was slowing page load time */ addLoadEvent( function() { var lists = document.createElement("script"); lists.setAttribute("type","text/javascript"); lists.setAttribute("src", toRoot+"reference/lists.js"); document.getElementsByTagName("head")[0].appendChild(lists); } ); addLoadEvent( function() { $("pre:not(.no-pretty-print)").addClass("prettyprint"); prettyPrint(); } ); /* ######### RESIZE THE SIDENAV HEIGHT ########## */ function resizeNav(delay) { var $nav = $("#devdoc-nav"); var $window = $(window); var navHeight; // Get the height of entire window and the total header height. // Then figure out based on scroll position whether the header is visible var windowHeight = $window.height(); var scrollTop = $window.scrollTop(); var headerHeight = $('#header').outerHeight(); var subheaderHeight = $('#nav-x').outerHeight(); var headerVisible = (scrollTop < (headerHeight + subheaderHeight)); // get the height of space between nav and top of window. // Could be either margin or top position, depending on whether the nav is fixed. var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1; // add 1 for the #side-nav bottom margin // Depending on whether the header is visible, set the side nav's height. if (headerVisible) { // The sidenav height grows as the header goes off screen navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin; } else { // Once header is off screen, the nav height is almost full window height navHeight = windowHeight - topMargin; } $scrollPanes = $(".scroll-pane"); if ($scrollPanes.length > 1) { // subtract the height of the api level widget and nav swapper from the available nav height navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true)); $("#swapper").css({height:navHeight + "px"}); if ($("#nav-tree").is(":visible")) { $("#nav-tree").css({height:navHeight}); } var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px"; //subtract 10px to account for drag bar // if the window becomes small enough to make the class panel height 0, // then the package panel should begin to shrink if (parseInt(classesHeight) <= 0) { $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar $("#packages-nav").css({height:navHeight - 10}); } $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'}); $("#classes-nav .jspContainer").css({height:classesHeight}); } else { $nav.height(navHeight); } if (delay) { updateFromResize = true; delayedReInitScrollbars(delay); } else { reInitScrollbars(); } } var updateScrollbars = false; var updateFromResize = false; /* Re-initialize the scrollbars to account for changed nav size. * This method postpones the actual update by a 1/4 second in order to optimize the * scroll performance while the header is still visible, because re-initializing the * scroll panes is an intensive process. */ function delayedReInitScrollbars(delay) { // If we're scheduled for an update, but have received another resize request // before the scheduled resize has occured, just ignore the new request // (and wait for the scheduled one). if (updateScrollbars && updateFromResize) { updateFromResize = false; return; } // We're scheduled for an update and the update request came from this method's setTimeout if (updateScrollbars && !updateFromResize) { reInitScrollbars(); updateScrollbars = false; } else { updateScrollbars = true; updateFromResize = false; setTimeout('delayedReInitScrollbars()',delay); } } /* Re-initialize the scrollbars to account for changed nav size. */ function reInitScrollbars() { var pane = $(".scroll-pane").each(function(){ var api = $(this).data('jsp'); if (!api) { setTimeout(reInitScrollbars,300); return;} api.reinitialise( {verticalGutter:0} ); }); $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller } /* Resize the height of the nav panels in the reference, * and save the new size to a cookie */ function saveNavPanels() { var basePath = getBaseUri(location.pathname); var section = basePath.substring(1,basePath.indexOf("/",1)); writeCookie("height", resizePackagesNav.css("height"), section, null); } function restoreHeight(packageHeight) { $("#resize-packages-nav").height(packageHeight); $("#packages-nav").height(packageHeight); // var classesHeight = navHeight - packageHeight; // $("#classes-nav").css({height:classesHeight}); // $("#classes-nav .jspContainer").css({height:classesHeight}); } /* ######### END RESIZE THE SIDENAV HEIGHT ########## */ /** Scroll the jScrollPane to make the currently selected item visible This is called when the page finished loading. */ function scrollIntoView(nav) { var $nav = $("#"+nav); var element = $nav.jScrollPane({/* ...settings... */}); var api = element.data('jsp'); if ($nav.is(':visible')) { var $selected = $(".selected", $nav); if ($selected.length == 0) return; var selectedOffset = $selected.position().top; if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even // if the current item is close to the bottom api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view // to be 1/4 of the way from the top } } } /* Show popup dialogs */ function showDialog(id) { $dialog = $("#"+id); $dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>'); $dialog.wrapInner('<div/>'); $dialog.removeClass("hide"); } /* ######### COOKIES! ########## */ function readCookie(cookie) { var myCookie = cookie_namespace+"_"+cookie+"="; if (document.cookie) { var index = document.cookie.indexOf(myCookie); if (index != -1) { var valStart = index + myCookie.length; var valEnd = document.cookie.indexOf(";", valStart); if (valEnd == -1) { valEnd = document.cookie.length; } var val = document.cookie.substring(valStart, valEnd); return val; } } return 0; } function writeCookie(cookie, val, section, expiration) { if (val==undefined) return; section = section == null ? "_" : "_"+section+"_"; if (expiration == null) { var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week expiration = date.toGMTString(); } var cookieValue = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/"; document.cookie = cookieValue; } /* ######### END COOKIES! ########## */ /* REMEMBER THE PREVIOUS PAGE FOR EACH TAB function loadLast(cookiePath) { var location = window.location.href; if (location.indexOf("/"+cookiePath+"/") != -1) { return true; } var lastPage = readCookie(cookiePath + "_lastpage"); if (lastPage) { window.location = lastPage; return false; } return true; } $(window).unload(function(){ var path = getBaseUri(location.pathname); if (path.indexOf("/reference/") != -1) { writeCookie("lastpage", path, "reference", null); } else if (path.indexOf("/guide/") != -1) { writeCookie("lastpage", path, "guide", null); } else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) { writeCookie("lastpage", path, "resources", null); } }); */ function toggle(obj, slide) { var ul = $("ul:first", obj); var li = ul.parent(); if (li.hasClass("closed")) { if (slide) { ul.slideDown("fast"); } else { ul.show(); } li.removeClass("closed"); li.addClass("open"); $(".toggle-img", li).attr("title", "hide pages"); } else { ul.slideUp("fast"); li.removeClass("open"); li.addClass("closed"); $(".toggle-img", li).attr("title", "show pages"); } } function buildToggleLists() { $(".toggle-list").each( function(i) { $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>"); $(this).addClass("closed"); }); } /* REFERENCE NAV SWAP */ function getNavPref() { var v = readCookie('reference_nav'); if (v != NAV_PREF_TREE) { v = NAV_PREF_PANELS; } return v; } function chooseDefaultNav() { nav_pref = getNavPref(); if (nav_pref == NAV_PREF_TREE) { $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); } } function swapNav() { if (nav_pref == NAV_PREF_TREE) { nav_pref = NAV_PREF_PANELS; } else { nav_pref = NAV_PREF_TREE; init_default_navtree(toRoot); } var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years writeCookie("nav", nav_pref, "reference", date.toGMTString()); $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); resizeNav(); // Gross nasty hack to make tree view show up upon first swap by setting height manually $("#nav-tree .jspContainer:visible") .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'}); // Another nasty hack to make the scrollbar appear now that we have height resizeNav(); if ($("#nav-tree").is(':visible')) { scrollIntoView("nav-tree"); } else { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); } } /* ############################################ */ /* ########## LOCALIZATION ############ */ /* ############################################ */ function getBaseUri(uri) { var intlUrl = (uri.substring(0,6) == "/intl/"); if (intlUrl) { base = uri.substring(uri.indexOf('intl/')+5,uri.length); base = base.substring(base.indexOf('/')+1, base.length); //alert("intl, returning base url: /" + base); return ("/" + base); } else { //alert("not intl, returning uri as found."); return uri; } } function requestAppendHL(uri) { //append "?hl=<lang> to an outgoing request (such as to blog) var lang = getLangPref(); if (lang) { var q = 'hl=' + lang; uri += '?' + q; window.location = uri; return false; } else { return true; } } function changeNavLang(lang) { var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]"); $links.each(function(i){ // for each link with a translation var $link = $(this); if (lang != "en") { // No need to worry about English, because a language change invokes new request // put the desired language from the attribute as the text $link.text($link.attr(lang+"-lang")) } }); } function changeLangPref(lang, submit) { var date = new Date(); expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years //alert("expires: " + expires) writeCookie("pref_lang", lang, null, expires); // ####### TODO: Remove this condition once we're stable on devsite ####### // This condition is only needed if we still need to support legacy GAE server if (devsite) { // Switch language when on Devsite server if (submit) { $("#setlang").submit(); } } else { // Switch language when on legacy GAE server if (submit) { window.location = getBaseUri(location.pathname); } } } function loadLangPref() { var lang = readCookie("pref_lang"); if (lang != 0) { $("#language").find("option[value='"+lang+"']").attr("selected",true); } } function getLangPref() { var lang = $("#language").find(":selected").attr("value"); if (!lang) { lang = readCookie("pref_lang"); } return (lang != 0) ? lang : 'en'; } /* ########## END LOCALIZATION ############ */ /* Used to hide and reveal supplemental content, such as long code samples. See the companion CSS in android-developer-docs.css */ function toggleContent(obj) { var div = $(obj.parentNode.parentNode); var toggleMe = $(".toggle-content-toggleme",div); if (div.hasClass("closed")) { // if it's closed, open it toggleMe.slideDown(); $(".toggle-content-text", obj).toggle(); div.removeClass("closed").addClass("open"); $(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot + "assets/images/triangle-opened.png"); } else { // if it's open, close it toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow $(".toggle-content-text", obj).toggle(); div.removeClass("open").addClass("closed"); $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot + "assets/images/triangle-closed.png"); }); } return false; } /* New version of expandable content */ function toggleExpandable(link,id) { if($(id).is(':visible')) { $(id).slideUp(); $(link).removeClass('expanded'); } else { $(id).slideDown(); $(link).addClass('expanded'); } } function hideExpandable(ids) { $(ids).slideUp(); $(ids).prev('h4').find('a.expandable').removeClass('expanded'); } /* * Slideshow 1.0 * Used on /index.html and /develop/index.html for carousel * * Sample usage: * HTML - * <div class="slideshow-container"> * <a href="" class="slideshow-prev">Prev</a> * <a href="" class="slideshow-next">Next</a> * <ul> * <li class="item"><img src="images/marquee1.jpg"></li> * <li class="item"><img src="images/marquee2.jpg"></li> * <li class="item"><img src="images/marquee3.jpg"></li> * <li class="item"><img src="images/marquee4.jpg"></li> * </ul> * </div> * * <script type="text/javascript"> * $('.slideshow-container').dacSlideshow({ * auto: true, * btnPrev: '.slideshow-prev', * btnNext: '.slideshow-next' * }); * </script> * * Options: * btnPrev: optional identifier for previous button * btnNext: optional identifier for next button * btnPause: optional identifier for pause button * auto: whether or not to auto-proceed * speed: animation speed * autoTime: time between auto-rotation * easing: easing function for transition * start: item to select by default * scroll: direction to scroll in * pagination: whether or not to include dotted pagination * */ (function($) { $.fn.dacSlideshow = function(o) { //Options - see above o = $.extend({ btnPrev: null, btnNext: null, btnPause: null, auto: true, speed: 500, autoTime: 12000, easing: null, start: 0, scroll: 1, pagination: true }, o || {}); //Set up a carousel for each return this.each(function() { var running = false; var animCss = o.vertical ? "top" : "left"; var sizeCss = o.vertical ? "height" : "width"; var div = $(this); var ul = $("ul", div); var tLi = $("li", ul); var tl = tLi.size(); var timer = null; var li = $("li", ul); var itemLength = li.size(); var curr = o.start; li.css({float: o.vertical ? "none" : "left"}); ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); div.css({position: "relative", "z-index": "2", left: "0px"}); var liSize = o.vertical ? height(li) : width(li); var ulSize = liSize * itemLength; var divSize = liSize; li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); //Pagination if (o.pagination) { var pagination = $("<div class='pagination'></div>"); var pag_ul = $("<ul></ul>"); if (tl > 1) { for (var i=0;i<tl;i++) { var li = $("<li>"+i+"</li>"); pag_ul.append(li); if (i==o.start) li.addClass('active'); li.click(function() { go(parseInt($(this).text())); }) } pagination.append(pag_ul); div.append(pagination); } } //Previous button if(o.btnPrev) $(o.btnPrev).click(function(e) { e.preventDefault(); return go(curr-o.scroll); }); //Next button if(o.btnNext) $(o.btnNext).click(function(e) { e.preventDefault(); return go(curr+o.scroll); }); //Pause button if(o.btnPause) $(o.btnPause).click(function(e) { e.preventDefault(); if ($(this).hasClass('paused')) { startRotateTimer(); } else { pauseRotateTimer(); } }); //Auto rotation if(o.auto) startRotateTimer(); function startRotateTimer() { clearInterval(timer); timer = setInterval(function() { if (curr == tl-1) { go(0); } else { go(curr+o.scroll); } }, o.autoTime); $(o.btnPause).removeClass('paused'); } function pauseRotateTimer() { clearInterval(timer); $(o.btnPause).addClass('paused'); } //Go to an item function go(to) { if(!running) { if(to<0) { to = itemLength-1; } else if (to>itemLength-1) { to = 0; } curr = to; running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { running = false; } ); $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength && o.btnNext) || [] ).addClass("disabled"); var nav_items = $('li', pagination); nav_items.removeClass('active'); nav_items.eq(to).addClass('active'); } if(o.auto) startRotateTimer(); return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery); /* * dacSlideshow 1.0 * Used on develop/index.html for side-sliding tabs * * Sample usage: * HTML - * <div class="slideshow-container"> * <a href="" class="slideshow-prev">Prev</a> * <a href="" class="slideshow-next">Next</a> * <ul> * <li class="item"><img src="images/marquee1.jpg"></li> * <li class="item"><img src="images/marquee2.jpg"></li> * <li class="item"><img src="images/marquee3.jpg"></li> * <li class="item"><img src="images/marquee4.jpg"></li> * </ul> * </div> * * <script type="text/javascript"> * $('.slideshow-container').dacSlideshow({ * auto: true, * btnPrev: '.slideshow-prev', * btnNext: '.slideshow-next' * }); * </script> * * Options: * btnPrev: optional identifier for previous button * btnNext: optional identifier for next button * auto: whether or not to auto-proceed * speed: animation speed * autoTime: time between auto-rotation * easing: easing function for transition * start: item to select by default * scroll: direction to scroll in * pagination: whether or not to include dotted pagination * */ (function($) { $.fn.dacTabbedList = function(o) { //Options - see above o = $.extend({ speed : 250, easing: null, nav_id: null, frame_id: null }, o || {}); //Set up a carousel for each return this.each(function() { var curr = 0; var running = false; var animCss = "margin-left"; var sizeCss = "width"; var div = $(this); var nav = $(o.nav_id, div); var nav_li = $("li", nav); var nav_size = nav_li.size(); var frame = div.find(o.frame_id); var content_width = $(frame).find('ul').width(); //Buttons $(nav_li).click(function(e) { go($(nav_li).index($(this))); }) //Go to an item function go(to) { if(!running) { curr = to; running = true; frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing, function() { running = false; } ); nav_li.removeClass('active'); nav_li.eq(to).addClass('active'); } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery); /* ######################################################## */ /* ################ SEARCH SUGGESTIONS ################## */ /* ######################################################## */ var gSelectedIndex = -1; var gSelectedID = -1; var gMatches = new Array(); var gLastText = ""; var ROW_COUNT = 20; var gInitialized = false; function set_item_selected($li, selected) { if (selected) { $li.attr('class','jd-autocomplete jd-selected'); } else { $li.attr('class','jd-autocomplete'); } } function set_item_values(toroot, $li, match) { var $link = $('a',$li); $link.html(match.__hilabel || match.label); $link.attr('href',toroot + match.link); } function sync_selection_table(toroot) { var $list = $("#search_filtered"); var $li; //list item jquery object var i; //list item iterator gSelectedID = -1; //initialize the table; draw it for the first time (but not visible). if (!gInitialized) { for (i=0; i<ROW_COUNT; i++) { var $li = $("<li class='jd-autocomplete'></li>"); $list.append($li); $li.mousedown(function() { window.location = this.firstChild.getAttribute("href"); }); $li.mouseover(function() { $('#search_filtered li').removeClass('jd-selected'); $(this).addClass('jd-selected'); gSelectedIndex = $('#search_filtered li').index(this); }); $li.append('<a></a>'); } gInitialized = true; } //if we have results, make the table visible and initialize result info if (gMatches.length > 0) { $('#search_filtered_div').removeClass('no-display'); var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT; for (i=0; i<N; i++) { $li = $('#search_filtered li:nth-child('+(i+1)+')'); $li.attr('class','show-item'); set_item_values(toroot, $li, gMatches[i]); set_item_selected($li, i == gSelectedIndex); if (i == gSelectedIndex) { gSelectedID = gMatches[i].id; } } //start hiding rows that are no longer matches for (; i<ROW_COUNT; i++) { $li = $('#search_filtered li:nth-child('+(i+1)+')'); $li.attr('class','no-display'); } //if there are more results we're not showing, so say so. /* if (gMatches.length > ROW_COUNT) { li = list.rows[ROW_COUNT]; li.className = "show-item"; c1 = li.cells[0]; c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more"; } else { list.rows[ROW_COUNT].className = "hide-item"; }*/ //if we have no results, hide the table } else { $('#search_filtered_div').addClass('no-display'); } } function search_changed(e, kd, toroot) { var search = document.getElementById("search_autocomplete"); var text = search.value.replace(/(^ +)|( +$)/g, ''); // show/hide the close button if (text != '') { $(".search .close").removeClass("hide"); } else { $(".search .close").addClass("hide"); } // 13 = enter if (e.keyCode == 13) { $('#search_filtered_div').addClass('no-display'); if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) { if ($("#searchResults").is(":hidden")) { // if results aren't showing, return true to allow search to execute return true; } else { // otherwise, results are already showing, so allow ajax to auto refresh the results // and ignore this Enter press to avoid the reload. return false; } } else if (kd && gSelectedIndex >= 0) { window.location = toroot + gMatches[gSelectedIndex].link; return false; } } // 38 -- arrow up else if (kd && (e.keyCode == 38)) { if (gSelectedIndex >= 0) { $('#search_filtered li').removeClass('jd-selected'); gSelectedIndex--; $('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected'); } return false; } // 40 -- arrow down else if (kd && (e.keyCode == 40)) { if (gSelectedIndex < gMatches.length-1 && gSelectedIndex < ROW_COUNT-1) { $('#search_filtered li').removeClass('jd-selected'); gSelectedIndex++; $('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected'); } return false; } else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) { gMatches = new Array(); matchedCount = 0; gSelectedIndex = -1; for (var i=0; i<DATA.length; i++) { var s = DATA[i]; if (text.length != 0 && s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) { gMatches[matchedCount] = s; matchedCount++; } } rank_autocomplete_results(text); for (var i=0; i<gMatches.length; i++) { var s = gMatches[i]; if (gSelectedID == s.id) { gSelectedIndex = i; } } highlight_autocomplete_result_labels(text); sync_selection_table(toroot); return true; // allow the event to bubble up to the search api } } function rank_autocomplete_results(query) { query = query || ''; if (!gMatches || !gMatches.length) return; // helper function that gets the last occurence index of the given regex // in the given string, or -1 if not found var _lastSearch = function(s, re) { if (s == '') return -1; var l = -1; var tmp; while ((tmp = s.search(re)) >= 0) { if (l < 0) l = 0; l += tmp; s = s.substr(tmp + 1); } return l; }; // helper function that counts the occurrences of a given character in // a given string var _countChar = function(s, c) { var n = 0; for (var i=0; i<s.length; i++) if (s.charAt(i) == c) ++n; return n; }; var queryLower = query.toLowerCase(); var queryAlnum = (queryLower.match(/\w+/) || [''])[0]; var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum); var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b'); var _resultScoreFn = function(result) { // scores are calculated based on exact and prefix matches, // and then number of path separators (dots) from the last // match (i.e. favoring classes and deep package names) var score = 1.0; var labelLower = result.label.toLowerCase(); var t; t = _lastSearch(labelLower, partExactAlnumRE); if (t >= 0) { // exact part match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 200 / (partsAfter + 1); } else { t = _lastSearch(labelLower, partPrefixAlnumRE); if (t >= 0) { // part prefix match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 20 / (partsAfter + 1); } } return score; }; for (var i=0; i<gMatches.length; i++) { gMatches[i].__resultScore = _resultScoreFn(gMatches[i]); } gMatches.sort(function(a,b){ var n = b.__resultScore - a.__resultScore; if (n == 0) // lexicographical sort if scores are the same n = (a.label < b.label) ? -1 : 1; return n; }); } function highlight_autocomplete_result_labels(query) { query = query || ''; if (!gMatches || !gMatches.length) return; var queryLower = query.toLowerCase(); var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0]; var queryRE = new RegExp( '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig'); for (var i=0; i<gMatches.length; i++) { gMatches[i].__hilabel = gMatches[i].label.replace( queryRE, '<b>$1</b>'); } } function search_focus_changed(obj, focused) { if (!focused) { if(obj.value == ""){ $(".search .close").addClass("hide"); } document.getElementById("search_filtered_div").className = "no-display"; } } function submit_search() { var query = document.getElementById('search_autocomplete').value; location.hash = 'q=' + query; loadSearchResults(); $("#searchResults").slideDown('slow'); return false; } function hideResults() { $("#searchResults").slideUp(); $(".search .close").addClass("hide"); location.hash = ''; $("#search_autocomplete").val("").blur(); // reset the ajax search callback to nothing, so results don't appear unless ENTER searchControl.setSearchStartingCallback(this, function(control, searcher, query) {}); return false; } /* ########################################################## */ /* ################ CUSTOM SEARCH ENGINE ################## */ /* ########################################################## */ google.load('search', '1'); var searchControl; function loadSearchResults() { document.getElementById("search_autocomplete").style.color = "#000"; // create search control searchControl = new google.search.SearchControl(); // use our existing search form and use tabs when multiple searchers are used drawOptions = new google.search.DrawOptions(); drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED); drawOptions.setInput(document.getElementById("search_autocomplete")); // configure search result options searchOptions = new google.search.SearcherOptions(); searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN); // configure each of the searchers, for each tab devSiteSearcher = new google.search.WebSearch(); devSiteSearcher.setUserDefinedLabel("All"); devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u"); designSearcher = new google.search.WebSearch(); designSearcher.setUserDefinedLabel("Design"); designSearcher.setSiteRestriction("http://developer.android.com/design/"); trainingSearcher = new google.search.WebSearch(); trainingSearcher.setUserDefinedLabel("Training"); trainingSearcher.setSiteRestriction("http://developer.android.com/training/"); guidesSearcher = new google.search.WebSearch(); guidesSearcher.setUserDefinedLabel("Guides"); guidesSearcher.setSiteRestriction("http://developer.android.com/guide/"); referenceSearcher = new google.search.WebSearch(); referenceSearcher.setUserDefinedLabel("Reference"); referenceSearcher.setSiteRestriction("http://developer.android.com/reference/"); googleSearcher = new google.search.WebSearch(); googleSearcher.setUserDefinedLabel("Google Services"); googleSearcher.setSiteRestriction("http://developer.android.com/google/"); blogSearcher = new google.search.WebSearch(); blogSearcher.setUserDefinedLabel("Blog"); blogSearcher.setSiteRestriction("http://android-developers.blogspot.com"); // add each searcher to the search control searchControl.addSearcher(devSiteSearcher, searchOptions); searchControl.addSearcher(designSearcher, searchOptions); searchControl.addSearcher(trainingSearcher, searchOptions); searchControl.addSearcher(guidesSearcher, searchOptions); searchControl.addSearcher(referenceSearcher, searchOptions); searchControl.addSearcher(googleSearcher, searchOptions); searchControl.addSearcher(blogSearcher, searchOptions); // configure result options searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET); searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF); searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT); searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING); // upon ajax search, refresh the url and search title searchControl.setSearchStartingCallback(this, function(control, searcher, query) { updateResultTitle(query); var query = document.getElementById('search_autocomplete').value; location.hash = 'q=' + query; }); // draw the search results box searchControl.draw(document.getElementById("leftSearchControl"), drawOptions); // get query and execute the search searchControl.execute(decodeURI(getQuery(location.hash))); document.getElementById("search_autocomplete").focus(); addTabListeners(); } // End of loadSearchResults google.setOnLoadCallback(function(){ if (location.hash.indexOf("q=") == -1) { // if there's no query in the url, don't search and make sure results are hidden $('#searchResults').hide(); return; } else { // first time loading search results for this page $('#searchResults').slideDown('slow'); $(".search .close").removeClass("hide"); loadSearchResults(); } }, true); // when an event on the browser history occurs (back, forward, load) requery hash and do search $(window).hashchange( function(){ // Exit if the hash isn't a search query or there's an error in the query if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) { // If the results pane is open, close it. if (!$("#searchResults").is(":hidden")) { hideResults(); } return; } // Otherwise, we have a search to do var query = decodeURI(getQuery(location.hash)); searchControl.execute(query); $('#searchResults').slideDown('slow'); $("#search_autocomplete").focus(); $(".search .close").removeClass("hide"); updateResultTitle(query); }); function updateResultTitle(query) { $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>"); } // forcefully regain key-up event control (previously jacked by search api) $("#search_autocomplete").keyup(function(event) { return search_changed(event, false, toRoot); }); // add event listeners to each tab so we can track the browser history function addTabListeners() { var tabHeaders = $(".gsc-tabHeader"); for (var i = 0; i < tabHeaders.length; i++) { $(tabHeaders[i]).attr("id",i).click(function() { /* // make a copy of the page numbers for the search left pane setTimeout(function() { // remove any residual page numbers $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove(); // move the page numbers to the left position; make a clone, // because the element is drawn to the DOM only once // and because we're going to remove it (previous line), // we need it to be available to move again as the user navigates $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible') .clone().appendTo('#searchResults .gsc-tabsArea'); }, 200); */ }); } setTimeout(function(){$(tabHeaders[0]).click()},200); } function getQuery(hash) { var queryParts = hash.split('='); return queryParts[1]; } /* returns the given string with all HTML brackets converted to entities TODO: move this to the site's JS library */ function escapeHTML(string) { return string.replace(/</g,"&lt;") .replace(/>/g,"&gt;"); } /* ######################################################## */ /* ################# JAVADOC REFERENCE ################### */ /* ######################################################## */ /* Initialize some droiddoc stuff, but only if we're in the reference */ if (location.pathname.indexOf("/reference")) { if(!location.pathname.indexOf("/reference-gms/packages.html") && !location.pathname.indexOf("/reference-gcm/packages.html") && !location.pathname.indexOf("/reference/com/google") == 0) { $(document).ready(function() { // init available apis based on user pref changeApiLevel(); initSidenavHeightResize() }); } } var API_LEVEL_COOKIE = "api_level"; var minLevel = 1; var maxLevel = 1; /******* SIDENAV DIMENSIONS ************/ function initSidenavHeightResize() { // Change the drag bar size to nicely fit the scrollbar positions var $dragBar = $(".ui-resizable-s"); $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"}); $( "#resize-packages-nav" ).resizable({ containment: "#nav-panels", handles: "s", alsoResize: "#packages-nav", resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */ stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */ }); } function updateSidenavFixedWidth() { if (!navBarIsFixed) return; $('#devdoc-nav').css({ 'width' : $('#side-nav').css('width'), 'margin' : $('#side-nav').css('margin') }); $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'}); initSidenavHeightResize(); } function updateSidenavFullscreenWidth() { if (!navBarIsFixed) return; $('#devdoc-nav').css({ 'width' : $('#side-nav').css('width'), 'margin' : $('#side-nav').css('margin') }); $('#devdoc-nav .totop').css({'left': 'inherit'}); initSidenavHeightResize(); } function buildApiLevelSelector() { maxLevel = SINCE_DATA.length; var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE)); userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default minLevel = parseInt($("#doc-api-level").attr("class")); // Handle provisional api levels; the provisional level will always be the highest possible level // Provisional api levels will also have a length; other stuff that's just missing a level won't, // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class) if (isNaN(minLevel) && minLevel.length) { minLevel = maxLevel; } var select = $("#apiLevelSelector").html("").change(changeApiLevel); for (var i = maxLevel-1; i >= 0; i--) { var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]); // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames) select.append(option); } // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true) var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0); selectedLevelItem.setAttribute('selected',true); } function changeApiLevel() { maxLevel = SINCE_DATA.length; var selectedLevel = maxLevel; selectedLevel = parseInt($("#apiLevelSelector option:selected").val()); toggleVisisbleApis(selectedLevel, "body"); var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years var expiration = date.toGMTString(); writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration); if (selectedLevel < minLevel) { var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class"; $("#naMessage").show().html("<div><p><strong>This " + thing + " requires API level " + minLevel + " or higher.</strong></p>" + "<p>This document is hidden because your selected API level for the documentation is " + selectedLevel + ". You can change the documentation API level with the selector " + "above the left navigation.</p>" + "<p>For more information about specifying the API level your app requires, " + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'" + ">Supporting Different Platform Versions</a>.</p>" + "<input type='button' value='OK, make this page visible' " + "title='Change the API level to " + minLevel + "' " + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />" + "</div>"); } else { $("#naMessage").hide(); } } function toggleVisisbleApis(selectedLevel, context) { var apis = $(".api",context); apis.each(function(i) { var obj = $(this); var className = obj.attr("class"); var apiLevelIndex = className.lastIndexOf("-")+1; var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex); apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length; var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex); if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail return; } apiLevel = parseInt(apiLevel); // Handle provisional api levels; if this item's level is the provisional one, set it to the max var selectedLevelNum = parseInt(selectedLevel) var apiLevelNum = parseInt(apiLevel); if (isNaN(apiLevelNum)) { apiLevelNum = maxLevel; } // Grey things out that aren't available and give a tooltip title if (apiLevelNum > selectedLevelNum) { obj.addClass("absent").attr("title","Requires API Level \"" + apiLevel + "\" or higher"); } else obj.removeClass("absent").removeAttr("title"); }); } /* ################# SIDENAV TREE VIEW ################### */ function new_node(me, mom, text, link, children_data, api_level) { var node = new Object(); node.children = Array(); node.children_data = children_data; node.depth = mom.depth + 1; node.li = document.createElement("li"); mom.get_children_ul().appendChild(node.li); node.label_div = document.createElement("div"); node.label_div.className = "label"; if (api_level != null) { $(node.label_div).addClass("api"); $(node.label_div).addClass("api-level-"+api_level); } node.li.appendChild(node.label_div); if (children_data != null) { node.expand_toggle = document.createElement("a"); node.expand_toggle.href = "javascript:void(0)"; node.expand_toggle.onclick = function() { if (node.expanded) { $(node.get_children_ul()).slideUp("fast"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.expanded = false; } else { expand_node(me, node); } }; node.label_div.appendChild(node.expand_toggle); node.plus_img = document.createElement("img"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.plus_img.className = "plus"; node.plus_img.width = "8"; node.plus_img.border = "0"; node.expand_toggle.appendChild(node.plus_img); node.expanded = false; } var a = document.createElement("a"); node.label_div.appendChild(a); node.label = document.createTextNode(text); a.appendChild(node.label); if (link) { a.href = me.toroot + link; } else { if (children_data != null) { a.className = "nolink"; a.href = "javascript:void(0)"; a.onclick = node.expand_toggle.onclick; // This next line shouldn't be necessary. I'll buy a beer for the first // person who figures out how to remove this line and have the link // toggle shut on the first try. --joeo@android.com node.expanded = false; } } node.children_ul = null; node.get_children_ul = function() { if (!node.children_ul) { node.children_ul = document.createElement("ul"); node.children_ul.className = "children_ul"; node.children_ul.style.display = "none"; node.li.appendChild(node.children_ul); } return node.children_ul; }; return node; } function expand_node(me, node) { if (node.children_data && !node.expanded) { if (node.children_visited) { $(node.get_children_ul()).slideDown("fast"); } else { get_node(me, node); if ($(node.label_div).hasClass("absent")) { $(node.get_children_ul()).addClass("absent"); } $(node.get_children_ul()).slideDown("fast"); } node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png"; node.expanded = true; // perform api level toggling because new nodes are new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } } function get_node(me, mom) { mom.children_visited = true; for (var i in mom.children_data) { var node_data = mom.children_data[i]; mom.children[i] = new_node(me, mom, node_data[0], node_data[1], node_data[2], node_data[3]); } } function this_page_relative(toroot) { var full = document.location.pathname; var file = ""; if (toroot.substr(0, 1) == "/") { if (full.substr(0, toroot.length) == toroot) { return full.substr(toroot.length); } else { // the file isn't under toroot. Fail. return null; } } else { if (toroot != "./") { toroot = "./" + toroot; } do { if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") { var pos = full.lastIndexOf("/"); file = full.substr(pos) + file; full = full.substr(0, pos); toroot = toroot.substr(0, toroot.length-3); } } while (toroot != "" && toroot != "/"); return file.substr(1); } } function find_page(url, data) { var nodes = data; var result = null; for (var i in nodes) { var d = nodes[i]; if (d[1] == url) { return new Array(i); } else if (d[2] != null) { result = find_page(url, d[2]); if (result != null) { return (new Array(i).concat(result)); } } } return null; } function init_default_navtree(toroot) { init_navtree("tree-list", toroot, NAVTREE_DATA); // perform api level toggling because because the whole tree is new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } function init_navtree(navtree_id, toroot, root_nodes) { var me = new Object(); me.toroot = toroot; me.node = new Object(); me.node.li = document.getElementById(navtree_id); me.node.children_data = root_nodes; me.node.children = new Array(); me.node.children_ul = document.createElement("ul"); me.node.get_children_ul = function() { return me.node.children_ul; }; //me.node.children_ul.className = "children_ul"; me.node.li.appendChild(me.node.children_ul); me.node.depth = 0; get_node(me, me.node); me.this_page = this_page_relative(toroot); me.breadcrumbs = find_page(me.this_page, root_nodes); if (me.breadcrumbs != null && me.breadcrumbs.length != 0) { var mom = me.node; for (var i in me.breadcrumbs) { var j = me.breadcrumbs[i]; mom = mom.children[j]; expand_node(me, mom); } mom.label_div.className = mom.label_div.className + " selected"; addLoadEvent(function() { scrollIntoView("nav-tree"); }); } } /* TODO: eliminate redundancy with non-google functions */ function init_google_navtree(navtree_id, toroot, root_nodes) { var me = new Object(); me.toroot = toroot; me.node = new Object(); me.node.li = document.getElementById(navtree_id); me.node.children_data = root_nodes; me.node.children = new Array(); me.node.children_ul = document.createElement("ul"); me.node.get_children_ul = function() { return me.node.children_ul; }; //me.node.children_ul.className = "children_ul"; me.node.li.appendChild(me.node.children_ul); me.node.depth = 0; get_google_node(me, me.node); } function new_google_node(me, mom, text, link, children_data, api_level) { var node = new Object(); var child; node.children = Array(); node.children_data = children_data; node.depth = mom.depth + 1; node.get_children_ul = function() { if (!node.children_ul) { node.children_ul = document.createElement("ul"); node.children_ul.className = "tree-list-children"; node.li.appendChild(node.children_ul); } return node.children_ul; }; node.li = document.createElement("li"); mom.get_children_ul().appendChild(node.li); if(link) { child = document.createElement("a"); } else { child = document.createElement("span"); child.className = "tree-list-subtitle"; } if (children_data != null) { node.li.className="nav-section"; node.label_div = document.createElement("div"); node.label_div.className = "nav-section-header-ref"; node.li.appendChild(node.label_div); get_google_node(me, node); node.label_div.appendChild(child); } else { node.li.appendChild(child); } if(link) { child.href = me.toroot + link; } node.label = document.createTextNode(text); child.appendChild(node.label); node.children_ul = null; return node; } function get_google_node(me, mom) { mom.children_visited = true; var linkText; for (var i in mom.children_data) { var node_data = mom.children_data[i]; linkText = node_data[0]; if(linkText.match("^"+"com.google.android")=="com.google.android"){ linkText = linkText.substr(19, linkText.length); } mom.children[i] = new_google_node(me, mom, linkText, node_data[1], node_data[2], node_data[3]); } } function showGoogleRefTree() { init_default_google_navtree(toRoot); init_default_gcm_navtree(toRoot); resizeNav(); } function init_default_google_navtree(toroot) { init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA); } function init_default_gcm_navtree(toroot) { init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA); } /* TOGGLE INHERITED MEMBERS */ /* Toggle an inherited class (arrow toggle) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleInherited(linkObj, expand) { var base = linkObj.getAttribute("id"); var list = document.getElementById(base + "-list"); var summary = document.getElementById(base + "-summary"); var trigger = document.getElementById(base + "-trigger"); var a = $(linkObj); if ( (expand == null && a.hasClass("closed")) || expand ) { list.style.display = "none"; summary.style.display = "block"; trigger.src = toRoot + "assets/images/triangle-opened.png"; a.removeClass("closed"); a.addClass("opened"); } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) { list.style.display = "block"; summary.style.display = "none"; trigger.src = toRoot + "assets/images/triangle-closed.png"; a.removeClass("opened"); a.addClass("closed"); } return false; } /* Toggle all inherited classes in a single table (e.g. all inherited methods) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleAllInherited(linkObj, expand) { var a = $(linkObj); var table = $(a.parent().parent().parent()); // ugly way to get table/tbody var expandos = $(".jd-expando-trigger", table); if ( (expand == null && a.text() == "[Expand]") || expand ) { expandos.each(function(i) { toggleInherited(this, true); }); a.text("[Collapse]"); } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) { expandos.each(function(i) { toggleInherited(this, false); }); a.text("[Expand]"); } return false; } /* Toggle all inherited members in the class (link in the class title) */ function toggleAllClassInherited() { var a = $("#toggleAllClassInherited"); // get toggle link from class title var toggles = $(".toggle-all", $("#body-content")); if (a.text() == "[Expand All]") { toggles.each(function(i) { toggleAllInherited(this, true); }); a.text("[Collapse All]"); } else { toggles.each(function(i) { toggleAllInherited(this, false); }); a.text("[Expand All]"); } return false; } /* Expand all inherited members in the class. Used when initiating page search */ function ensureAllInheritedExpanded() { var toggles = $(".toggle-all", $("#body-content")); toggles.each(function(i) { toggleAllInherited(this, true); }); $("#toggleAllClassInherited").text("[Collapse All]"); } /* HANDLE KEY EVENTS * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search) */ var agent = navigator['userAgent'].toLowerCase(); var mac = agent.indexOf("macintosh") != -1; $(document).keydown( function(e) { var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key if (control && e.which == 70) { // 70 is "F" ensureAllInheritedExpanded(); } });
JavaScript
$(document).ready(function() { // prep nav expandos var pagePath = document.location.pathname; if (pagePath.indexOf(SITE_ROOT) == 0) { pagePath = pagePath.substr(SITE_ROOT.length); if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') { pagePath += 'index.html'; } } if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') { // If running locally, SITE_ROOT will be a relative path, so account for that by // finding the relative URL to this page. This will allow us to find links on the page // leading back to this page. var pathParts = pagePath.split('/'); var relativePagePathParts = []; var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3; for (var i = 0; i < upDirs; i++) { relativePagePathParts.push('..'); } for (var i = 0; i < upDirs; i++) { relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]); } relativePagePathParts.push(pathParts[pathParts.length - 1]); pagePath = relativePagePathParts.join('/'); } else { // Otherwise the page path should be an absolute URL. pagePath = SITE_ROOT + pagePath; } // select current page in sidenav and set up prev/next links if they exist var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]'); if ($selNavLink.length) { $selListItem = $selNavLink.closest('li'); $selListItem.addClass('selected'); $selListItem.closest('li>ul').addClass('expanded'); // set up prev links var $prevLink = []; var $prevListItem = $selListItem.prev('li'); if ($prevListItem.length) { if ($prevListItem.hasClass('nav-section')) { // jump to last topic of previous section $prevLink = $prevListItem.find('a:last'); } else { // jump to previous topic in this section $prevLink = $prevListItem.find('a:eq(0)'); } } else { // jump to this section's index page (if it exists) $prevLink = $selListItem.parents('li').find('a'); } if ($prevLink.length) { var prevHref = $prevLink.attr('href'); if (prevHref == SITE_ROOT + 'index.html') { // Don't show Previous when it leads to the homepage $('.prev-page-link').hide(); } else { $('.prev-page-link').attr('href', prevHref).show(); } } else { $('.prev-page-link').hide(); } // set up next links var $nextLink = []; if ($selListItem.hasClass('nav-section')) { // we're on an index page, jump to the first topic $nextLink = $selListItem.find('ul').find('a:eq(0)') } else { // jump to the next topic in this section (if it exists) $nextLink = $selListItem.next('li').find('a:eq(0)'); if (!$nextLink.length) { // no more topics in this section, jump to the first topic in the next section $nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)'); } } if ($nextLink.length) { $('.next-page-link').attr('href', $nextLink.attr('href')).show(); } else { $('.next-page-link').hide(); } } // Set up expand/collapse behavior $('.nav-y li').has('ul').click(function() { if ($(this).hasClass('expanded')) { return; } // hide other var $old = $('.nav-y li.expanded'); if ($old.length) { var $oldUl = $old.children('ul'); $oldUl.css('height', $oldUl.height() + 'px'); window.setTimeout(function() { $oldUl .addClass('animate-height') .css('height', ''); }, 0); $old.removeClass('expanded'); } // show me $(this).addClass('expanded'); var $ul = $(this).children('ul'); var expandedHeight = $ul.height(); $ul .removeClass('animate-height') .css('height', 0); window.setTimeout(function() { $ul .addClass('animate-height') .css('height', expandedHeight + 'px'); }, 0); }); // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away // from the page) $('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) { window.location.href = $(this).attr('href'); return false; }); // Set up play-on-hover <video> tags. $('video.play-on-hover').bind('click', function(){ $(this).get(0).load(); // in case the video isn't seekable $(this).get(0).play(); }); // Set up tooltips var TOOLTIP_MARGIN = 10; $('acronym').each(function() { var $target = $(this); var $tooltip = $('<div>') .addClass('tooltip-box') .text($target.attr('title')) .hide() .appendTo('body'); $target.removeAttr('title'); $target.hover(function() { // in var targetRect = $target.offset(); targetRect.width = $target.width(); targetRect.height = $target.height(); $tooltip.css({ left: targetRect.left, top: targetRect.top + targetRect.height + TOOLTIP_MARGIN }); $tooltip.addClass('below'); $tooltip.show(); }, function() { // out $tooltip.hide(); }); }); // Set up <h2> deeplinks $('h2').click(function() { var id = $(this).attr('id'); if (id) { document.location.hash = id; } }); // Set up fixed navbar var navBarIsFixed = false; $(window).scroll(function() { var scrollTop = $(window).scrollTop(); var navBarShouldBeFixed = (scrollTop > (100 - 40)); if (navBarIsFixed != navBarShouldBeFixed) { if (navBarShouldBeFixed) { $('#nav') .addClass('fixed') .prependTo('#page-container'); } else { $('#nav') .removeClass('fixed') .prependTo('#nav-container'); } navBarIsFixed = navBarShouldBeFixed; } }); });
JavaScript
var classesNav; var devdocNav; var sidenav; var cookie_namespace = 'android_developer'; var NAV_PREF_TREE = "tree"; var NAV_PREF_PANELS = "panels"; var nav_pref; var isMobile = false; // true if mobile, so we can adjust some layout var basePath = getBaseUri(location.pathname); var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1)); /****** ON LOAD SET UP STUFF *********/ var navBarIsFixed = false; $(document).ready(function() { if (devsite) { // move the lang selector into the overflow menu $("#moremenu .mid div.header:last").after($("#language").detach()); } // init the fullscreen toggle click event $('#nav-swap .fullscreen').click(function(){ if ($(this).hasClass('disabled')) { toggleFullscreen(true); } else { toggleFullscreen(false); } }); // initialize the divs with custom scrollbars $('.scroll-pane').jScrollPane( {verticalGutter:0} ); // add HRs below all H2s (except for a few other h2 variants) $('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>'); // set search's onkeyup handler here so we can show suggestions // even while search results are visible $("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)}); // set up the search close button $('.search .close').click(function() { $searchInput = $('#search_autocomplete'); $searchInput.attr('value', ''); $(this).addClass("hide"); $("#search-container").removeClass('active'); $("#search_autocomplete").blur(); search_focus_changed($searchInput.get(), false); // see search_autocomplete.js hideResults(); // see search_autocomplete.js }); $('.search').click(function() { if (!$('#search_autocomplete').is(":focused")) { $('#search_autocomplete').focus(); } }); // Set up quicknav var quicknav_open = false; $("#btn-quicknav").click(function() { if (quicknav_open) { $(this).removeClass('active'); quicknav_open = false; collapse(); } else { $(this).addClass('active'); quicknav_open = true; expand(); } }) var expand = function() { $('#header-wrap').addClass('quicknav'); $('#quicknav').stop().show().animate({opacity:'1'}); } var collapse = function() { $('#quicknav').stop().animate({opacity:'0'}, 100, function() { $(this).hide(); $('#header-wrap').removeClass('quicknav'); }); } //Set up search $("#search_autocomplete").focus(function() { $("#search-container").addClass('active'); }) $("#search-container").mouseover(function() { $("#search-container").addClass('active'); $("#search_autocomplete").focus(); }) $("#search-container").mouseout(function() { if ($("#search_autocomplete").is(":focus")) return; if ($("#search_autocomplete").val() == '') { setTimeout(function(){ $("#search-container").removeClass('active'); $("#search_autocomplete").blur(); },250); } }) $("#search_autocomplete").blur(function() { if ($("#search_autocomplete").val() == '') { $("#search-container").removeClass('active'); } }) // prep nav expandos var pagePath = document.location.pathname; // account for intl docs by removing the intl/*/ path if (pagePath.indexOf("/intl/") == 0) { pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last / } if (pagePath.indexOf(SITE_ROOT) == 0) { if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') { pagePath += 'index.html'; } } if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') { // If running locally, SITE_ROOT will be a relative path, so account for that by // finding the relative URL to this page. This will allow us to find links on the page // leading back to this page. var pathParts = pagePath.split('/'); var relativePagePathParts = []; var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3; for (var i = 0; i < upDirs; i++) { relativePagePathParts.push('..'); } for (var i = 0; i < upDirs; i++) { relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]); } relativePagePathParts.push(pathParts[pathParts.length - 1]); pagePath = relativePagePathParts.join('/'); } else { // Otherwise the page path is already an absolute URL } // select current page in sidenav and set up prev/next links if they exist var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]'); var $selListItem; if ($selNavLink.length) { $selListItem = $selNavLink.closest('li'); $selListItem.addClass('selected'); // Traverse up the tree and expand all parent nav-sections $selNavLink.parents('li.nav-section').each(function() { $(this).addClass('expanded'); $(this).children('ul').show(); }); // set up prev links var $prevLink = []; var $prevListItem = $selListItem.prev('li'); var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true : false; // navigate across topic boundaries only in design docs if ($prevListItem.length) { if ($prevListItem.hasClass('nav-section')) { // jump to last topic of previous section $prevLink = $prevListItem.find('a:last'); } else if (!$selListItem.hasClass('nav-section')) { // jump to previous topic in this section $prevLink = $prevListItem.find('a:eq(0)'); } } else { // jump to this section's index page (if it exists) var $parentListItem = $selListItem.parents('li'); $prevLink = $selListItem.parents('li').find('a'); // except if cross boundaries aren't allowed, and we're at the top of a section already // (and there's another parent) if (!crossBoundaries && $parentListItem.hasClass('nav-section') && $selListItem.hasClass('nav-section')) { $prevLink = []; } } // set up next links var $nextLink = []; var startClass = false; var training = $(".next-class-link").length; // decides whether to provide "next class" link var isCrossingBoundary = false; if ($selListItem.hasClass('nav-section')) { // we're on an index page, jump to the first topic $nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)'); // if there aren't any children, go to the next section (required for About pages) if($nextLink.length == 0) { $nextLink = $selListItem.next('li').find('a'); } else if ($('.topic-start-link').length) { // as long as there's a child link and there is a "topic start link" (we're on a landing) // then set the landing page "start link" text to be the first doc title $('.topic-start-link').text($nextLink.text().toUpperCase()); } // If the selected page has a description, then it's a class or article homepage if ($selListItem.find('a[description]').length) { // this means we're on a class landing page startClass = true; } } else { // jump to the next topic in this section (if it exists) $nextLink = $selListItem.next('li').find('a:eq(0)'); if (!$nextLink.length) { isCrossingBoundary = true; // no more topics in this section, jump to the first topic in the next section $nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)'); if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course) $nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)'); } } } if (startClass) { $('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide"); // if there's no training bar (below the start button), // then we need to add a bottom border to button if (!$("#tb").length) { $('.start-class-link').css({'border-bottom':'1px solid #DADADA'}); } } else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries $('.content-footer.next-class').show(); $('.next-page-link').attr('href','') .removeClass("hide").addClass("disabled") .click(function() { return false; }); $('.next-class-link').attr('href',$nextLink.attr('href')) .removeClass("hide").append($nextLink.html()); $('.next-class-link').find('.new').empty(); } else { $('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide"); } if (!startClass && $prevLink.length) { var prevHref = $prevLink.attr('href'); if (prevHref == SITE_ROOT + 'index.html') { // Don't show Previous when it leads to the homepage } else { $('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide"); } } // If this is a training 'article', there should be no prev/next nav // ... if the grandparent is the "nav" ... and it has no child list items... if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') && !$selListItem.find('li').length) { $('.next-page-link,.prev-page-link').attr('href','').addClass("disabled") .click(function() { return false; }); } } // Set up the course landing pages for Training with class names and descriptions if ($('body.trainingcourse').length) { var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a'); var $classDescriptions = $classLinks.attr('description'); var $olClasses = $('<ol class="class-list"></ol>'); var $liClass; var $imgIcon; var $h2Title; var $pSummary; var $olLessons; var $liLesson; $classLinks.each(function(index) { $liClass = $('<li></li>'); $h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>'); $pSummary = $('<p class="description">' + $(this).attr('description') + '</p>'); $olLessons = $('<ol class="lesson-list"></ol>'); $lessons = $(this).closest('li').find('ul li a'); if ($lessons.length) { $imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>'); $lessons.each(function(index) { $olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>'); }); } else { $imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>'); $pSummary.addClass('article'); } $liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons); $olClasses.append($liClass); }); $('.jd-descr').append($olClasses); } // Set up expand/collapse behavior $('#nav li.nav-section .nav-section-header').click(function() { var section = $(this).closest('li.nav-section'); if (section.hasClass('expanded')) { /* hide me */ // if (section.hasClass('selected') || section.find('li').hasClass('selected')) { // /* but not if myself or my descendents are selected */ // return; // } section.children('ul').slideUp(250, function() { section.closest('li').removeClass('expanded'); resizeNav(); }); } else { /* show me */ // first hide all other siblings var $others = $('li.nav-section.expanded', $(this).closest('ul')); $others.removeClass('expanded').children('ul').slideUp(250); // now expand me section.closest('li').addClass('expanded'); section.children('ul').slideDown(250, function() { resizeNav(); }); } }); $(".scroll-pane").scroll(function(event) { event.preventDefault(); return false; }); /* Resize nav height when window height changes */ $(window).resize(function() { if ($('#side-nav').length == 0) return; var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]'); setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed // make sidenav behave when resizing the window and side-scolling is a concern if (navBarIsFixed) { if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) { updateSideNavPosition(); } else { updateSidenavFullscreenWidth(); } } resizeNav(); }); // Set up fixed navbar var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll $(window).scroll(function(event) { if ($('#side-nav').length == 0) return; if (event.target.nodeName == "DIV") { // Dump scroll event if the target is a DIV, because that means the event is coming // from a scrollable div and so there's no need to make adjustments to our layout return; } var scrollTop = $(window).scrollTop(); var headerHeight = $('#header').outerHeight(); var subheaderHeight = $('#nav-x').outerHeight(); var searchResultHeight = $('#searchResults').is(":visible") ? $('#searchResults').outerHeight() : 0; var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight; // we set the navbar fixed when the scroll position is beyond the height of the site header... var navBarShouldBeFixed = scrollTop > totalHeaderHeight; // ... except if the document content is shorter than the sidenav height. // (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing) if ($("#doc-col").height() < $("#side-nav").height()) { navBarShouldBeFixed = false; } var scrollLeft = $(window).scrollLeft(); // When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match if (navBarIsFixed && (scrollLeft != prevScrollLeft)) { updateSideNavPosition(); prevScrollLeft = scrollLeft; } // Don't continue if the header is sufficently far away // (to avoid intensive resizing that slows scrolling) if (navBarIsFixed && navBarShouldBeFixed) { return; } if (navBarIsFixed != navBarShouldBeFixed) { if (navBarShouldBeFixed) { // make it fixed var width = $('#devdoc-nav').width(); $('#devdoc-nav') .addClass('fixed') .css({'width':width+'px'}) .prependTo('#body-content'); // add neato "back to top" button $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'}); // update the sidenaav position for side scrolling updateSideNavPosition(); } else { // make it static again $('#devdoc-nav') .removeClass('fixed') .css({'width':'auto','margin':''}) .prependTo('#side-nav'); $('#devdoc-nav a.totop').hide(); } navBarIsFixed = navBarShouldBeFixed; } resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance }); var navBarLeftPos; if ($('#devdoc-nav').length) { setNavBarLeftPos(); } // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away // from the page) $('.nav-section-header').find('a:eq(0)').click(function(evt) { window.location.href = $(this).attr('href'); return false; }); // Set up play-on-hover <video> tags. $('video.play-on-hover').bind('click', function(){ $(this).get(0).load(); // in case the video isn't seekable $(this).get(0).play(); }); // Set up tooltips var TOOLTIP_MARGIN = 10; $('acronym,.tooltip-link').each(function() { var $target = $(this); var $tooltip = $('<div>') .addClass('tooltip-box') .append($target.attr('title')) .hide() .appendTo('body'); $target.removeAttr('title'); $target.hover(function() { // in var targetRect = $target.offset(); targetRect.width = $target.width(); targetRect.height = $target.height(); $tooltip.css({ left: targetRect.left, top: targetRect.top + targetRect.height + TOOLTIP_MARGIN }); $tooltip.addClass('below'); $tooltip.show(); }, function() { // out $tooltip.hide(); }); }); // Set up <h2> deeplinks $('h2').click(function() { var id = $(this).attr('id'); if (id) { document.location.hash = id; } }); //Loads the +1 button var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); // Revise the sidenav widths to make room for the scrollbar // which avoids the visible width from changing each time the bar appears var $sidenav = $("#side-nav"); var sidenav_width = parseInt($sidenav.innerWidth()); $("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller if ($(".scroll-pane").length > 1) { // Check if there's a user preference for the panel heights var cookieHeight = readCookie("reference_height"); if (cookieHeight) { restoreHeight(cookieHeight); } } resizeNav(); /* init the language selector based on user cookie for lang */ loadLangPref(); changeNavLang(getLangPref()); /* setup event handlers to ensure the overflow menu is visible while picking lang */ $("#language select") .mousedown(function() { $("div.morehover").addClass("hover"); }) .blur(function() { $("div.morehover").removeClass("hover"); }); /* some global variable setup */ resizePackagesNav = $("#resize-packages-nav"); classesNav = $("#classes-nav"); devdocNav = $("#devdoc-nav"); var cookiePath = ""; if (location.href.indexOf("/reference/") != -1) { cookiePath = "reference_"; } else if (location.href.indexOf("/guide/") != -1) { cookiePath = "guide_"; } else if (location.href.indexOf("/tools/") != -1) { cookiePath = "tools_"; } else if (location.href.indexOf("/training/") != -1) { cookiePath = "training_"; } else if (location.href.indexOf("/design/") != -1) { cookiePath = "design_"; } else if (location.href.indexOf("/distribute/") != -1) { cookiePath = "distribute_"; } }); function toggleFullscreen(enable) { var delay = 20; var enabled = true; var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]'); if (enable) { // Currently NOT USING fullscreen; enable fullscreen stylesheet.removeAttr('disabled'); $('#nav-swap .fullscreen').removeClass('disabled'); $('#devdoc-nav').css({left:''}); setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch enabled = true; } else { // Currently USING fullscreen; disable fullscreen stylesheet.attr('disabled', 'disabled'); $('#nav-swap .fullscreen').addClass('disabled'); setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch enabled = false; } writeCookie("fullscreen", enabled, null, null); setNavBarLeftPos(); resizeNav(delay); updateSideNavPosition(); setTimeout(initSidenavHeightResize,delay); } function setNavBarLeftPos() { navBarLeftPos = $('#body-content').offset().left; } function updateSideNavPosition() { var newLeft = $(window).scrollLeft() - navBarLeftPos; $('#devdoc-nav').css({left: -newLeft}); $('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))}); } // TODO: use $(document).ready instead function addLoadEvent(newfun) { var current = window.onload; if (typeof window.onload != 'function') { window.onload = newfun; } else { window.onload = function() { current(); newfun(); } } } var agent = navigator['userAgent'].toLowerCase(); // If a mobile phone, set flag and do mobile setup if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod (agent.indexOf("blackberry") != -1) || (agent.indexOf("webos") != -1) || (agent.indexOf("mini") != -1)) { // opera mini browsers isMobile = true; } /* loads the lists.js file to the page. Loading this in the head was slowing page load time */ addLoadEvent( function() { var lists = document.createElement("script"); lists.setAttribute("type","text/javascript"); lists.setAttribute("src", toRoot+"reference/lists.js"); document.getElementsByTagName("head")[0].appendChild(lists); } ); addLoadEvent( function() { $("pre:not(.no-pretty-print)").addClass("prettyprint"); prettyPrint(); } ); /* ######### RESIZE THE SIDENAV HEIGHT ########## */ function resizeNav(delay) { var $nav = $("#devdoc-nav"); var $window = $(window); var navHeight; // Get the height of entire window and the total header height. // Then figure out based on scroll position whether the header is visible var windowHeight = $window.height(); var scrollTop = $window.scrollTop(); var headerHeight = $('#header').outerHeight(); var subheaderHeight = $('#nav-x').outerHeight(); var headerVisible = (scrollTop < (headerHeight + subheaderHeight)); // get the height of space between nav and top of window. // Could be either margin or top position, depending on whether the nav is fixed. var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1; // add 1 for the #side-nav bottom margin // Depending on whether the header is visible, set the side nav's height. if (headerVisible) { // The sidenav height grows as the header goes off screen navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin; } else { // Once header is off screen, the nav height is almost full window height navHeight = windowHeight - topMargin; } $scrollPanes = $(".scroll-pane"); if ($scrollPanes.length > 1) { // subtract the height of the api level widget and nav swapper from the available nav height navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true)); $("#swapper").css({height:navHeight + "px"}); if ($("#nav-tree").is(":visible")) { $("#nav-tree").css({height:navHeight}); } var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px"; //subtract 10px to account for drag bar // if the window becomes small enough to make the class panel height 0, // then the package panel should begin to shrink if (parseInt(classesHeight) <= 0) { $("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar $("#packages-nav").css({height:navHeight - 10}); } $("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'}); $("#classes-nav .jspContainer").css({height:classesHeight}); } else { $nav.height(navHeight); } if (delay) { updateFromResize = true; delayedReInitScrollbars(delay); } else { reInitScrollbars(); } } var updateScrollbars = false; var updateFromResize = false; /* Re-initialize the scrollbars to account for changed nav size. * This method postpones the actual update by a 1/4 second in order to optimize the * scroll performance while the header is still visible, because re-initializing the * scroll panes is an intensive process. */ function delayedReInitScrollbars(delay) { // If we're scheduled for an update, but have received another resize request // before the scheduled resize has occured, just ignore the new request // (and wait for the scheduled one). if (updateScrollbars && updateFromResize) { updateFromResize = false; return; } // We're scheduled for an update and the update request came from this method's setTimeout if (updateScrollbars && !updateFromResize) { reInitScrollbars(); updateScrollbars = false; } else { updateScrollbars = true; updateFromResize = false; setTimeout('delayedReInitScrollbars()',delay); } } /* Re-initialize the scrollbars to account for changed nav size. */ function reInitScrollbars() { var pane = $(".scroll-pane").each(function(){ var api = $(this).data('jsp'); if (!api) { setTimeout(reInitScrollbars,300); return;} api.reinitialise( {verticalGutter:0} ); }); $(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller } /* Resize the height of the nav panels in the reference, * and save the new size to a cookie */ function saveNavPanels() { var basePath = getBaseUri(location.pathname); var section = basePath.substring(1,basePath.indexOf("/",1)); writeCookie("height", resizePackagesNav.css("height"), section, null); } function restoreHeight(packageHeight) { $("#resize-packages-nav").height(packageHeight); $("#packages-nav").height(packageHeight); // var classesHeight = navHeight - packageHeight; // $("#classes-nav").css({height:classesHeight}); // $("#classes-nav .jspContainer").css({height:classesHeight}); } /* ######### END RESIZE THE SIDENAV HEIGHT ########## */ /** Scroll the jScrollPane to make the currently selected item visible This is called when the page finished loading. */ function scrollIntoView(nav) { var $nav = $("#"+nav); var element = $nav.jScrollPane({/* ...settings... */}); var api = element.data('jsp'); if ($nav.is(':visible')) { var $selected = $(".selected", $nav); if ($selected.length == 0) return; var selectedOffset = $selected.position().top; if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even // if the current item is close to the bottom api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view // to be 1/4 of the way from the top } } } /* Show popup dialogs */ function showDialog(id) { $dialog = $("#"+id); $dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>'); $dialog.wrapInner('<div/>'); $dialog.removeClass("hide"); } /* ######### COOKIES! ########## */ function readCookie(cookie) { var myCookie = cookie_namespace+"_"+cookie+"="; if (document.cookie) { var index = document.cookie.indexOf(myCookie); if (index != -1) { var valStart = index + myCookie.length; var valEnd = document.cookie.indexOf(";", valStart); if (valEnd == -1) { valEnd = document.cookie.length; } var val = document.cookie.substring(valStart, valEnd); return val; } } return 0; } function writeCookie(cookie, val, section, expiration) { if (val==undefined) return; section = section == null ? "_" : "_"+section+"_"; if (expiration == null) { var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week expiration = date.toGMTString(); } var cookieValue = cookie_namespace + section + cookie + "=" + val + "; expires=" + expiration+"; path=/"; document.cookie = cookieValue; } /* ######### END COOKIES! ########## */ /* REMEMBER THE PREVIOUS PAGE FOR EACH TAB function loadLast(cookiePath) { var location = window.location.href; if (location.indexOf("/"+cookiePath+"/") != -1) { return true; } var lastPage = readCookie(cookiePath + "_lastpage"); if (lastPage) { window.location = lastPage; return false; } return true; } $(window).unload(function(){ var path = getBaseUri(location.pathname); if (path.indexOf("/reference/") != -1) { writeCookie("lastpage", path, "reference", null); } else if (path.indexOf("/guide/") != -1) { writeCookie("lastpage", path, "guide", null); } else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) { writeCookie("lastpage", path, "resources", null); } }); */ function toggle(obj, slide) { var ul = $("ul:first", obj); var li = ul.parent(); if (li.hasClass("closed")) { if (slide) { ul.slideDown("fast"); } else { ul.show(); } li.removeClass("closed"); li.addClass("open"); $(".toggle-img", li).attr("title", "hide pages"); } else { ul.slideUp("fast"); li.removeClass("open"); li.addClass("closed"); $(".toggle-img", li).attr("title", "show pages"); } } function buildToggleLists() { $(".toggle-list").each( function(i) { $("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>"); $(this).addClass("closed"); }); } /* REFERENCE NAV SWAP */ function getNavPref() { var v = readCookie('reference_nav'); if (v != NAV_PREF_TREE) { v = NAV_PREF_PANELS; } return v; } function chooseDefaultNav() { nav_pref = getNavPref(); if (nav_pref == NAV_PREF_TREE) { $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); } } function swapNav() { if (nav_pref == NAV_PREF_TREE) { nav_pref = NAV_PREF_PANELS; } else { nav_pref = NAV_PREF_TREE; init_default_navtree(toRoot); } var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years writeCookie("nav", nav_pref, "reference", date.toGMTString()); $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); resizeNav(); // Gross nasty hack to make tree view show up upon first swap by setting height manually $("#nav-tree .jspContainer:visible") .css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'}); // Another nasty hack to make the scrollbar appear now that we have height resizeNav(); if ($("#nav-tree").is(':visible')) { scrollIntoView("nav-tree"); } else { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); } } /* ############################################ */ /* ########## LOCALIZATION ############ */ /* ############################################ */ function getBaseUri(uri) { var intlUrl = (uri.substring(0,6) == "/intl/"); if (intlUrl) { base = uri.substring(uri.indexOf('intl/')+5,uri.length); base = base.substring(base.indexOf('/')+1, base.length); //alert("intl, returning base url: /" + base); return ("/" + base); } else { //alert("not intl, returning uri as found."); return uri; } } function requestAppendHL(uri) { //append "?hl=<lang> to an outgoing request (such as to blog) var lang = getLangPref(); if (lang) { var q = 'hl=' + lang; uri += '?' + q; window.location = uri; return false; } else { return true; } } function changeNavLang(lang) { var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]"); $links.each(function(i){ // for each link with a translation var $link = $(this); if (lang != "en") { // No need to worry about English, because a language change invokes new request // put the desired language from the attribute as the text $link.text($link.attr(lang+"-lang")) } }); } function changeLangPref(lang, submit) { var date = new Date(); expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years //alert("expires: " + expires) writeCookie("pref_lang", lang, null, expires); // ####### TODO: Remove this condition once we're stable on devsite ####### // This condition is only needed if we still need to support legacy GAE server if (devsite) { // Switch language when on Devsite server if (submit) { $("#setlang").submit(); } } else { // Switch language when on legacy GAE server changeDocLang(lang); if (submit) { window.location = getBaseUri(location.pathname); } } } function loadLangPref() { var lang = readCookie("pref_lang"); if (lang != 0) { $("#language").find("option[value='"+lang+"']").attr("selected",true); } } function getLangPref() { var lang = $("#language").find(":selected").attr("value"); if (!lang) { lang = readCookie("pref_lang"); } return (lang != 0) ? lang : 'en'; } /* ########## END LOCALIZATION ############ */ /* Used to hide and reveal supplemental content, such as long code samples. See the companion CSS in android-developer-docs.css */ function toggleContent(obj) { var div = $(obj.parentNode.parentNode); var toggleMe = $(".toggle-content-toggleme",div); if (div.hasClass("closed")) { // if it's closed, open it toggleMe.slideDown(); $(".toggle-content-text", obj).toggle(); div.removeClass("closed").addClass("open"); $(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot + "assets/images/triangle-opened.png"); } else { // if it's open, close it toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow $(".toggle-content-text", obj).toggle(); div.removeClass("open").addClass("closed"); $(".toggle-content-img", div).attr("title", "show").attr("src", toRoot + "assets/images/triangle-closed.png"); }); } return false; } /* New version of expandable content */ function toggleExpandable(link,id) { if($(id).is(':visible')) { $(id).slideUp(); $(link).removeClass('expanded'); } else { $(id).slideDown(); $(link).addClass('expanded'); } } function hideExpandable(ids) { $(ids).slideUp(); $(ids).prev('h4').find('a.expandable').removeClass('expanded'); } /* * Slideshow 1.0 * Used on /index.html and /develop/index.html for carousel * * Sample usage: * HTML - * <div class="slideshow-container"> * <a href="" class="slideshow-prev">Prev</a> * <a href="" class="slideshow-next">Next</a> * <ul> * <li class="item"><img src="images/marquee1.jpg"></li> * <li class="item"><img src="images/marquee2.jpg"></li> * <li class="item"><img src="images/marquee3.jpg"></li> * <li class="item"><img src="images/marquee4.jpg"></li> * </ul> * </div> * * <script type="text/javascript"> * $('.slideshow-container').dacSlideshow({ * auto: true, * btnPrev: '.slideshow-prev', * btnNext: '.slideshow-next' * }); * </script> * * Options: * btnPrev: optional identifier for previous button * btnNext: optional identifier for next button * btnPause: optional identifier for pause button * auto: whether or not to auto-proceed * speed: animation speed * autoTime: time between auto-rotation * easing: easing function for transition * start: item to select by default * scroll: direction to scroll in * pagination: whether or not to include dotted pagination * */ (function($) { $.fn.dacSlideshow = function(o) { //Options - see above o = $.extend({ btnPrev: null, btnNext: null, btnPause: null, auto: true, speed: 500, autoTime: 12000, easing: null, start: 0, scroll: 1, pagination: true }, o || {}); //Set up a carousel for each return this.each(function() { var running = false; var animCss = o.vertical ? "top" : "left"; var sizeCss = o.vertical ? "height" : "width"; var div = $(this); var ul = $("ul", div); var tLi = $("li", ul); var tl = tLi.size(); var timer = null; var li = $("li", ul); var itemLength = li.size(); var curr = o.start; li.css({float: o.vertical ? "none" : "left"}); ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); div.css({position: "relative", "z-index": "2", left: "0px"}); var liSize = o.vertical ? height(li) : width(li); var ulSize = liSize * itemLength; var divSize = liSize; li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); //Pagination if (o.pagination) { var pagination = $("<div class='pagination'></div>"); var pag_ul = $("<ul></ul>"); if (tl > 1) { for (var i=0;i<tl;i++) { var li = $("<li>"+i+"</li>"); pag_ul.append(li); if (i==o.start) li.addClass('active'); li.click(function() { go(parseInt($(this).text())); }) } pagination.append(pag_ul); div.append(pagination); } } //Previous button if(o.btnPrev) $(o.btnPrev).click(function(e) { e.preventDefault(); return go(curr-o.scroll); }); //Next button if(o.btnNext) $(o.btnNext).click(function(e) { e.preventDefault(); return go(curr+o.scroll); }); //Pause button if(o.btnPause) $(o.btnPause).click(function(e) { e.preventDefault(); if ($(this).hasClass('paused')) { startRotateTimer(); } else { pauseRotateTimer(); } }); //Auto rotation if(o.auto) startRotateTimer(); function startRotateTimer() { clearInterval(timer); timer = setInterval(function() { if (curr == tl-1) { go(0); } else { go(curr+o.scroll); } }, o.autoTime); $(o.btnPause).removeClass('paused'); } function pauseRotateTimer() { clearInterval(timer); $(o.btnPause).addClass('paused'); } //Go to an item function go(to) { if(!running) { if(to<0) { to = itemLength-1; } else if (to>itemLength-1) { to = 0; } curr = to; running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { running = false; } ); $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength && o.btnNext) || [] ).addClass("disabled"); var nav_items = $('li', pagination); nav_items.removeClass('active'); nav_items.eq(to).addClass('active'); } if(o.auto) startRotateTimer(); return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery); /* * dacSlideshow 1.0 * Used on develop/index.html for side-sliding tabs * * Sample usage: * HTML - * <div class="slideshow-container"> * <a href="" class="slideshow-prev">Prev</a> * <a href="" class="slideshow-next">Next</a> * <ul> * <li class="item"><img src="images/marquee1.jpg"></li> * <li class="item"><img src="images/marquee2.jpg"></li> * <li class="item"><img src="images/marquee3.jpg"></li> * <li class="item"><img src="images/marquee4.jpg"></li> * </ul> * </div> * * <script type="text/javascript"> * $('.slideshow-container').dacSlideshow({ * auto: true, * btnPrev: '.slideshow-prev', * btnNext: '.slideshow-next' * }); * </script> * * Options: * btnPrev: optional identifier for previous button * btnNext: optional identifier for next button * auto: whether or not to auto-proceed * speed: animation speed * autoTime: time between auto-rotation * easing: easing function for transition * start: item to select by default * scroll: direction to scroll in * pagination: whether or not to include dotted pagination * */ (function($) { $.fn.dacTabbedList = function(o) { //Options - see above o = $.extend({ speed : 250, easing: null, nav_id: null, frame_id: null }, o || {}); //Set up a carousel for each return this.each(function() { var curr = 0; var running = false; var animCss = "margin-left"; var sizeCss = "width"; var div = $(this); var nav = $(o.nav_id, div); var nav_li = $("li", nav); var nav_size = nav_li.size(); var frame = div.find(o.frame_id); var content_width = $(frame).find('ul').width(); //Buttons $(nav_li).click(function(e) { go($(nav_li).index($(this))); }) //Go to an item function go(to) { if(!running) { curr = to; running = true; frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing, function() { running = false; } ); nav_li.removeClass('active'); nav_li.eq(to).addClass('active'); } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery); /* ######################################################## */ /* ################ SEARCH SUGGESTIONS ################## */ /* ######################################################## */ var gSelectedIndex = -1; var gSelectedID = -1; var gMatches = new Array(); var gLastText = ""; var ROW_COUNT = 20; var gInitialized = false; function set_item_selected($li, selected) { if (selected) { $li.attr('class','jd-autocomplete jd-selected'); } else { $li.attr('class','jd-autocomplete'); } } function set_item_values(toroot, $li, match) { var $link = $('a',$li); $link.html(match.__hilabel || match.label); $link.attr('href',toroot + match.link); } function sync_selection_table(toroot) { var $list = $("#search_filtered"); var $li; //list item jquery object var i; //list item iterator gSelectedID = -1; //initialize the table; draw it for the first time (but not visible). if (!gInitialized) { for (i=0; i<ROW_COUNT; i++) { var $li = $("<li class='jd-autocomplete'></li>"); $list.append($li); $li.mousedown(function() { window.location = this.firstChild.getAttribute("href"); }); $li.mouseover(function() { $('#search_filtered li').removeClass('jd-selected'); $(this).addClass('jd-selected'); gSelectedIndex = $('#search_filtered li').index(this); }); $li.append('<a></a>'); } gInitialized = true; } //if we have results, make the table visible and initialize result info if (gMatches.length > 0) { $('#search_filtered_div').removeClass('no-display'); var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT; for (i=0; i<N; i++) { $li = $('#search_filtered li:nth-child('+(i+1)+')'); $li.attr('class','show-item'); set_item_values(toroot, $li, gMatches[i]); set_item_selected($li, i == gSelectedIndex); if (i == gSelectedIndex) { gSelectedID = gMatches[i].id; } } //start hiding rows that are no longer matches for (; i<ROW_COUNT; i++) { $li = $('#search_filtered li:nth-child('+(i+1)+')'); $li.attr('class','no-display'); } //if there are more results we're not showing, so say so. /* if (gMatches.length > ROW_COUNT) { li = list.rows[ROW_COUNT]; li.className = "show-item"; c1 = li.cells[0]; c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more"; } else { list.rows[ROW_COUNT].className = "hide-item"; }*/ //if we have no results, hide the table } else { $('#search_filtered_div').addClass('no-display'); } } function search_changed(e, kd, toroot) { var search = document.getElementById("search_autocomplete"); var text = search.value.replace(/(^ +)|( +$)/g, ''); // show/hide the close button if (text != '') { $(".search .close").removeClass("hide"); } else { $(".search .close").addClass("hide"); } // 13 = enter if (e.keyCode == 13) { $('#search_filtered_div').addClass('no-display'); if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) { if ($("#searchResults").is(":hidden")) { // if results aren't showing, return true to allow search to execute return true; } else { // otherwise, results are already showing, so allow ajax to auto refresh the results // and ignore this Enter press to avoid the reload. return false; } } else if (kd && gSelectedIndex >= 0) { window.location = toroot + gMatches[gSelectedIndex].link; return false; } } // 38 -- arrow up else if (kd && (e.keyCode == 38)) { if (gSelectedIndex >= 0) { $('#search_filtered li').removeClass('jd-selected'); gSelectedIndex--; $('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected'); } return false; } // 40 -- arrow down else if (kd && (e.keyCode == 40)) { if (gSelectedIndex < gMatches.length-1 && gSelectedIndex < ROW_COUNT-1) { $('#search_filtered li').removeClass('jd-selected'); gSelectedIndex++; $('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected'); } return false; } else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) { gMatches = new Array(); matchedCount = 0; gSelectedIndex = -1; for (var i=0; i<DATA.length; i++) { var s = DATA[i]; if (text.length != 0 && s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) { gMatches[matchedCount] = s; matchedCount++; } } rank_autocomplete_results(text); for (var i=0; i<gMatches.length; i++) { var s = gMatches[i]; if (gSelectedID == s.id) { gSelectedIndex = i; } } highlight_autocomplete_result_labels(text); sync_selection_table(toroot); return true; // allow the event to bubble up to the search api } } function rank_autocomplete_results(query) { query = query || ''; if (!gMatches || !gMatches.length) return; // helper function that gets the last occurence index of the given regex // in the given string, or -1 if not found var _lastSearch = function(s, re) { if (s == '') return -1; var l = -1; var tmp; while ((tmp = s.search(re)) >= 0) { if (l < 0) l = 0; l += tmp; s = s.substr(tmp + 1); } return l; }; // helper function that counts the occurrences of a given character in // a given string var _countChar = function(s, c) { var n = 0; for (var i=0; i<s.length; i++) if (s.charAt(i) == c) ++n; return n; }; var queryLower = query.toLowerCase(); var queryAlnum = (queryLower.match(/\w+/) || [''])[0]; var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum); var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b'); var _resultScoreFn = function(result) { // scores are calculated based on exact and prefix matches, // and then number of path separators (dots) from the last // match (i.e. favoring classes and deep package names) var score = 1.0; var labelLower = result.label.toLowerCase(); var t; t = _lastSearch(labelLower, partExactAlnumRE); if (t >= 0) { // exact part match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 200 / (partsAfter + 1); } else { t = _lastSearch(labelLower, partPrefixAlnumRE); if (t >= 0) { // part prefix match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 20 / (partsAfter + 1); } } return score; }; for (var i=0; i<gMatches.length; i++) { gMatches[i].__resultScore = _resultScoreFn(gMatches[i]); } gMatches.sort(function(a,b){ var n = b.__resultScore - a.__resultScore; if (n == 0) // lexicographical sort if scores are the same n = (a.label < b.label) ? -1 : 1; return n; }); } function highlight_autocomplete_result_labels(query) { query = query || ''; if (!gMatches || !gMatches.length) return; var queryLower = query.toLowerCase(); var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0]; var queryRE = new RegExp( '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig'); for (var i=0; i<gMatches.length; i++) { gMatches[i].__hilabel = gMatches[i].label.replace( queryRE, '<b>$1</b>'); } } function search_focus_changed(obj, focused) { if (!focused) { if(obj.value == ""){ $(".search .close").addClass("hide"); } document.getElementById("search_filtered_div").className = "no-display"; } } function submit_search() { var query = document.getElementById('search_autocomplete').value; location.hash = 'q=' + query; loadSearchResults(); $("#searchResults").slideDown('slow'); return false; } function hideResults() { $("#searchResults").slideUp(); $(".search .close").addClass("hide"); location.hash = ''; $("#search_autocomplete").val("").blur(); // reset the ajax search callback to nothing, so results don't appear unless ENTER searchControl.setSearchStartingCallback(this, function(control, searcher, query) {}); return false; } /* ########################################################## */ /* ################ CUSTOM SEARCH ENGINE ################## */ /* ########################################################## */ google.load('search', '1'); var searchControl; function loadSearchResults() { document.getElementById("search_autocomplete").style.color = "#000"; // create search control searchControl = new google.search.SearchControl(); // use our existing search form and use tabs when multiple searchers are used drawOptions = new google.search.DrawOptions(); drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED); drawOptions.setInput(document.getElementById("search_autocomplete")); // configure search result options searchOptions = new google.search.SearcherOptions(); searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN); // configure each of the searchers, for each tab devSiteSearcher = new google.search.WebSearch(); devSiteSearcher.setUserDefinedLabel("All"); devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u"); designSearcher = new google.search.WebSearch(); designSearcher.setUserDefinedLabel("Design"); designSearcher.setSiteRestriction("http://developer.android.com/design/"); trainingSearcher = new google.search.WebSearch(); trainingSearcher.setUserDefinedLabel("Training"); trainingSearcher.setSiteRestriction("http://developer.android.com/training/"); guidesSearcher = new google.search.WebSearch(); guidesSearcher.setUserDefinedLabel("Guides"); guidesSearcher.setSiteRestriction("http://developer.android.com/guide/"); referenceSearcher = new google.search.WebSearch(); referenceSearcher.setUserDefinedLabel("Reference"); referenceSearcher.setSiteRestriction("http://developer.android.com/reference/"); googleSearcher = new google.search.WebSearch(); googleSearcher.setUserDefinedLabel("Google Services"); googleSearcher.setSiteRestriction("http://developer.android.com/google/"); blogSearcher = new google.search.WebSearch(); blogSearcher.setUserDefinedLabel("Blog"); blogSearcher.setSiteRestriction("http://android-developers.blogspot.com"); // add each searcher to the search control searchControl.addSearcher(devSiteSearcher, searchOptions); searchControl.addSearcher(designSearcher, searchOptions); searchControl.addSearcher(trainingSearcher, searchOptions); searchControl.addSearcher(guidesSearcher, searchOptions); searchControl.addSearcher(referenceSearcher, searchOptions); searchControl.addSearcher(googleSearcher, searchOptions); searchControl.addSearcher(blogSearcher, searchOptions); // configure result options searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET); searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF); searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT); searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING); // upon ajax search, refresh the url and search title searchControl.setSearchStartingCallback(this, function(control, searcher, query) { updateResultTitle(query); var query = document.getElementById('search_autocomplete').value; location.hash = 'q=' + query; }); // draw the search results box searchControl.draw(document.getElementById("leftSearchControl"), drawOptions); // get query and execute the search searchControl.execute(decodeURI(getQuery(location.hash))); document.getElementById("search_autocomplete").focus(); addTabListeners(); } // End of loadSearchResults google.setOnLoadCallback(function(){ if (location.hash.indexOf("q=") == -1) { // if there's no query in the url, don't search and make sure results are hidden $('#searchResults').hide(); return; } else { // first time loading search results for this page $('#searchResults').slideDown('slow'); $(".search .close").removeClass("hide"); loadSearchResults(); } }, true); // when an event on the browser history occurs (back, forward, load) requery hash and do search $(window).hashchange( function(){ // Exit if the hash isn't a search query or there's an error in the query if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) { // If the results pane is open, close it. if (!$("#searchResults").is(":hidden")) { hideResults(); } return; } // Otherwise, we have a search to do var query = decodeURI(getQuery(location.hash)); searchControl.execute(query); $('#searchResults').slideDown('slow'); $("#search_autocomplete").focus(); $(".search .close").removeClass("hide"); updateResultTitle(query); }); function updateResultTitle(query) { $("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>"); } // forcefully regain key-up event control (previously jacked by search api) $("#search_autocomplete").keyup(function(event) { return search_changed(event, false, toRoot); }); // add event listeners to each tab so we can track the browser history function addTabListeners() { var tabHeaders = $(".gsc-tabHeader"); for (var i = 0; i < tabHeaders.length; i++) { $(tabHeaders[i]).attr("id",i).click(function() { /* // make a copy of the page numbers for the search left pane setTimeout(function() { // remove any residual page numbers $('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove(); // move the page numbers to the left position; make a clone, // because the element is drawn to the DOM only once // and because we're going to remove it (previous line), // we need it to be available to move again as the user navigates $('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible') .clone().appendTo('#searchResults .gsc-tabsArea'); }, 200); */ }); } setTimeout(function(){$(tabHeaders[0]).click()},200); } function getQuery(hash) { var queryParts = hash.split('='); return queryParts[1]; } /* returns the given string with all HTML brackets converted to entities TODO: move this to the site's JS library */ function escapeHTML(string) { return string.replace(/</g,"&lt;") .replace(/>/g,"&gt;"); } /* ######################################################## */ /* ################# JAVADOC REFERENCE ################### */ /* ######################################################## */ /* Initialize some droiddoc stuff, but only if we're in the reference */ if (location.pathname.indexOf("/reference")) { if(!location.pathname.indexOf("/reference-gms/packages.html") && !location.pathname.indexOf("/reference-gcm/packages.html") && !location.pathname.indexOf("/reference/com/google") == 0) { $(document).ready(function() { // init available apis based on user pref changeApiLevel(); initSidenavHeightResize() }); } } var API_LEVEL_COOKIE = "api_level"; var minLevel = 1; var maxLevel = 1; /******* SIDENAV DIMENSIONS ************/ function initSidenavHeightResize() { // Change the drag bar size to nicely fit the scrollbar positions var $dragBar = $(".ui-resizable-s"); $dragBar.css({'width': $dragBar.parent().width() - 5 + "px"}); $( "#resize-packages-nav" ).resizable({ containment: "#nav-panels", handles: "s", alsoResize: "#packages-nav", resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */ stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */ }); } function updateSidenavFixedWidth() { if (!navBarIsFixed) return; $('#devdoc-nav').css({ 'width' : $('#side-nav').css('width'), 'margin' : $('#side-nav').css('margin') }); $('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'}); initSidenavHeightResize(); } function updateSidenavFullscreenWidth() { if (!navBarIsFixed) return; $('#devdoc-nav').css({ 'width' : $('#side-nav').css('width'), 'margin' : $('#side-nav').css('margin') }); $('#devdoc-nav .totop').css({'left': 'inherit'}); initSidenavHeightResize(); } function buildApiLevelSelector() { maxLevel = SINCE_DATA.length; var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE)); userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default minLevel = parseInt($("#doc-api-level").attr("class")); // Handle provisional api levels; the provisional level will always be the highest possible level // Provisional api levels will also have a length; other stuff that's just missing a level won't, // so leave those kinds of entities at the default level of 1 (for example, the R.styleable class) if (isNaN(minLevel) && minLevel.length) { minLevel = maxLevel; } var select = $("#apiLevelSelector").html("").change(changeApiLevel); for (var i = maxLevel-1; i >= 0; i--) { var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]); // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames) select.append(option); } // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true) var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0); selectedLevelItem.setAttribute('selected',true); } function changeApiLevel() { maxLevel = SINCE_DATA.length; var selectedLevel = maxLevel; selectedLevel = parseInt($("#apiLevelSelector option:selected").val()); toggleVisisbleApis(selectedLevel, "body"); var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years var expiration = date.toGMTString(); writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration); if (selectedLevel < minLevel) { var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class"; $("#naMessage").show().html("<div><p><strong>This " + thing + " requires API level " + minLevel + " or higher.</strong></p>" + "<p>This document is hidden because your selected API level for the documentation is " + selectedLevel + ". You can change the documentation API level with the selector " + "above the left navigation.</p>" + "<p>For more information about specifying the API level your app requires, " + "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'" + ">Supporting Different Platform Versions</a>.</p>" + "<input type='button' value='OK, make this page visible' " + "title='Change the API level to " + minLevel + "' " + "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />" + "</div>"); } else { $("#naMessage").hide(); } } function toggleVisisbleApis(selectedLevel, context) { var apis = $(".api",context); apis.each(function(i) { var obj = $(this); var className = obj.attr("class"); var apiLevelIndex = className.lastIndexOf("-")+1; var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex); apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length; var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex); if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail return; } apiLevel = parseInt(apiLevel); // Handle provisional api levels; if this item's level is the provisional one, set it to the max var selectedLevelNum = parseInt(selectedLevel) var apiLevelNum = parseInt(apiLevel); if (isNaN(apiLevelNum)) { apiLevelNum = maxLevel; } // Grey things out that aren't available and give a tooltip title if (apiLevelNum > selectedLevelNum) { obj.addClass("absent").attr("title","Requires API Level \"" + apiLevel + "\" or higher"); } else obj.removeClass("absent").removeAttr("title"); }); } /* ################# SIDENAV TREE VIEW ################### */ function new_node(me, mom, text, link, children_data, api_level) { var node = new Object(); node.children = Array(); node.children_data = children_data; node.depth = mom.depth + 1; node.li = document.createElement("li"); mom.get_children_ul().appendChild(node.li); node.label_div = document.createElement("div"); node.label_div.className = "label"; if (api_level != null) { $(node.label_div).addClass("api"); $(node.label_div).addClass("api-level-"+api_level); } node.li.appendChild(node.label_div); if (children_data != null) { node.expand_toggle = document.createElement("a"); node.expand_toggle.href = "javascript:void(0)"; node.expand_toggle.onclick = function() { if (node.expanded) { $(node.get_children_ul()).slideUp("fast"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.expanded = false; } else { expand_node(me, node); } }; node.label_div.appendChild(node.expand_toggle); node.plus_img = document.createElement("img"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.plus_img.className = "plus"; node.plus_img.width = "8"; node.plus_img.border = "0"; node.expand_toggle.appendChild(node.plus_img); node.expanded = false; } var a = document.createElement("a"); node.label_div.appendChild(a); node.label = document.createTextNode(text); a.appendChild(node.label); if (link) { a.href = me.toroot + link; } else { if (children_data != null) { a.className = "nolink"; a.href = "javascript:void(0)"; a.onclick = node.expand_toggle.onclick; // This next line shouldn't be necessary. I'll buy a beer for the first // person who figures out how to remove this line and have the link // toggle shut on the first try. --joeo@android.com node.expanded = false; } } node.children_ul = null; node.get_children_ul = function() { if (!node.children_ul) { node.children_ul = document.createElement("ul"); node.children_ul.className = "children_ul"; node.children_ul.style.display = "none"; node.li.appendChild(node.children_ul); } return node.children_ul; }; return node; } function expand_node(me, node) { if (node.children_data && !node.expanded) { if (node.children_visited) { $(node.get_children_ul()).slideDown("fast"); } else { get_node(me, node); if ($(node.label_div).hasClass("absent")) { $(node.get_children_ul()).addClass("absent"); } $(node.get_children_ul()).slideDown("fast"); } node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png"; node.expanded = true; // perform api level toggling because new nodes are new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } } function get_node(me, mom) { mom.children_visited = true; for (var i in mom.children_data) { var node_data = mom.children_data[i]; mom.children[i] = new_node(me, mom, node_data[0], node_data[1], node_data[2], node_data[3]); } } function this_page_relative(toroot) { var full = document.location.pathname; var file = ""; if (toroot.substr(0, 1) == "/") { if (full.substr(0, toroot.length) == toroot) { return full.substr(toroot.length); } else { // the file isn't under toroot. Fail. return null; } } else { if (toroot != "./") { toroot = "./" + toroot; } do { if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") { var pos = full.lastIndexOf("/"); file = full.substr(pos) + file; full = full.substr(0, pos); toroot = toroot.substr(0, toroot.length-3); } } while (toroot != "" && toroot != "/"); return file.substr(1); } } function find_page(url, data) { var nodes = data; var result = null; for (var i in nodes) { var d = nodes[i]; if (d[1] == url) { return new Array(i); } else if (d[2] != null) { result = find_page(url, d[2]); if (result != null) { return (new Array(i).concat(result)); } } } return null; } function init_default_navtree(toroot) { init_navtree("tree-list", toroot, NAVTREE_DATA); // perform api level toggling because because the whole tree is new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } function init_navtree(navtree_id, toroot, root_nodes) { var me = new Object(); me.toroot = toroot; me.node = new Object(); me.node.li = document.getElementById(navtree_id); me.node.children_data = root_nodes; me.node.children = new Array(); me.node.children_ul = document.createElement("ul"); me.node.get_children_ul = function() { return me.node.children_ul; }; //me.node.children_ul.className = "children_ul"; me.node.li.appendChild(me.node.children_ul); me.node.depth = 0; get_node(me, me.node); me.this_page = this_page_relative(toroot); me.breadcrumbs = find_page(me.this_page, root_nodes); if (me.breadcrumbs != null && me.breadcrumbs.length != 0) { var mom = me.node; for (var i in me.breadcrumbs) { var j = me.breadcrumbs[i]; mom = mom.children[j]; expand_node(me, mom); } mom.label_div.className = mom.label_div.className + " selected"; addLoadEvent(function() { scrollIntoView("nav-tree"); }); } } /* TODO: eliminate redundancy with non-google functions */ function init_google_navtree(navtree_id, toroot, root_nodes) { var me = new Object(); me.toroot = toroot; me.node = new Object(); me.node.li = document.getElementById(navtree_id); me.node.children_data = root_nodes; me.node.children = new Array(); me.node.children_ul = document.createElement("ul"); me.node.get_children_ul = function() { return me.node.children_ul; }; //me.node.children_ul.className = "children_ul"; me.node.li.appendChild(me.node.children_ul); me.node.depth = 0; get_google_node(me, me.node); } function new_google_node(me, mom, text, link, children_data, api_level) { var node = new Object(); var child; node.children = Array(); node.children_data = children_data; node.depth = mom.depth + 1; node.get_children_ul = function() { if (!node.children_ul) { node.children_ul = document.createElement("ul"); node.children_ul.className = "tree-list-children"; node.li.appendChild(node.children_ul); } return node.children_ul; }; node.li = document.createElement("li"); mom.get_children_ul().appendChild(node.li); if(link) { child = document.createElement("a"); } else { child = document.createElement("span"); child.className = "tree-list-subtitle"; } if (children_data != null) { node.li.className="nav-section"; node.label_div = document.createElement("div"); node.label_div.className = "nav-section-header-ref"; node.li.appendChild(node.label_div); get_google_node(me, node); node.label_div.appendChild(child); } else { node.li.appendChild(child); } if(link) { child.href = me.toroot + link; } node.label = document.createTextNode(text); child.appendChild(node.label); node.children_ul = null; return node; } function get_google_node(me, mom) { mom.children_visited = true; var linkText; for (var i in mom.children_data) { var node_data = mom.children_data[i]; linkText = node_data[0]; if(linkText.match("^"+"com.google.android")=="com.google.android"){ linkText = linkText.substr(19, linkText.length); } mom.children[i] = new_google_node(me, mom, linkText, node_data[1], node_data[2], node_data[3]); } } function showGoogleRefTree() { init_default_google_navtree(toRoot); init_default_gcm_navtree(toRoot); resizeNav(); } function init_default_google_navtree(toroot) { init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA); } function init_default_gcm_navtree(toroot) { init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA); } /* TOGGLE INHERITED MEMBERS */ /* Toggle an inherited class (arrow toggle) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleInherited(linkObj, expand) { var base = linkObj.getAttribute("id"); var list = document.getElementById(base + "-list"); var summary = document.getElementById(base + "-summary"); var trigger = document.getElementById(base + "-trigger"); var a = $(linkObj); if ( (expand == null && a.hasClass("closed")) || expand ) { list.style.display = "none"; summary.style.display = "block"; trigger.src = toRoot + "assets/images/triangle-opened.png"; a.removeClass("closed"); a.addClass("opened"); } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) { list.style.display = "block"; summary.style.display = "none"; trigger.src = toRoot + "assets/images/triangle-closed.png"; a.removeClass("opened"); a.addClass("closed"); } return false; } /* Toggle all inherited classes in a single table (e.g. all inherited methods) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleAllInherited(linkObj, expand) { var a = $(linkObj); var table = $(a.parent().parent().parent()); // ugly way to get table/tbody var expandos = $(".jd-expando-trigger", table); if ( (expand == null && a.text() == "[Expand]") || expand ) { expandos.each(function(i) { toggleInherited(this, true); }); a.text("[Collapse]"); } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) { expandos.each(function(i) { toggleInherited(this, false); }); a.text("[Expand]"); } return false; } /* Toggle all inherited members in the class (link in the class title) */ function toggleAllClassInherited() { var a = $("#toggleAllClassInherited"); // get toggle link from class title var toggles = $(".toggle-all", $("#body-content")); if (a.text() == "[Expand All]") { toggles.each(function(i) { toggleAllInherited(this, true); }); a.text("[Collapse All]"); } else { toggles.each(function(i) { toggleAllInherited(this, false); }); a.text("[Expand All]"); } return false; } /* Expand all inherited members in the class. Used when initiating page search */ function ensureAllInheritedExpanded() { var toggles = $(".toggle-all", $("#body-content")); toggles.each(function(i) { toggleAllInherited(this, true); }); $("#toggleAllClassInherited").text("[Collapse All]"); } /* HANDLE KEY EVENTS * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search) */ var agent = navigator['userAgent'].toLowerCase(); var mac = agent.indexOf("macintosh") != -1; $(document).keydown( function(e) { var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key if (control && e.which == 70) { // 70 is "F" ensureAllInheritedExpanded(); } });
JavaScript
/* * Release: 1.3.1 2009-04-26 */ /* * Copyright (c) Andr?e Hansson (peolanha AT gmail DOT com) * MIT License - http://www.opensource.org/licenses/mit-license.php * Idea loosely based on JASH, http://billyreisinger.com/jash/ * * Website: http://gridder.andreehansson.se/ * * Changelog: * - New GUI! The new GUI should be less obtrusive and has been repositioned. * It is also featuring a slight delay on inputs so that you'll have a chance * to change the settings before it is re-rendering the grid * - Due to a lot of inquries regarding affiliation with jQuery the filenames has * been changed, I'm very sorry for the inconvenience! * - CSS issues with the GUI should also be fixed in more websites, please report * in any issue you stumble upon * - A small bug in IE that made the paragraph lines not position correctly has been * fixed * - A dropdown box has replaced the columns input box, 960 Gridder calculates the * proper number of columns that can be used with the specified grid width * - The 960 Gridder is now displaying perfectly (into the very pixels) in all * A-grade browsers (according to browsershots.org) * - An option to invert the gutters has been added, set this to 'true' if * you want to use it, OR use the shortcut CTRL+ALT+A * - Some other minor changes... */ function Grid() { var c = this; c.settingsDef = { urlBase: "http://gridder.andreehansson.se/releases/1.3.1/", gColor: "#EEEEEE", gColumns: 12, gOpacity: 0.45, gWidth: 10, pColor: "#C0C0C0", pHeight: 15, pOffset: 0, pOpacity: 0.55, center: true, invert: false, gEnabled: true, pEnabled: true, size: 960, fixFlash: true, setupEnabled: true, pressedKeys: [], delayTimer: "" }; c.settings = (typeof (window.gOverride) === "undefined") ? {} : window.gOverride; for (var a in c.settingsDef) { if (typeof (c.settings[a]) === "undefined") { c.settings[a] = c.settingsDef[a]; } } if (typeof (window.jQuery) === "undefined" || jQuery().jquery.match(/^1\.3/) === null) { window.jQuery = undefined; var b = document.createElement("script"); b.type = "text/javascript"; b.src = c.settings.urlBase + "jquery.js"; document.body.appendChild(b); } c._createEntity = function (e, d) { jQuery('<div class="g-' + e + '">&nbsp;</div>').appendTo("#g-grid").css(d); }; c._setVariable = function (d, e) { d = d.replace(/g-setup-/, ""); if (isNaN(parseInt(e, 10)) || parseInt(e, 10) === 0) { c.settings[d] = e; } else { c.settings[d] = parseInt(e, 10); } if (e === true) { jQuery("#g-setup-" + d).attr("checked", "checked"); } else { if (e === false) { jQuery("#g-setup-" + d).removeAttr("checked"); } else { jQuery("#g-setup-" + d).val(e); } } }; c.setupWindow = function () { jQuery('<style type"text/css">#g-setup{position:absolute;top:150px;left:-310px;padding:6px;margin:0;list-style:none;width:320px!important;background-color:#d1cfe6;border:2px solid #a19bd1;z-index:2100; display:none;}#g-setup *{background:transparent!important;border:0!important;color:#58517c!important;font-family:Verdana,Geneva,sans-serif!important;font-size:10px!important;font-weight:normal!important;letter-spacing:normal!important;line-height:1!important;list-style-type:none!important;margin:0!important;padding:0!important;text-decoration:none!important;text-indent:0!important;text-transform:none!important;word-spacing:0!important;z-index:2100!important;}#g-setup .head{font-weight:bold!important;text-align:center;border-bottom:1px solid #7cb267!important;}#g-setup ul{width:150px;float:left!important;}#g-setup li{clear:left;padding:5px!important;}* html #g-setup li{clear:none!important;padding:4px!important;}#g-setup span{float:left!important;width:50px;padding:1px 4px 0 0!important;text-align:right!important;line-height:1.5!important;}#g-setup input,#g-setup select{float:left!important;width:70px;border:1px solid #a19bd1!important;background-color:#e7e6ee!important;padding:2px!important;}#g-setup select{width:77px;padding:0!important;}#g-setup-misc{margin-top:5px!important;clear:left;float:none!important;width:300px!important;border-top:1px solid #7cb267!important;}#g-setup-misc span{line-height:1.1!important;width:200px;}#g-setup-misc input{width:15px;padding:0!important;height:15px;}#g-setup-tab{width:26px;overflow:hidden;position:absolute;top:0;left:100%;margin-left:-26px!important;z-index:2100!important;}#g-setup-tab img{left:0;position:relative;}#g-grid{left:0;position:absolute;z-index:500;top:0;}#g-grid .g-vertical,#g-grid .g-horizontal{position:absolute;z-index:1000;}*:first-child+html #g-grid .g-horizontal,*:first-child+html #g-grid .g-vertical{margin-left:-1px;}#g-grid .g-horizontal{min-height:1px;height:1px;font-size:0;line-height:0;}</style>').appendTo("head"); c.settings.height = jQuery(document).height(); if (c.settings.setupEnabled) { jQuery('<div id="g-setup"><ul><li class="head">Vertical</li><li><span>Color</span><input id="g-setup-gColor" /></li><li><span>Opacity</span><input id="g-setup-gOpacity" /></li><li><span>Width</span><input id="g-setup-gWidth" /></li><li><span>Columns</span><select id="g-setup-gColumns"></select></li></ul><ul><li class="head">Horizontal</li><li><span>Color</span><input id="g-setup-pColor" /></li><li><span>Opacity</span><input id="g-setup-pOpacity" /></li><li><span>Height</span><input id="g-setup-pHeight" /></li><li><span>Offset</span><input id="g-setup-pOffset" /></li></ul><ul id="g-setup-misc"><li><span>Enable vertical (gutters)</span><input id="g-setup-gEnabled" type="checkbox" /></li><li><span>Enable horizontal (paragraphs)</span><input id="g-setup-pEnabled" type="checkbox" /></li><li><span>Invert vertical</span><input id="g-setup-invert" type="checkbox" /></li><li><span>Center grid</span><input id="g-setup-center" type="checkbox" /></li></ul><div style="clear: left;"></div><div id="g-setup-tab"><a href="javascript:;"><img src="http://gridder.andreehansson.se/releases/1.3.1/logo-sprite.png" alt="" /></a></div></div>').appendTo("body"); for (var d = 2; d < 48; d++) { if (Math.round((c.settings.size / d)) === (c.settings.size / d)) { jQuery('<option value="' + d + '">' + d + "</option>").appendTo("#g-setup-gColumns"); } } for (var d in c.settings) { if (jQuery("#g-setup-" + d).length !== 0) { if (jQuery("#g-setup-" + d).parent().parent().is("#g-setup-misc") && c.settings[d]) { jQuery("#g-setup-" + d).attr("checked", "checked"); } else { jQuery("#g-setup-" + d).val(c.settings[d]); } } } jQuery("#g-setup").css("top", jQuery(window).scrollTop() + 150); jQuery("#g-setup-tab a").click(function () { c.toggleSetupWindow(); }); jQuery("#g-setup input").keyup(function () { var e = this; clearTimeout(c.settings.delayTimer); c.settings.delayTimer = setTimeout(function () { c.setVariable(jQuery(e).attr("id"), jQuery(e).val()); }, 700); }); jQuery("#g-setup-gColumns").change(function () { c.setVariable("gColumns", $(this).val()); }); jQuery("#g-setup-misc input").click(function () { c.setVariable(jQuery(this).attr("id"), jQuery(this).attr("checked")); }); jQuery().keydown(function (f) { if (jQuery.inArray(f.which, c.settings.pressedKeys) === -1) { c.settings.pressedKeys.push(f.which); } }); jQuery(window).scroll(function () { jQuery("#g-setup").css("top", jQuery().scrollTop() + 150); }); } jQuery().keyup(function (g) { if (jQuery.inArray(17, c.settings.pressedKeys) !== -1 && jQuery.inArray(18, c.settings.pressedKeys) !== -1) { if (jQuery.inArray(90, c.settings.pressedKeys) !== -1) { c.setVariable("gEnabled", !c.settings.gEnabled); } else { if (jQuery.inArray(88, c.settings.pressedKeys) !== -1) { c.setVariable("pEnabled", !c.settings.pEnabled); } else { if (jQuery.inArray(65, c.settings.pressedKeys) !== -1) { c.setVariable("invert", !c.settings.invert); } else { if (jQuery.inArray(67, c.settings.pressedKeys) !== -1) { c.setVariable({ gEnabled: !c.settings.gEnabled, pEnabled: !c.settings.pEnabled }); } } } } } var f = jQuery.inArray(g.which, c.settings.pressedKeys); c.settings.pressedKeys.splice(f, f); }); }; c.setVariable = function () { if (typeof (arguments[0]) === "object") { for (var d in arguments[0]) { c._setVariable(d, arguments[0][d]); } } else { c._setVariable(arguments[0], arguments[1]); } c.createGrid(); }; c.toggleSetupWindow = function () { var d = jQuery("#g-setup-tab img"); d.css("left", d.position().left === 0 ? -26 : 0); if (parseInt(jQuery("#g-setup").css("left"), 10) === 0) { jQuery("#g-setup").animate({ left: -310 }, 200); } else { jQuery("#g-setup").animate({ left: 0 }, 200); } }; c.createGrid = function () { jQuery("embed").each(function () { if (c.settings.fixFlash) { jQuery(this).attr("wmode", "transparent"); } else { jQuery(this).removeAttr("wmode"); } var i = jQuery(this).wrap("<div></div>").parent().html(); jQuery(this).parent().replaceWith(i); jQuery(this).remove(); }); jQuery("#g-grid").remove(); jQuery('<div id="g-grid"></div>').appendTo("body").css("width", c.settings.size); if (c.settings.center) { jQuery("#g-grid").css({ left: "50%", marginLeft: -((c.settings.size / 2) + c.settings.gWidth) }); } if (c.settings.gEnabled && c.settings.gColumns > 0) { if (c.settings.invert) { jQuery().css("overflow-x", "hidden"); var e = (jQuery(window).width() - c.settings.size) / 2; c._createEntity("vertical", { left: -e, width: e, height: c.settings.height, backgroundColor: c.settings.gColor, opacity: c.settings.gOpacity }); for (var g = 0; g < c.settings.gColumns; g++) { var f = (c.settings.size / c.settings.gColumns) - (c.settings.gWidth * 2); var h = (c.settings.gWidth * 2); c._createEntity("vertical", { left: ((f + h) * g) + h, width: f + "px", height: c.settings.height, backgroundColor: c.settings.gColor, opacity: c.settings.gOpacity }); } if ((c.settings.height + 10) > jQuery(window).height()) { e -= 10; } c._createEntity("vertical", { left: "100%", marginLeft: 20, width: e, height: c.settings.height, backgroundColor: c.settings.gColor, opacity: c.settings.gOpacity }); } else { for (var g = 0; g <= c.settings.gColumns; g++) { c._createEntity("vertical", { left: ((c.settings.size / c.settings.gColumns) * g), width: (c.settings.gWidth * 2), height: c.settings.height, backgroundColor: c.settings.gColor, opacity: c.settings.gOpacity }); } } } if (c.settings.pEnabled && c.settings.pHeight > 1) { var d = ((c.settings.height - c.settings.pOffset) / c.settings.pHeight); for (g = 0; g <= d; g++) { c._createEntity("horizontal", { top: ((c.settings.height / d) * g) + c.settings.pOffset, left: "50%", marginLeft: -(c.settings.size / 2), width: (c.settings.size + (c.settings.gWidth * 2)), backgroundColor: c.settings.pColor, opacity: c.settings.pOpacity }); } } }; } var checkJQuery = function () { if (typeof (window.jQuery) === "undefined") { setTimeout(function () { checkJQuery(); }, 10); } else { window.grid.setupWindow(); window.grid.createGrid(); } }; if (typeof (window.grid) === "undefined") { window.grid = new Grid(); checkJQuery(); } else { window.grid.toggleSetupWindow(); }
JavaScript
$(document).ready(function() { // prep nav expandos var pagePath = document.location.pathname; if (pagePath.indexOf(SITE_ROOT) == 0) { pagePath = pagePath.substr(SITE_ROOT.length); if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') { pagePath += 'index.html'; } } if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') { // If running locally, SITE_ROOT will be a relative path, so account for that by // finding the relative URL to this page. This will allow us to find links on the page // leading back to this page. var pathParts = pagePath.split('/'); var relativePagePathParts = []; var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3; for (var i = 0; i < upDirs; i++) { relativePagePathParts.push('..'); } for (var i = 0; i < upDirs; i++) { relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]); } relativePagePathParts.push(pathParts[pathParts.length - 1]); pagePath = relativePagePathParts.join('/'); } else { // Otherwise the page path should be an absolute URL. pagePath = SITE_ROOT + pagePath; } // select current page in sidenav and set up prev/next links if they exist var $selNavLink = $('.nav-y').find('a[href="' + pagePath + '"]'); if ($selNavLink.length) { $selListItem = $selNavLink.closest('li'); $selListItem.addClass('selected'); $selListItem.closest('li>ul').addClass('expanded'); // set up prev links var $prevLink = []; var $prevListItem = $selListItem.prev('li'); if ($prevListItem.length) { if ($prevListItem.hasClass('nav-section')) { // jump to last topic of previous section $prevLink = $prevListItem.find('a:last'); } else { // jump to previous topic in this section $prevLink = $prevListItem.find('a:eq(0)'); } } else { // jump to this section's index page (if it exists) $prevLink = $selListItem.parents('li').find('a'); } if ($prevLink.length) { var prevHref = $prevLink.attr('href'); if (prevHref == SITE_ROOT + 'index.html') { // Don't show Previous when it leads to the homepage $('.prev-page-link').hide(); } else { $('.prev-page-link').attr('href', prevHref).show(); } } else { $('.prev-page-link').hide(); } // set up next links var $nextLink = []; if ($selListItem.hasClass('nav-section')) { // we're on an index page, jump to the first topic $nextLink = $selListItem.find('ul').find('a:eq(0)') } else { // jump to the next topic in this section (if it exists) $nextLink = $selListItem.next('li').find('a:eq(0)'); if (!$nextLink.length) { // no more topics in this section, jump to the first topic in the next section $nextLink = $selListItem.parents('li').next('li.nav-section').find('a:eq(0)'); } } if ($nextLink.length) { $('.next-page-link').attr('href', $nextLink.attr('href')).show(); } else { $('.next-page-link').hide(); } } // Set up expand/collapse behavior $('.nav-y li').has('ul').click(function() { if ($(this).hasClass('expanded')) { return; } // hide other var $old = $('.nav-y li.expanded'); if ($old.length) { var $oldUl = $old.children('ul'); $oldUl.css('height', $oldUl.height() + 'px'); window.setTimeout(function() { $oldUl .addClass('animate-height') .css('height', ''); }, 0); $old.removeClass('expanded'); } // show me $(this).addClass('expanded'); var $ul = $(this).children('ul'); var expandedHeight = $ul.height(); $ul .removeClass('animate-height') .css('height', 0); window.setTimeout(function() { $ul .addClass('animate-height') .css('height', expandedHeight + 'px'); }, 0); }); // Stop expand/collapse behavior when clicking on nav section links (since we're navigating away // from the page) $('.nav-y li').has('ul').find('a:eq(0)').click(function(evt) { window.location.href = $(this).attr('href'); return false; }); // Set up play-on-hover <video> tags. $('video.play-on-hover').bind('click', function(){ $(this).get(0).load(); // in case the video isn't seekable $(this).get(0).play(); }); // Set up tooltips var TOOLTIP_MARGIN = 10; $('acronym').each(function() { var $target = $(this); var $tooltip = $('<div>') .addClass('tooltip-box') .text($target.attr('title')) .hide() .appendTo('body'); $target.removeAttr('title'); $target.hover(function() { // in var targetRect = $target.offset(); targetRect.width = $target.width(); targetRect.height = $target.height(); $tooltip.css({ left: targetRect.left, top: targetRect.top + targetRect.height + TOOLTIP_MARGIN }); $tooltip.addClass('below'); $tooltip.show(); }, function() { // out $tooltip.hide(); }); }); // Set up <h2> deeplinks $('h2').click(function() { var id = $(this).attr('id'); if (id) { document.location.hash = id; } }); // Set up fixed navbar var navBarIsFixed = false; $(window).scroll(function() { var scrollTop = $(window).scrollTop(); var navBarShouldBeFixed = (scrollTop > (100 - 40)); if (navBarIsFixed != navBarShouldBeFixed) { if (navBarShouldBeFixed) { $('#nav') .addClass('fixed') .prependTo('#page-container'); } else { $('#nav') .removeClass('fixed') .prependTo('#nav-container'); } navBarIsFixed = navBarShouldBeFixed; } }); });
JavaScript
var resizePackagesNav; var classesNav; var devdocNav; var sidenav; var content; var HEADER_HEIGHT = 117; var cookie_namespace = 'android_developer'; var NAV_PREF_TREE = "tree"; var NAV_PREF_PANELS = "panels"; var nav_pref; var toRoot; var isMobile = false; // true if mobile, so we can adjust some layout function addLoadEvent(newfun) { var current = window.onload; if (typeof window.onload != 'function') { window.onload = newfun; } else { window.onload = function() { current(); newfun(); } } } var agent = navigator['userAgent']; if ((agent.indexOf("Mobile") != -1) || (agent.indexOf("BlackBerry") != -1) || (agent.indexOf("Mini") != -1)) { isMobile = true; addLoadEvent(mobileSetup); } addLoadEvent(function() { window.onresize = resizeAll; }); function mobileSetup() { $("body").css({'overflow':'auto'}); $("html").css({'overflow':'auto'}); $("#body-content").css({'position':'relative', 'top':'0'}); $("#doc-content").css({'overflow':'visible', 'border-left':'3px solid #DDD'}); $("#side-nav").css({'padding':'0'}); $("#nav-tree").css({'overflow-y': 'auto'}); } /* loads the lists.js file to the page. Loading this in the head was slowing page load time */ addLoadEvent( function() { var lists = document.createElement("script"); lists.setAttribute("type","text/javascript"); lists.setAttribute("src", toRoot+"reference/lists.js"); document.getElementsByTagName("head")[0].appendChild(lists); } ); function setToRoot(root) { toRoot = root; // note: toRoot also used by carousel.js } function restoreWidth(navWidth) { var windowWidth = $(window).width() + "px"; content.css({marginLeft:parseInt(navWidth) + 6 + "px", //account for 6px-wide handle-bar width:parseInt(windowWidth) - parseInt(navWidth) - 6 + "px"}); sidenav.css({width:navWidth}); resizePackagesNav.css({width:navWidth}); classesNav.css({width:navWidth}); $("#packages-nav").css({width:navWidth}); } function restoreHeight(packageHeight) { var windowHeight = ($(window).height() - HEADER_HEIGHT); var swapperHeight = windowHeight - 13; $("#swapper").css({height:swapperHeight + "px"}); sidenav.css({height:windowHeight + "px"}); content.css({height:windowHeight + "px"}); resizePackagesNav.css({maxHeight:swapperHeight + "px", height:packageHeight}); classesNav.css({height:swapperHeight - parseInt(packageHeight) + "px"}); $("#packages-nav").css({height:parseInt(packageHeight) - 6 + "px"}); //move 6px to give space for the resize handle devdocNav.css({height:sidenav.css("height")}); $("#nav-tree").css({height:swapperHeight + "px"}); } function readCookie(cookie) { var myCookie = cookie_namespace+"_"+cookie+"="; if (document.cookie) { var index = document.cookie.indexOf(myCookie); if (index != -1) { var valStart = index + myCookie.length; var valEnd = document.cookie.indexOf(";", valStart); if (valEnd == -1) { valEnd = document.cookie.length; } var val = document.cookie.substring(valStart, valEnd); return val; } } return 0; } function writeCookie(cookie, val, section, expiration) { if (!val) return; section = section == null ? "_" : "_"+section+"_"; if (expiration == null) { var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week expiration = date.toGMTString(); } document.cookie = cookie_namespace+section+cookie+"="+val+"; expires="+expiration+"; path=/"; } function init() { $("#side-nav").css({position:"absolute",left:0}); content = $("#doc-content"); resizePackagesNav = $("#resize-packages-nav"); classesNav = $("#classes-nav"); sidenav = $("#side-nav"); devdocNav = $("#devdoc-nav"); if (location.href.indexOf("/reference/") != -1) { var cookiePath = "reference_"; } else if (location.href.indexOf("/guide/") != -1) { var cookiePath = "guide_"; } if (!isMobile) { $("#resize-packages-nav").resizable({handles: "s", resize: function(e, ui) { resizeHeight(); } }); $(".side-nav-resizable").resizable({handles: "e", resize: function(e, ui) { resizeWidth(); } }); var cookieWidth = readCookie(cookiePath+'width'); var cookieHeight = readCookie(cookiePath+'height'); if (cookieWidth) { restoreWidth(cookieWidth); } else if ($(".side-nav-resizable").length) { resizeWidth(); } if (cookieHeight) { restoreHeight(cookieHeight); } else { resizeHeight(); } } if (devdocNav.length) { // only dev guide and sdk highlightNav(location.href); } } function highlightNav(fullPageName) { fullPageName = fullPageName.replace(/^https?:\/\//, ''); var lastSlashPos = fullPageName.lastIndexOf("/"); var firstSlashPos = fullPageName.indexOf("/"); if (lastSlashPos == (fullPageName.length - 1)) { // if the url ends in slash (add 'index.html') fullPageName = fullPageName + "index.html"; } var htmlPos = fullPageName.lastIndexOf(".html", fullPageName.length); var pathPageName = fullPageName.slice(firstSlashPos, htmlPos + 5); var link = $("#devdoc-nav a[href$='"+ pathPageName+"']"); if ((link.length == 0) && (fullPageName.indexOf("/guide/") != -1)) { // if there's no match, then let's backstep through the directory until we find an index.html page that matches our ancestor directories (only for dev guide) lastBackstep = pathPageName.lastIndexOf("/"); while (link.length == 0) { backstepDirectory = pathPageName.lastIndexOf("/", lastBackstep); link = $("#devdoc-nav a[href$='"+ pathPageName.slice(0, backstepDirectory + 1)+"index.html']"); lastBackstep = pathPageName.lastIndexOf("/", lastBackstep - 1); if (lastBackstep == 0) break; } } link.parent().addClass('selected'); if (link.parent().parent().is(':hidden')) { toggle(link.parent().parent().parent(), false); } else if (link.parent().parent().hasClass('toggle-list')) { toggle(link.parent().parent(), false); } } function resizeHeight() { var windowHeight = ($(window).height() - HEADER_HEIGHT); var swapperHeight = windowHeight - 13; $("#swapper").css({height:swapperHeight + "px"}); sidenav.css({height:windowHeight + "px"}); content.css({height:windowHeight + "px"}); resizePackagesNav.css({maxHeight:swapperHeight + "px"}); classesNav.css({height:swapperHeight - parseInt(resizePackagesNav.css("height")) + "px"}); $("#packages-nav").css({height:parseInt(resizePackagesNav.css("height")) - 6 + "px"}); //move 6px for handle devdocNav.css({height:sidenav.css("height")}); $("#nav-tree").css({height:swapperHeight + "px"}); var basePath = getBaseUri(location.pathname); var section = basePath.substring(1,basePath.indexOf("/",1)); writeCookie("height", resizePackagesNav.css("height"), section, null); } function resizeWidth() { var windowWidth = $(window).width() + "px"; if (sidenav.length) { var sidenavWidth = sidenav.css("width"); } else { var sidenavWidth = 0; } content.css({marginLeft:parseInt(sidenavWidth) + 6 + "px", //account for 6px-wide handle-bar width:parseInt(windowWidth) - parseInt(sidenavWidth) - 6 + "px"}); resizePackagesNav.css({width:sidenavWidth}); classesNav.css({width:sidenavWidth}); $("#packages-nav").css({width:sidenavWidth}); var basePath = getBaseUri(location.pathname); var section = basePath.substring(1,basePath.indexOf("/",1)); writeCookie("width", sidenavWidth, section, null); } function resizeAll() { if (!isMobile) { resizeHeight(); if ($(".side-nav-resizable").length) { resizeWidth(); } } } function getBaseUri(uri) { var intlUrl = (uri.substring(0,6) == "/intl/"); if (intlUrl) { base = uri.substring(uri.indexOf('intl/')+5,uri.length); base = base.substring(base.indexOf('/')+1, base.length); //alert("intl, returning base url: /" + base); return ("/" + base); } else { //alert("not intl, returning uri as found."); return uri; } } function requestAppendHL(uri) { //append "?hl=<lang> to an outgoing request (such as to blog) var lang = getLangPref(); if (lang) { var q = 'hl=' + lang; uri += '?' + q; window.location = uri; return false; } else { return true; } } function loadLast(cookiePath) { var location = window.location.href; if (location.indexOf("/"+cookiePath+"/") != -1) { return true; } var lastPage = readCookie(cookiePath + "_lastpage"); if (lastPage) { window.location = lastPage; return false; } return true; } $(window).unload(function(){ var path = getBaseUri(location.pathname); if (path.indexOf("/reference/") != -1) { writeCookie("lastpage", path, "reference", null); } else if (path.indexOf("/guide/") != -1) { writeCookie("lastpage", path, "guide", null); } }); function toggle(obj, slide) { var ul = $("ul", obj); var li = ul.parent(); if (li.hasClass("closed")) { if (slide) { ul.slideDown("fast"); } else { ul.show(); } li.removeClass("closed"); li.addClass("open"); $(".toggle-img", li).attr("title", "hide pages"); } else { ul.slideUp("fast"); li.removeClass("open"); li.addClass("closed"); $(".toggle-img", li).attr("title", "show pages"); } } function buildToggleLists() { $(".toggle-list").each( function(i) { $("div", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>"); $(this).addClass("closed"); }); } function getNavPref() { var v = readCookie('reference_nav'); if (v != NAV_PREF_TREE) { v = NAV_PREF_PANELS; } return v; } function chooseDefaultNav() { nav_pref = getNavPref(); if (nav_pref == NAV_PREF_TREE) { $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); } } function swapNav() { if (nav_pref == NAV_PREF_TREE) { nav_pref = NAV_PREF_PANELS; } else { nav_pref = NAV_PREF_TREE; init_default_navtree(toRoot); } var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years writeCookie("nav", nav_pref, "reference", date.toGMTString()); $("#nav-panels").toggle(); $("#panel-link").toggle(); $("#nav-tree").toggle(); $("#tree-link").toggle(); if ($("#nav-tree").is(':visible')) scrollIntoView("nav-tree"); else { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); } } function scrollIntoView(nav) { var navObj = $("#"+nav); if (navObj.is(':visible')) { var selected = $(".selected", navObj); if (selected.length == 0) return; if (selected.is("div")) selected = selected.parent(); var scrolling = document.getElementById(nav); var navHeight = navObj.height(); var offsetTop = selected.position().top; if (selected.parent().parent().is(".toggle-list")) offsetTop += selected.parent().parent().position().top; if(offsetTop > navHeight - 92) { scrolling.scrollTop = offsetTop - navHeight + 92; } } } function toggleAllInherited(linkObj, expand) { var a = $(linkObj); var table = $(a.parent().parent().parent()); var expandos = $(".jd-expando-trigger", table); if ( (expand == null && a.text() == "[Expand]") || expand ) { expandos.each(function(i) { toggleInherited(this, true); }); a.text("[Collapse]"); } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) { expandos.each(function(i) { toggleInherited(this, false); }); a.text("[Expand]"); } return false; } function toggleAllSummaryInherited(linkObj) { var a = $(linkObj); var content = $(a.parent().parent().parent()); var toggles = $(".toggle-all", content); if (a.text() == "[Expand All]") { toggles.each(function(i) { toggleAllInherited(this, true); }); a.text("[Collapse All]"); } else { toggles.each(function(i) { toggleAllInherited(this, false); }); a.text("[Expand All]"); } return false; } function changeTabLang(lang) { var nodes = $("#header-tabs").find("."+lang); for (i=0; i < nodes.length; i++) { // for each node in this language var node = $(nodes[i]); node.siblings().css("display","none"); // hide all siblings if (node.not(":empty").length != 0) { //if this languages node has a translation, show it node.css("display","inline"); } else { //otherwise, show English instead node.css("display","none"); node.siblings().filter(".en").css("display","inline"); } } } function changeNavLang(lang) { var nodes = $("#side-nav").find("."+lang); for (i=0; i < nodes.length; i++) { // for each node in this language var node = $(nodes[i]); node.siblings().css("display","none"); // hide all siblings if (node.not(":empty").length != 0) { // if this languages node has a translation, show it node.css("display","inline"); } else { // otherwise, show English instead node.css("display","none"); node.siblings().filter(".en").css("display","inline"); } } } function changeDocLang(lang) { changeTabLang(lang); changeNavLang(lang); } function changeLangPref(lang, refresh) { var date = new Date(); expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000))); // keep this for 50 years //alert("expires: " + expires) writeCookie("pref_lang", lang, null, expires); //changeDocLang(lang); if (refresh) { l = getBaseUri(location.pathname); window.location = l; } } function loadLangPref() { var lang = readCookie("pref_lang"); if (lang != 0) { $("#language").find("option[value='"+lang+"']").attr("selected",true); } } function getLangPref() { var lang = $("#language").find(":selected").attr("value"); if (!lang) { lang = readCookie("pref_lang"); } return (lang != 0) ? lang : 'en'; } function toggleContent(obj) { var button = $(obj); var div = $(obj.parentNode); var toggleMe = $(".toggle-content-toggleme",div); if (button.hasClass("show")) { toggleMe.slideDown(); button.removeClass("show").addClass("hide"); } else { toggleMe.slideUp(); button.removeClass("hide").addClass("show"); } $("span", button).toggle(); }
JavaScript
/* API LEVEL TOGGLE */ addLoadEvent(changeApiLevel); var API_LEVEL_ENABLED_COOKIE = "api_level_enabled"; var API_LEVEL_COOKIE = "api_level"; var minLevel = 1; function toggleApiLevelSelector(checkbox) { var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years var expiration = date.toGMTString(); if (checkbox.checked) { $("#apiLevelSelector").removeAttr("disabled"); $("#api-level-toggle label").removeClass("disabled"); writeCookie(API_LEVEL_ENABLED_COOKIE, 1, null, expiration); } else { $("#apiLevelSelector").attr("disabled","disabled"); $("#api-level-toggle label").addClass("disabled"); writeCookie(API_LEVEL_ENABLED_COOKIE, 0, null, expiration); } changeApiLevel(); } function buildApiLevelSelector() { var maxLevel = SINCE_DATA.length; var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE); var userApiLevel = readCookie(API_LEVEL_COOKIE); userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default if (userApiLevelEnabled == 0) { $("#apiLevelSelector").attr("disabled","disabled"); } else { $("#apiLevelCheckbox").attr("checked","checked"); $("#api-level-toggle label").removeClass("disabled"); } minLevel = $("body").attr("class"); var select = $("#apiLevelSelector").html("").change(changeApiLevel); for (var i = maxLevel-1; i >= 0; i--) { var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]); // if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames) select.append(option); } // get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true) var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0); selectedLevelItem.setAttribute('selected',true); } function changeApiLevel() { var maxLevel = SINCE_DATA.length; var userApiLevelEnabled = readCookie(API_LEVEL_ENABLED_COOKIE); var selectedLevel = maxLevel; if (userApiLevelEnabled == 0) { toggleVisisbleApis(selectedLevel, "body"); } else { selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "body"); var date = new Date(); date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years var expiration = date.toGMTString(); writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration); } if (selectedLevel < minLevel) { var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class"; $("#naMessage").show().html("<div><p><strong>This " + thing + " is not available with API Level " + selectedLevel + ".</strong></p>" + "<p>To use this " + thing + ", your application must specify API Level " + minLevel + " or higher in its manifest " + "and be compiled against a version of the Android library that supports an equal or higher API Level. To reveal this " + "document, change the value of the API Level filter above.</p>" + "<p><a href='" +toRoot+ "guide/appendix/api-levels.html'>What is the API Level?</a></p></div>"); } else { $("#naMessage").hide(); } } function toggleVisisbleApis(selectedLevel, context) { var apis = $(".api",context); apis.each(function(i) { var obj = $(this); var className = obj.attr("class"); var apiLevelIndex = className.lastIndexOf("-")+1; var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex); apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length; var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex); if (apiLevel > selectedLevel) obj.addClass("absent").attr("title","Requires API Level "+apiLevel+" or higher"); else obj.removeClass("absent").removeAttr("title"); }); } /* NAVTREE */ function new_node(me, mom, text, link, children_data, api_level) { var node = new Object(); node.children = Array(); node.children_data = children_data; node.depth = mom.depth + 1; node.li = document.createElement("li"); mom.get_children_ul().appendChild(node.li); node.label_div = document.createElement("div"); node.label_div.className = "label"; if (api_level != null) { $(node.label_div).addClass("api"); $(node.label_div).addClass("api-level-"+api_level); } node.li.appendChild(node.label_div); node.label_div.style.paddingLeft = 10*node.depth + "px"; if (children_data == null) { // 12 is the width of the triangle and padding extra space node.label_div.style.paddingLeft = ((10*node.depth)+12) + "px"; } else { node.label_div.style.paddingLeft = 10*node.depth + "px"; node.expand_toggle = document.createElement("a"); node.expand_toggle.href = "javascript:void(0)"; node.expand_toggle.onclick = function() { if (node.expanded) { $(node.get_children_ul()).slideUp("fast"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.expanded = false; } else { expand_node(me, node); } }; node.label_div.appendChild(node.expand_toggle); node.plus_img = document.createElement("img"); node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png"; node.plus_img.className = "plus"; node.plus_img.border = "0"; node.expand_toggle.appendChild(node.plus_img); node.expanded = false; } var a = document.createElement("a"); node.label_div.appendChild(a); node.label = document.createTextNode(text); a.appendChild(node.label); if (link) { a.href = me.toroot + link; } else { if (children_data != null) { a.className = "nolink"; a.href = "javascript:void(0)"; a.onclick = node.expand_toggle.onclick; // This next line shouldn't be necessary. I'll buy a beer for the first // person who figures out how to remove this line and have the link // toggle shut on the first try. --joeo@android.com node.expanded = false; } } node.children_ul = null; node.get_children_ul = function() { if (!node.children_ul) { node.children_ul = document.createElement("ul"); node.children_ul.className = "children_ul"; node.children_ul.style.display = "none"; node.li.appendChild(node.children_ul); } return node.children_ul; }; return node; } function expand_node(me, node) { if (node.children_data && !node.expanded) { if (node.children_visited) { $(node.get_children_ul()).slideDown("fast"); } else { get_node(me, node); if ($(node.label_div).hasClass("absent")) $(node.get_children_ul()).addClass("absent"); $(node.get_children_ul()).slideDown("fast"); } node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png"; node.expanded = true; // perform api level toggling because new nodes are new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } } function get_node(me, mom) { mom.children_visited = true; for (var i in mom.children_data) { var node_data = mom.children_data[i]; mom.children[i] = new_node(me, mom, node_data[0], node_data[1], node_data[2], node_data[3]); } } function this_page_relative(toroot) { var full = document.location.pathname; var file = ""; if (toroot.substr(0, 1) == "/") { if (full.substr(0, toroot.length) == toroot) { return full.substr(toroot.length); } else { // the file isn't under toroot. Fail. return null; } } else { if (toroot != "./") { toroot = "./" + toroot; } do { if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") { var pos = full.lastIndexOf("/"); file = full.substr(pos) + file; full = full.substr(0, pos); toroot = toroot.substr(0, toroot.length-3); } } while (toroot != "" && toroot != "/"); return file.substr(1); } } function find_page(url, data) { var nodes = data; var result = null; for (var i in nodes) { var d = nodes[i]; if (d[1] == url) { return new Array(i); } else if (d[2] != null) { result = find_page(url, d[2]); if (result != null) { return (new Array(i).concat(result)); } } } return null; } function load_navtree_data(toroot) { var navtreeData = document.createElement("script"); navtreeData.setAttribute("type","text/javascript"); navtreeData.setAttribute("src", toroot+"navtree_data.js"); $("head").append($(navtreeData)); } function init_default_navtree(toroot) { init_navtree("nav-tree", toroot, NAVTREE_DATA); // perform api level toggling because because the whole tree is new to the DOM var selectedLevel = $("#apiLevelSelector option:selected").val(); toggleVisisbleApis(selectedLevel, "#side-nav"); } function init_navtree(navtree_id, toroot, root_nodes) { var me = new Object(); me.toroot = toroot; me.node = new Object(); me.node.li = document.getElementById(navtree_id); me.node.children_data = root_nodes; me.node.children = new Array(); me.node.children_ul = document.createElement("ul"); me.node.get_children_ul = function() { return me.node.children_ul; }; //me.node.children_ul.className = "children_ul"; me.node.li.appendChild(me.node.children_ul); me.node.depth = 0; get_node(me, me.node); me.this_page = this_page_relative(toroot); me.breadcrumbs = find_page(me.this_page, root_nodes); if (me.breadcrumbs != null && me.breadcrumbs.length != 0) { var mom = me.node; for (var i in me.breadcrumbs) { var j = me.breadcrumbs[i]; mom = mom.children[j]; expand_node(me, mom); } mom.label_div.className = mom.label_div.className + " selected"; addLoadEvent(function() { scrollIntoView("nav-tree"); }); } } /* TOGGLE INHERITED MEMBERS */ /* Toggle an inherited class (arrow toggle) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleInherited(linkObj, expand) { var base = linkObj.getAttribute("id"); var list = document.getElementById(base + "-list"); var summary = document.getElementById(base + "-summary"); var trigger = document.getElementById(base + "-trigger"); var a = $(linkObj); if ( (expand == null && a.hasClass("closed")) || expand ) { list.style.display = "none"; summary.style.display = "block"; trigger.src = toRoot + "assets/images/triangle-opened.png"; a.removeClass("closed"); a.addClass("opened"); } else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) { list.style.display = "block"; summary.style.display = "none"; trigger.src = toRoot + "assets/images/triangle-closed.png"; a.removeClass("opened"); a.addClass("closed"); } return false; } /* Toggle all inherited classes in a single table (e.g. all inherited methods) * @param linkObj The link that was clicked. * @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed. * 'null' to simply toggle. */ function toggleAllInherited(linkObj, expand) { var a = $(linkObj); var table = $(a.parent().parent().parent()); // ugly way to get table/tbody var expandos = $(".jd-expando-trigger", table); if ( (expand == null && a.text() == "[Expand]") || expand ) { expandos.each(function(i) { toggleInherited(this, true); }); a.text("[Collapse]"); } else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) { expandos.each(function(i) { toggleInherited(this, false); }); a.text("[Expand]"); } return false; } /* Toggle all inherited members in the class (link in the class title) */ function toggleAllClassInherited() { var a = $("#toggleAllClassInherited"); // get toggle link from class title var toggles = $(".toggle-all", $("#doc-content")); if (a.text() == "[Expand All]") { toggles.each(function(i) { toggleAllInherited(this, true); }); a.text("[Collapse All]"); } else { toggles.each(function(i) { toggleAllInherited(this, false); }); a.text("[Expand All]"); } return false; } /* Expand all inherited members in the class. Used when initiating page search */ function ensureAllInheritedExpanded() { var toggles = $(".toggle-all", $("#doc-content")); toggles.each(function(i) { toggleAllInherited(this, true); }); $("#toggleAllClassInherited").text("[Collapse All]"); } /* HANDLE KEY EVENTS * - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search) */ var agent = navigator['userAgent'].toLowerCase(); var mac = agent.indexOf("macintosh") != -1; $(document).keydown( function(e) { var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key if (control && e.which == 70) { // 70 is "F" ensureAllInheritedExpanded(); } });
JavaScript
var gSelectedIndex = -1; var gSelectedID = -1; var gMatches = new Array(); var gLastText = ""; var ROW_COUNT = 20; var gInitialized = false; var DEFAULT_TEXT = "search developer docs"; function set_row_selected(row, selected) { var c1 = row.cells[0]; // var c2 = row.cells[1]; if (selected) { c1.className = "jd-autocomplete jd-selected"; // c2.className = "jd-autocomplete jd-selected jd-linktype"; } else { c1.className = "jd-autocomplete"; // c2.className = "jd-autocomplete jd-linktype"; } } function set_row_values(toroot, row, match) { var link = row.cells[0].childNodes[0]; link.innerHTML = match.__hilabel || match.label; link.href = toroot + match.link // row.cells[1].innerHTML = match.type; } function sync_selection_table(toroot) { var filtered = document.getElementById("search_filtered"); var r; //TR DOM object var i; //TR iterator gSelectedID = -1; filtered.onmouseover = function() { if(gSelectedIndex >= 0) { set_row_selected(this.rows[gSelectedIndex], false); gSelectedIndex = -1; } } //initialize the table; draw it for the first time (but not visible). if (!gInitialized) { for (i=0; i<ROW_COUNT; i++) { var r = filtered.insertRow(-1); var c1 = r.insertCell(-1); // var c2 = r.insertCell(-1); c1.className = "jd-autocomplete"; // c2.className = "jd-autocomplete jd-linktype"; var link = document.createElement("a"); c1.onmousedown = function() { window.location = this.firstChild.getAttribute("href"); } c1.onmouseover = function() { this.className = this.className + " jd-selected"; } c1.onmouseout = function() { this.className = "jd-autocomplete"; } c1.appendChild(link); } /* var r = filtered.insertRow(-1); var c1 = r.insertCell(-1); c1.className = "jd-autocomplete jd-linktype"; c1.colSpan = 2; */ gInitialized = true; } //if we have results, make the table visible and initialize result info if (gMatches.length > 0) { document.getElementById("search_filtered_div").className = "showing"; var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT; for (i=0; i<N; i++) { r = filtered.rows[i]; r.className = "show-row"; set_row_values(toroot, r, gMatches[i]); set_row_selected(r, i == gSelectedIndex); if (i == gSelectedIndex) { gSelectedID = gMatches[i].id; } } //start hiding rows that are no longer matches for (; i<ROW_COUNT; i++) { r = filtered.rows[i]; r.className = "no-display"; } //if there are more results we're not showing, so say so. /* if (gMatches.length > ROW_COUNT) { r = filtered.rows[ROW_COUNT]; r.className = "show-row"; c1 = r.cells[0]; c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more"; } else { filtered.rows[ROW_COUNT].className = "hide-row"; }*/ //if we have no results, hide the table } else { document.getElementById("search_filtered_div").className = "no-display"; } } function search_changed(e, kd, toroot) { var search = document.getElementById("search_autocomplete"); var text = search.value.replace(/(^ +)|( +$)/g, ''); // 13 = enter if (e.keyCode == 13) { document.getElementById("search_filtered_div").className = "no-display"; if (kd && gSelectedIndex >= 0) { window.location = toroot + gMatches[gSelectedIndex].link; return false; } else if (gSelectedIndex < 0) { return true; } } // 38 -- arrow up else if (kd && (e.keyCode == 38)) { if (gSelectedIndex >= 0) { gSelectedIndex--; } sync_selection_table(toroot); return false; } // 40 -- arrow down else if (kd && (e.keyCode == 40)) { if (gSelectedIndex < gMatches.length-1 && gSelectedIndex < ROW_COUNT-1) { gSelectedIndex++; } sync_selection_table(toroot); return false; } else if (!kd) { gMatches = new Array(); matchedCount = 0; gSelectedIndex = -1; for (var i=0; i<DATA.length; i++) { var s = DATA[i]; if (text.length != 0 && s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) { gMatches[matchedCount] = s; matchedCount++; } } rank_autocomplete_results(text); for (var i=0; i<gMatches.length; i++) { var s = gMatches[i]; if (gSelectedID == s.id) { gSelectedIndex = i; } } highlight_autocomplete_result_labels(text); sync_selection_table(toroot); return true; // allow the event to bubble up to the search api } } function rank_autocomplete_results(query) { query = query || ''; if (!gMatches || !gMatches.length) return; // helper function that gets the last occurence index of the given regex // in the given string, or -1 if not found var _lastSearch = function(s, re) { if (s == '') return -1; var l = -1; var tmp; while ((tmp = s.search(re)) >= 0) { if (l < 0) l = 0; l += tmp; s = s.substr(tmp + 1); } return l; }; // helper function that counts the occurrences of a given character in // a given string var _countChar = function(s, c) { var n = 0; for (var i=0; i<s.length; i++) if (s.charAt(i) == c) ++n; return n; }; var queryLower = query.toLowerCase(); var queryAlnum = (queryLower.match(/\w+/) || [''])[0]; var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum); var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b'); var _resultScoreFn = function(result) { // scores are calculated based on exact and prefix matches, // and then number of path separators (dots) from the last // match (i.e. favoring classes and deep package names) var score = 1.0; var labelLower = result.label.toLowerCase(); var t; t = _lastSearch(labelLower, partExactAlnumRE); if (t >= 0) { // exact part match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 200 / (partsAfter + 1); } else { t = _lastSearch(labelLower, partPrefixAlnumRE); if (t >= 0) { // part prefix match var partsAfter = _countChar(labelLower.substr(t + 1), '.'); score *= 20 / (partsAfter + 1); } } return score; }; for (var i=0; i<gMatches.length; i++) { gMatches[i].__resultScore = _resultScoreFn(gMatches[i]); } gMatches.sort(function(a,b){ var n = b.__resultScore - a.__resultScore; if (n == 0) // lexicographical sort if scores are the same n = (a.label < b.label) ? -1 : 1; return n; }); } function highlight_autocomplete_result_labels(query) { query = query || ''; if (!gMatches || !gMatches.length) return; var queryLower = query.toLowerCase(); var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0]; var queryRE = new RegExp( '(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig'); for (var i=0; i<gMatches.length; i++) { gMatches[i].__hilabel = gMatches[i].label.replace( queryRE, '<b>$1</b>'); } } function search_focus_changed(obj, focused) { if (focused) { if(obj.value == DEFAULT_TEXT){ obj.value = ""; obj.style.color="#000000"; } } else { if(obj.value == ""){ obj.value = DEFAULT_TEXT; obj.style.color="#aaaaaa"; } document.getElementById("search_filtered_div").className = "no-display"; } } function submit_search() { var query = document.getElementById('search_autocomplete').value; document.location = toRoot + 'search.html#q=' + query + '&t=0'; return false; }
JavaScript
/* file: carousel.js date: oct 2008 author: jeremydw,smain info: operates the carousel widget for announcements on the android developers home page. modified from the original market.js from jeremydw. */ /* -- video switcher -- */ var oldVid = "multi"; // set the default video var nowPlayingString = "Now playing:"; var assetsRoot = "assets/"; /* -- app thumbnail switcher -- */ var currentDroid; var oldDroid; // shows a random application function randomDroid(){ // count the total number of apps var droidListLength = 0; for (var k in droidList) droidListLength++; // pick a random app and show it var j = 0; var i = Math.floor(droidListLength*Math.random()); for (var x in droidList) { if(j++ == i){ currentDroid = x; showPreview(x); centerSlide(x); } } } // shows a bulletin, swaps the carousel highlighting function droid(appName){ oldDroid = $("#droidlink-"+currentDroid); currentDroid = appName; var droid = droidList[appName]; $("#"+appName).show().siblings().hide(); if(oldDroid) oldDroid.removeClass("selected"); $("#droidlink-"+appName).addClass("selected"); } // -- * build the carousel based on the droidList * -- // function buildCarousel() { var appList = document.getElementById("app-list"); for (var x in droidList) { var droid = droidList[x]; var icon = droid.icon; var name = droid.name; var a = document.createElement("a"); var img = document.createElement("img"); var br = document.createElement("br"); var span = document.createElement("span"); var text = document.createTextNode(droid.name); a.setAttribute("id", "droidlink-" + x); a.className = x; a.setAttribute("href", "#"); a.onclick = function() { showPreview(this.className); return false; } img.setAttribute("src", toRoot + assetsRoot + "images/home/" + droid.icon); img.setAttribute("alt", ""); span.appendChild(text); a.appendChild(img); a.appendChild(br); a.appendChild(span); appList.appendChild(a); /* add the bulletins */ var layout = droid.layout; var div = document.createElement("div"); var imgDiv = document.createElement("div"); var descDiv = document.createElement("div"); div.setAttribute("id", x); div.setAttribute("style", "display:none"); imgDiv.setAttribute("class", "bulletinImg"); descDiv.setAttribute("class", "bulletinDesc"); if (layout == "imgLeft") { $(imgDiv).addClass("img-left"); $(descDiv).addClass("desc-right"); } else if (layout == "imgTop") { $(imgDiv).addClass("img-top"); $(descDiv).addClass("desc-bottom"); } else if (layout == "imgRight") { $(imgDiv).addClass("img-right"); $(descDiv).addClass("desc-left"); } imgDiv.innerHTML = "<img src='" + toRoot + assetsRoot + "images/home/" + droid.img + "'>"; descDiv.innerHTML = (droid.title != "") ? "<h3>" + droid.title + "</h3>" + droid.desc : droid.desc; $(div).append(imgDiv); $(div).append(descDiv); $("#carouselMain").append(div); } } // -- * slider * -- // // -- dependencies: // (1) div containing slides, (2) a "clip" div to hide the scroller // (3) control arrows // -- * config below * -- // var slideCode = droidList; // the dictionary of slides var slideList = 'app-list'; // the div containing the slides var arrowRight = 'arrow-right'; // the right control arrow var arrowLeft = 'arrow-left'; // the left control arrow function showPreview(slideName) { centerSlide(slideName); if (slideName.indexOf('selected') != -1) { return false; } droid(slideName); // do this function when slide is clicked } var thumblist = document.getElementById(slideList);// the div containing the slides var slideWidth = 144; // width of a slide including all margins, etc. var slidesAtOnce = 3; // no. of slides to appear at once (requires odd number to have a centered slide) // -- * no editing should be needed below * -- // var originPosition = {}; var is_animating = 0; var currentStripPosition = 0; var centeringPoint = 0; var rightScrollLimit = 0; // makeSlideStrip() // - figures out how many slides there are // - determines the centering point of the slide strip function makeSlideStrip() { var slideTotal = 0; centeringPoint = Math.ceil(slidesAtOnce/2); for (var x in slideCode) { slideTotal++; } var i = 0; for (var code in slideCode) { if (i <= centeringPoint-1) { originPosition[code] = 0; } else { if (i >= slideTotal-centeringPoint+1) { originPosition[code] = (slideTotal-slidesAtOnce)*slideWidth; } else { originPosition[code] = (i-centeringPoint+1)*slideWidth; } } i++; } rightScrollLimit = -1*(slideTotal-slidesAtOnce)*slideWidth; } // slides with acceleration function slide(goal, id, go_left, cp) { var div = document.getElementById(id); var animation = {}; animation.time = 0.5; // in seconds animation.fps = 60; animation.goal = goal; origin = 0.0; animation.origin = Math.abs(origin); animation.frames = (animation.time * animation.fps) - 1.0; var current_frame = 0; var motions = Math.abs(animation.goal - animation.origin); function animate() { var ease_right = function (t) { return (1 - Math.cos(t * Math.PI))/2.0; }; var ease = ease_right; if (go_left == 1) { ease = function(t) { return 1.0 - ease_right(t); }; } var left = (ease(current_frame/animation.frames) * Math.abs(animation.goal - animation.origin)) - cp; if(left < 0) { left = 0; } if(!isNaN(left)) { div.style.left = '-' + Math.round(left) + 'px'; } current_frame += 1; if (current_frame == animation.frames) { is_animating = 0; window.clearInterval(timeoutId) } } var timeoutId = window.setInterval(animate, animation.time/animation.fps * 1000); } //Get style property function getStyle(element, cssProperty){ var elem = document.getElementById(element); if(elem.currentStyle){ return elem.currentStyle[cssProperty]; //IE } else{ var style = document.defaultView.getComputedStyle(elem, null); //firefox, Opera return style.getPropertyValue(cssProperty); } } // Left and right arrows function page_left() { var amount = slideWidth; animateSlide(amount, 'left'); } function page_right() { var amount = slideWidth; animateSlide(amount, 'right'); } // animates the strip // - sets arrows to on or off function animateSlide(amount,dir) { var currentStripPosition = parseInt(getStyle(slideList,'left')); var motionDistance; if (amount == slideWidth ) { motionDistance = slideWidth; } else { motionDistance = amount; } var rightarrow = document.getElementById(arrowRight); var leftarrow = document.getElementById(arrowLeft); function aToggle(state,aDir) { if (state == 'on') { if (aDir =='right') { rightarrow.className = 'arrow-right-on'; rightarrow.href = "javascript:page_right()"; } else { leftarrow.className = 'arrow-left-on'; leftarrow.href = "javascript:page_left()"; } } else { if (aDir =='right') { rightarrow.href = "javascript:{}"; rightarrow.className = 'arrow-right-off'; } else { leftarrow.href = "javascript:{}"; leftarrow.className = 'arrow-left-off'; } } } function arrowChange(rP) { if (rP >= rightScrollLimit) { aToggle('on','right'); } if (rP <= rightScrollLimit) { aToggle('off','right'); } if (rP <= slideWidth) { aToggle('on','left'); } if (rP >= 0) { aToggle('off','left'); } } if (dir == 'right' && is_animating == 0) { arrowChange(currentStripPosition-motionDistance); is_animating = 1; slide(motionDistance, slideList, 0, currentStripPosition); } else if (dir == 'left' && is_animating == 0) { arrowChange(currentStripPosition+motionDistance); is_animating = 1; rightStripPosition = currentStripPosition + motionDistance; slide(motionDistance, slideList, 1, rightStripPosition); } } function centerSlide(slideName) { var currentStripPosition = parseInt(getStyle(slideList,'left')); var dir = 'left'; var originpoint = Math.abs(currentStripPosition); if (originpoint <= originPosition[slideName]) { dir = 'right'; } var motionValue = Math.abs(originPosition[slideName]-originpoint); animateSlide(motionValue,dir); } function initCarousel(def) { buildCarousel(); showPreview(def); makeSlideStrip(); }
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. function setUploadPanelVisibility(visibility, focusInput) { var up = document.getElementById("uploadPanel"); // first check current visibility state of the panel var orgVisibility = up.style.display !== "none"; if (orgVisibility === visibility) return; var animationStep = 17; var animationLength = 150; var maxCallcount = animationLength / animationStep + 5; var animationStart = new Date(); var callCount = 0; // we can't get clientHeight when not yet visible so we show // it before setting its top value up.style.display = "block"; // get the height of the upload panel var h = up.clientHeight; // start an interval to do the animation var itv = setInterval(function () { ++callCount; var elapsed = new Date() - animationStart; // we stop the animation as soon as either we have been called // too many times or when we have reached the end of animation // time if (elapsed >= animationLength || callCount > maxCallcount) { // ensure we are no more called clearInterval(itv); // in all cases reset top value to 0 up.style.top = "0"; // if we were hiding the panel, hide it now if (! visibility) up.style.display = "none"; // update style of toggle button var uploadButton = document.getElementById("uploadButton"); uploadButton.className = visibility ? "pressed" : ""; // if requested and if we made the panel visible, give the // focus to file chooser if (visibility && focusInput) document.getElementById("filechooser").focus(); // ensure links to files are focusable or not focusable // depending on the visibility of the panel var links = document.getElementById("pageContent") .getElementsByTagName("a"); var newIndex = visibility ? -1 : 0; for (var linkIdx = 0; linkIdx < links.length; ++linkIdx) { var link = links[linkIdx]; link.tabIndex = newIndex; } } // compute the top value var frac = elapsed / animationLength; if (frac < 0) frac = 0; else if (frac > 1) frac = 1; var top = -1 * Math.round(h * (visibility ? (1 - frac) : frac)); up.style.top = top + "px"; }, 17); } function toggleUploadPanelVisibility() { var up = document.getElementById("uploadPanel"); // first check current visibility state of the panel var orgVisibility = up.style.display !== "none"; // chane panel visibility setUploadPanelVisibility(! orgVisibility, true); } function updateDates() { var spans = document.getElementsByTagName("span"); for (var spanIdx = 0; spanIdx < spans.length; ++spanIdx) { var span = spans[spanIdx]; if (span.className === "date") { var date = new Date(span.innerHTML); span.innerHTML = date.toLocaleString(); } } }
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. function tokens(s) { ret = []; var tokenStart = -1; var tokenStr = false; for (var i = 0; i < s.length; ++i) { var c = s.charAt(i); var cc = s.charCodeAt(i); if (cc == 0x22) { if (tokenStr) { ret.push(s.slice(tokenStart + 1, i)) tokenStart = -1; tokenStr = false; } else { if (tokenStart >= 0) ret.push(s.slice(tokenStart, i)); tokenStart = i; tokenStr = true; } } else if (cc == 0x20) { if (! tokenStr) { if (tokenStart >= 0) { ret.push(s.slice(tokenStart, i)); tokenStart = -1; } } } else if (cc >= 40 && cc <= 41 || cc == 44 || cc >= 58 && cc <= 64 || cc >= 91 && cc <= 93) { if (! tokenStr) { if (tokenStart >= 0) { ret.push(s.slice(tokenStart, i)); ret.push(c); } else ret.push(s.slice(i, i+1)); tokenStart = -1; } } else if (tokenStart < 0) tokenStart = i; } if (tokenStart >= 0) ret.push(s.slice(tokenStart)); return ret; } function ContentType(type) { this.type = type; this.parameters = {}; } ContentType.prototype.toString = function () { var ret = '{ type: '; if (this.type === undefined) ret += "undefined"; else ret += '"' + this.type + '"'; ret += ", parameters: {"; var first = true; for (var p in this.parameters) { if (! this.parameters.hasOwnProperty(p)) continue; if (first) { ret += " "; first = false; } else ret += ", "; ret += p; ret += ": "; ret += '"' + this.parameters[p] + '"'; } if (! first) ret += ' '; ret += '} }'; return ret; } function parseContentTypeTks(contentTypeTks) { var ret = new ContentType(); // the type is the first token ret.type = contentTypeTks[0]; // parse parameters var i = 1; while (i < contentTypeTks.length) { // stop on first encoding error if (contentTypeTks[i] != ';') break; // go to next token ++i; if (i >= contentTypeTks.length) break; // get attribute var attr = contentTypeTks[i]; // go to next token ++i; if (i >= contentTypeTks.length) break; // break is not expected token if (contentTypeTks[i] != '=') break; // go to next token ++i; if (i >= contentTypeTks.length) break; // get value var val = contentTypeTks[i]; ret.parameters[attr] = val; // go to next token ++i; } return ret; } function parseContentType(contentType) { var tks = tokens(contentType); return parseContentTypeTks(tks); } var MimeParser = (function () { function findDelimiter(buffer, delimiter, start) { for (var i = start; i <= buffer.length - delimiter.length; ++i) { var di = 0; for (; di < delimiter.length; ++di) { if (buffer[i+di] != delimiter.charCodeAt(di)) { break; } } if (di == delimiter.length) return i; } return -1; } function bypassPreamble() { var start = 0; var delimiterIdx = -1; while (1) { var delimiterIdx = findDelimiter(this.buffer, this.dashBoundary, start); if (delimiterIdx == -1) return; if (delimiterIdx == 0) break; if (delimiterIdx == 1) start = 2 else if (this.buffer[delimiterIdx - 1] == 0xA && this.buffer[delimiterIdx - 2] == 0xD) break; else start = delimiterIdx + 1; } this.buffer = this.buffer.slice(delimiterIdx); return parseBoundaryLine; } function parseBoundaryLine() { var eol = findDelimiter(this.buffer, "\r\n", 0); if (eol == -1) return; if (eol >= this.dashBoundary.length + 2 && this.buffer[this.dashBoundary.length] == 45 && this.buffer[this.dashBoundary.length + 1] == 45) { return parseEnd; } this.buffer = this.buffer.slice(eol + 2); return parseHeaders; } function parseHeaders() { var eol = findDelimiter(this.buffer, "\r\n", 0); if (eol == -1) return; else if (eol == 0) { // we reached last line of header this.buffer = this.buffer.slice(eol + 2); return parseBytes; } else { // line to decode var tks = tokens(this.buffer.slice(0, eol).toString()); if (tks.length >= 3) { this.partHeaders[tks[0].toLowerCase()] = parseContentTypeTks(tks.slice(2)); } // continue iteration this.buffer = this.buffer.slice(eol + 2); return parseHeaders; } } function parseBytes() { var limit = findDelimiter(this.buffer, "\r\n" + this.dashBoundary, 0); if (limit == -1) return; this.onPart(this.partHeaders, this.buffer.slice(0, limit)); this.partHeaders = {}; this.buffer = this.buffer.slice(limit + 2); return parseBoundaryLine; } function parseEnd() { this.buffer = new Buffer(0); } function MimeParser(boundary, onPart) { this.buffer = new Buffer(0); this.dashBoundary = '--' + boundary; this.updateFunction = bypassPreamble; this.partHeaders = {}; this.onPart = onPart; }; MimeParser.prototype.update = function (chunck) { this.buffer = Buffer.concat([this.buffer, chunck]); while (true) { var func = this.updateFunction(); if (func === undefined) break; this.updateFunction = func; } }; return MimeParser; })(); exports.parseContentType = parseContentType; exports.MimeParser = MimeParser; exports.ContentType = ContentType;
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. assert = require('assert'); var template = require('../3ds-template.js'); assert.equal(template.apply('test${b} de ce ${_0}', {b:3, _0:'_'}), 'test3 de ce _'); assert.equal(template.apply('test${b} de ce $${_0}', {b:3, _0:'_'}), 'test3 de ce $${_0}');
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>.
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. mime = require('../3ds-mime.js'); assert = require('assert'); assert.deepEqual(mime.parseContentType(' multipart/mixed; boundary="simple boundary"'), { type: 'multipart/mixed', parameters: { boundary:'simple boundary' } }); assert.strictEqual(mime.parseContentType(' multipart/mixed; boundary="simple boundary"').toString(), '{ type: "multipart/mixed", parameters: { boundary: "simple boundary" } }'); assert.deepEqual(mime.parseContentType('multipart/mixed; boundary=simple'), { type: 'multipart/mixed', parameters: { boundary: 'simple' } }); assert.deepEqual(mime.parseContentType('text/svg+xml; charset=utf-8;u=2'), { type: 'text/svg+xml', parameters: { charset: 'utf-8', u: '2' } }); assert.strictEqual(mime.parseContentType('text/svg+xml; charset=utf-8;u=2').toString(), '{ type: "text/svg+xml", parameters: { charset: "utf-8", u: "2" } }'); // var defaultContentType = 'text/plain; charset=US-ASCII'; // 'Content-Transfer-Encoding' // maxLen = 72
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. var http = require('http'); var url = require('url'); var fs = require('fs'); var path = require('path'); var template = require('./3ds-template.js'); var mime = require('./3ds-mime.js'); var assert = require('assert'); function filesize2string(filesize) { if (filesize <= 1) return filesize + " byte"; if (filesize < 1024) return filesize + " bytes"; if (filesize < 1024*1024) return Math.floor(filesize / 1024) + " Kb"; if (filesize < 1024*1024*1024) return Math.floor(filesize / 1024 / 1024) + " Mb"; return Math.floor(filesize / 1024 / 1024 / 1024) + " Gb"; } assert.equal(filesize2string(0), "0 byte"); assert.equal(filesize2string(1), "1 byte"); assert.equal(filesize2string(2), "2 bytes"); assert.equal(filesize2string(1023), "1023 bytes"); assert.equal(filesize2string(1024), "1 Kb"); assert.equal(filesize2string(1024*1024 - 1), "1023 Kb"); assert.equal(filesize2string(1024*1024), "1 Mb"); assert.equal(filesize2string(1024*1024*1024 - 1), "1023 Mb"); assert.equal(filesize2string(1024*1024*1024), "1 Gb"); function sendHtml(response, code, str) { var buffer = new Buffer(str); response.writeHead(code, { "Content-Type": "text/html; charset=UTF-8", "Content-Length": buffer.length, 'Cache-Control': 'max-age=10', }); response.end(buffer); } function sendErr(response, code, msg) { sendTemplateFile(response, code, 'text/html; charset=UTF-8', '3ds-server-err.html', { desc: http.STATUS_CODES[code], code: code, msg: msg, }, true); } function sendFile(response, code, type, filename) { fs.readFile(path.resolve(scriptDir, filename), function (err, content) { if (err === null) { response.writeHead('200', { 'Content-Type': type, 'Content-Length': content.length, 'Cache-Control': 'max-age=10', // 'Pragma': 'no-cache' }); response.end(content); } else sendErr(response, 500, "Can't read the file: " + err); }); } function sendTemplateFile(response, code, type, filename, values, fromSendErr) { fs.readFile(path.resolve(scriptDir, filename), function (err, content) { if (err === null) { // extract charset from content type var charset = mime.parseContentType(type).parameters.charset; if (charset === undefined) charset = 'utf8'; // decode buffer using charset var str = content.toString(charset); // apply the template str = template.apply(str, values); // encode the result in charset content = new Buffer(str, charset); response.writeHead(code, { 'Content-Type': type, 'Content-Length': content.length, 'Cache-Control': 'max-age=10', // 'Pragma': 'no-cache' }); response.end(content); } else { if (fromSendErr) { console.log('Loop in send err'); response.writeHead('500', { 'Content-Type': 'text/plain; charset=UTF-8', 'Cache-Control': 'max-age=10', // 'Pragma': 'no-cache' }); response.end("Can't read the file: " + err); } else sendErr(response, 500, "Can't read the file: " + err); } }); } function parseCmdLine() { // configuration of acception options; the `flag' property of // options indicates that the option is only a flag that don't // expect argument, if false then the next argument in the line // will be the option value. config = { '-d': { flag:false, id:'dir' }, '--dir': { flag:false, id:'dir' }, }; // the returned object of this function var ret = { options: {}, args: [], err: undefined, scriptDir: path.dirname(process.argv[1]) }; // the start state function start(arg) { if (arg[0] === '-') { if (! config.hasOwnProperty(arg)) { // a string result indicates an error return 'Option "' + arg + '" does not exists'; } var argConf = config[arg]; if (argConf.flag) ret.options[argConf.id] = true; else { return newArgValState(argConf); } } else ret.args.push(arg); } // a function that build the state of the parsing of a non flag // option function newArgValState(argConf) { return function (arg) { ret.options[argConf.id] = arg; return start; } } // initialize the initial state var state = start; // loop on arguments for (var ai = 2; ai < process.argv.length; ++ai) { var newState = state(process.argv[ai]); // update the state if a new one is provided if (typeof newState === 'string') { // string state is an error message; we return an object // with only an err object return { err: newState }; } else if (newState !== undefined) state = newState; } return ret; } // Function take from html5 specification function extractFilename(path) { if (path.substr(0, 12) == "C:\\fakepath\\") return path.substr(12); // modern browser var x; x = path.lastIndexOf('/'); if (x >= 0) // Unix-based path return path.substr(x+1); x = path.lastIndexOf('\\'); if (x >= 0) // Windows-based path return path.substr(x+1); return path; // just the filename } function handleUpload(request, response) { // parse content type to obtain boundary delimiter var ct = request.headers['content-type']; if (ct === undefined) { sendErr(response, 400, 'No Content-Type header in request.'); return; } ct = mime.parseContentType(ct); if (ct.type !== 'multipart/form-data') { sendErr(response, 400, 'Expect multipart/form-data type of content, got ' + ct.type + '.'); return; } var boundary = ct.parameters.boundary; if (boundary === undefined) { sendErr(response, 400, 'No boundary parameter along multipart/form-data type of content.'); return; } // here we start asynchronous actions to save data to // files; for each pending action we increment the // pendingOperations variable and decrement it when // this action is called. When this counter reaches 0, // there is no more pending actions s the response can // finally be returned; this is what sendEnd() do. // // Note that pendingOperations count is initially 1 // since we are also waiting for "end" event. var pendingOperations = 1; // instantiate MIME parser var uploadErr; function setUploadErr(err) { if (uploadErr === undefined) uploadErr = "" + err; } function sendEnd() { if (uploadErr !== undefined) { sendErr(response, 500, uploadErr); } else { var url = "/"; var html = '<!doctype html><html><head><meta charset="utf-8"><title>Redirecting: File successfully uploaded</title></head><body><h1>Redirecting: File successfully uploaded</h1><p>File successfully uploaded, you should have been redirected now, <a href="' + url + '">click here</a> if this is not the case.</p></body></html>'; response.setHeader("Location", url); sendHtml(response, 303, html); } } var mimeParser = new mime.MimeParser(boundary, function (headers, buffer) { // parse part header starting with content-disposition if (headers['content-disposition'] === undefined) { setUploadErr("No 'content-disposition' header in mime part"); return; } // check that content-disposition is form-data if (headers['content-disposition'].type !== 'form-data') { setUploadErr("Content disposition of part is not 'form-data' but '" + headers['content-disposition'].type + "'"); return; } // check that we have the name attribute var inputName = headers['content-disposition'].parameters.name; if (inputName === undefined) { setUploadErr("No 'name' parameter in Content disposition"); return; } // test that we have a filename attribute var filename = headers['content-disposition'].parameters.filename; if (filename === undefined) { setUploadErr("No 'filename' parameter in Content disposition"); return; } // we bypass empty files if (filename === "") return; // remove path from file name in case filename contains / or \ filename = extractFilename(filename); // check if there is an explicit content-type in header var partCT = headers['content-type']; if (partCT === undefined) partCT = new mime.ContentType("text/plain"); // check that we are not using any transforming encoding var cte = headers['content-transfer-encoding']; if (cte !== undefined) { var type = cte.type.toLowerCase(); // test if type is not identity if (type !== "7bit" || type !== "8bit" || type !== "binary") { setUploadErr("Not supported 'content-transfer-encoding': " + cte.type); return; } } // find a free file name to write content to var extension = path.extname(filename); var base = path.basename(filename, extension); var testPath = path.join(rootDir, base + extension); var repeat = 0; function tryFunction(exists) { --pendingOperations; // exists is no more // pending; we don't // sendEnd before exit of // function try { if (exists) { console.log("File exists: " + testPath); ++repeat; if (repeat >= 500) { setUploadErr("Try " + repeat + " times to find a filename and failed"); return; } testPath = path.join(rootDir, base + '.' + repeat + extension); // recursion fs.exists(testPath, tryFunction) ++pendingOperations; } else { console.log("Writing: " + testPath); fs.writeFile(testPath, buffer, function (err) { --pendingOperations; try { if (err !== null) setUploadErr("Failed to save file to disk: " + err); else console.log("Uploaded: " + testPath); } finally { if (pendingOperations === 0) sendEnd(); } }); ++pendingOperations; } } finally { if (pendingOperations === 0) sendEnd(); } } fs.exists(testPath, tryFunction); ++pendingOperations; // the exists is pending }); request.on('data', function(chunck) { mimeParser.update(chunck); }); request.on('end', function() { --pendingOperations; if (pendingOperations === 0) sendEnd(); }); } function handleRoot(request, response) { fs.readdir(rootDir, function (err, files) { if (err != null) { sendErr(response, 500, 'Failed to list root directory: ' + err + '.'); return; } // compute the stat of files filesData = []; for (var fi = 0; fi < files.length; ++fi) { filesData.push({ name: files[fi], stat: null }); } var pendingComputations = filesData.length; if (pendingComputations >= 1) { for (var fd = 0; fd < filesData.length; ++fd) { (function (fileData) { var filePath = path.resolve(rootDir, fileData.name); fs.stat(filePath, function (err, stat) { try { if (err != null) { console.log("failed to stat:" + filePath); return; } fileData.stat = stat; } finally { --pendingComputations; if (pendingComputations == 0) { sendPage(); } } }); })(filesData[fd]); } } else // if there is no file to list, don't expect the last // completion to call sendPage sendPage(); function sendPage() { var respTxt = ""; if (files.length >= 1) { for (var fd = 0; fd < files.length; ++fd) { var fileData = filesData[fd]; respTxt += '<div class="file"><a href="content/' + encodeURIComponent(fileData.name) + '">' + fileData.name + '</a></div>'; respTxt += '<div class="fileinfo"><span class="date">' + (fileData.stat != null ? fileData.stat.mtime.toGMTString() : '---'); respTxt += '</span><span class="sep"></span>' + (fileData.stat != null ? filesize2string(fileData.stat.size).replace(' ','&nbsp;') : '---&nbsp;octets') + '</div>'; } } else { respTxt = '<div class="help"><span id="arrow"></span>No files have been uploaded yet, click on the "Upload" button above to start uploading files.</div>' } sendTemplateFile(response, 200, 'text/html; charset=UTF-8', '3ds-server-index.html', { files: respTxt }); } }); } function handleContent(request, response, filename) { // decode filename as a component or URI now so that if '/' is // encoded in URI we will spot it in next test filename = decodeURIComponent(filename); // fail if filename contains / or \ characters if (/\/|\\/.test(filename)) { sendErr(response, 404, "Invalid file name: " + filename + " it contains either / or \\."); return; } // find the file var filepath = path.resolve(rootDir, filename); // findout its mimetype fs.readFile(filepath, function (err, data) { if (err !== null) { sendErr(response, 404, "File name: " + filename + " does not exists."); return; } var mimetype = 'application/octet-stream'; if (data.length >= 2 && data[0] == 0xff && data[1] == 0xd8) mimetype = 'image/jpeg' else if (data.length >= 8 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47 && data[4] == 0x0d && data[5] == 0x0a && data[6] == 0x1a && data[7] == 0x0a) mimetype = 'image/png'; sendFile(response, 200, mimetype, filepath); }); } var dispatcher = { '/': handleRoot, '/upload.js': { ct: 'text/javascript', filename:'3ds-server-upload.js' }, '/favicon.ico': { ct: 'image/vnd.microsoft.icon', filename: 'favicon.ico' }, '/img/bgnd.png': { ct: 'image/png', filename: 'bgnd_pattern (indexed).png' }, '/img/title-shadow.png': { ct: 'image/png', filename: 'title-shadow.png' }, '/img/sprites.png': { ct: 'image/png', filename: 'sprites.png'}, '/main.css': { ct: 'text/css', filename: '3ds-main.css' }, '/err.css': { ct: 'text/css', filename: '3ds-err.css' }, }; var rootDir; // the directory where uploads should be stored var cmdLine; // the result of the parsing of the command line var scriptDir; // the directory that contains the javascript files function main() { // parse the command line cmdLine = parseCmdLine(); if (cmdLine.err !== undefined) { console.log("Error parsing the command line: " + cmdLine.err); return 1; } if (cmdLine.options.dir === undefined) { console.log('The -d/--dir option is mandatory'); return 1; } // set the root directory rootDir = cmdLine.options.dir; scriptDir = cmdLine.scriptDir console.log('Serving in directory: ' + rootDir); // run the server http.createServer(function(request, response) { var u = url.parse(request.url); var partiallyDecodedPath = decodeURI(u.pathname); if (request.method === 'GET') { if (dispatcher.hasOwnProperty(partiallyDecodedPath)) { var dispatch = dispatcher[partiallyDecodedPath]; if (typeof(dispatch) === 'function') dispatch(request, response); else sendFile(response, 200, dispatch.ct, dispatch.filename); } else if (/^\/content\//.test(partiallyDecodedPath)) { handleContent(request, response, partiallyDecodedPath.slice(9)); } else sendErr(response, 404, 'Page ' + request.url + ' not found on this server.'); } else if (request.method === 'POST') { if (partiallyDecodedPath === '/upload') { handleUpload(request, response); } else { sendErr(response, 404, 'Page ' + request.url + ' not found on this server.'); } } else { sendErr(response, 501, 'Method ' + request.method + ' is not implemented on this server.'); } }).listen(8080); }; main();
JavaScript
// Copyright 2013 Stephane SOPPERA // // This file is part of 3ds-image-uploader. // // 3ds-image-uploader is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // 3ds-image-uploader is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3ds-image-uploader. If not, see <http://www.gnu.org/licenses/>. var attrRE = /([^$]|^)\$\{([a-zA-Z_0-9]+)\}/g function apply(str, vals) { return str.replace(attrRE, function (full, firstChar, id) { if (vals.hasOwnProperty(id)) return firstChar + vals[id]; else return full; }); } exports.apply = apply;
JavaScript
/** * 3Dify 1.1 - 2014-04-20 * Copyright (c) 2010 Serafino Bilotta (serafinobilotta@hotmail.com - http://www.p2warticles.com) * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * More information on this project: * http://www.p2warticles.com/ * * Requires: jQuery v1.3+ * * Full Usage Documentation: http://www.p2warticles.com/2011/04/3dify-plugin/ * Usage: * $(el).threedify({ * posZ: value, tilt of element, default 0 * angle: value angle of perspective, default 15 * }); * */ (function ($) { $.fn.threedify = function (op) { var defaults = { posZ: 0, angle: 15 }; var options = $.extend(defaults, op); return this.each(function () { $(this).mousemove(function (e) { var posX = (0.50 - (e.layerX) / $(e.currentTarget).width()) * 2 * options.angle, posY = (-0.50 + (e.layerY) / $(e.currentTarget).height()) * 2 * options.angle; var cssObj = { '-o-transform': 'rotateX(' + posY + 'deg) rotateY(' + posX + 'deg) rotateZ(' + options.posZ + 'deg)', '-ms-transform': 'rotateX(' + posY + 'deg) rotateY(' + posX + 'deg) rotateZ(' + options.posZ + 'deg)', '-moz-transform': 'rotateX(' + posY + 'deg) rotateY(' + posX + 'deg) rotateZ(' + options.posZ + 'deg)', '-webkit-transform': 'rotateX(' + posY + 'deg) rotateY(' + posX + 'deg) rotateZ(' + options.posZ + 'deg)', 'transform': 'rotateX(' + posY + 'deg) rotateY(' + posX + 'deg) rotateZ(' + options.posZ + 'deg)' }; $(this).css(cssObj); }); }); }; })(jQuery);
JavaScript
BrowserHistoryUtils = { addEvent: function(elm, evType, fn, useCapture) { useCapture = useCapture || false; if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } } } BrowserHistory = (function() { // type of browser var browser = { ie: false, firefox: false, safari: false, opera: false, version: -1 }; // if setDefaultURL has been called, our first clue // that the SWF is ready and listening //var swfReady = false; // the URL we'll send to the SWF once it is ready //var pendingURL = ''; // Default app state URL to use when no fragment ID present var defaultHash = ''; // Last-known app state URL var currentHref = document.location.href; // Initial URL (used only by IE) var initialHref = document.location.href; // Initial URL (used only by IE) var initialHash = document.location.hash; // History frame source URL prefix (used only by IE) var historyFrameSourcePrefix = 'history/historyFrame.html?'; // History maintenance (used only by Safari) var currentHistoryLength = -1; var historyHash = []; var initialState = createState(initialHref, initialHref + '#' + initialHash, initialHash); var backStack = []; var forwardStack = []; var currentObjectId = null; //UserAgent detection var useragent = navigator.userAgent.toLowerCase(); if (useragent.indexOf("opera") != -1) { browser.opera = true; } else if (useragent.indexOf("msie") != -1) { browser.ie = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('msie') + 4)); } else if (useragent.indexOf("safari") != -1) { browser.safari = true; browser.version = parseFloat(useragent.substring(useragent.indexOf('safari') + 7)); } else if (useragent.indexOf("gecko") != -1) { browser.firefox = true; } if (browser.ie == true && browser.version == 7) { window["_ie_firstload"] = false; } // Accessor functions for obtaining specific elements of the page. function getHistoryFrame() { return document.getElementById('ie_historyFrame'); } function getAnchorElement() { return document.getElementById('firefox_anchorDiv'); } function getFormElement() { return document.getElementById('safari_formDiv'); } function getRememberElement() { return document.getElementById("safari_remember_field"); } /* Get the Flash player object for performing ExternalInterface callbacks. */ function getPlayer(objectId) { var objectId = objectId || null; var player = null; /* AJH, needed? = document.getElementById(getPlayerId()); */ if (browser.ie && objectId != null) { player = document.getElementById(objectId); } if (player == null) { player = document.getElementsByTagName('object')[0]; } if (player == null || player.object == null) { player = document.getElementsByTagName('embed')[0]; } return player; } function getPlayers() { var players = []; if (players.length == 0) { var tmp = document.getElementsByTagName('object'); players = tmp; } if (players.length == 0 || players[0].object == null) { var tmp = document.getElementsByTagName('embed'); players = tmp; } return players; } function getIframeHash() { var doc = getHistoryFrame().contentWindow.document; var hash = String(doc.location.search); if (hash.length == 1 && hash.charAt(0) == "?") { hash = ""; } else if (hash.length >= 2 && hash.charAt(0) == "?") { hash = hash.substring(1); } return hash; } /* Get the current location hash excluding the '#' symbol. */ function getHash() { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. var idx = document.location.href.indexOf('#'); return (idx >= 0) ? document.location.href.substr(idx+1) : ''; } /* Get the current location hash excluding the '#' symbol. */ function setHash(hash) { // It would be nice if we could use document.location.hash here, // but it's faulty sometimes. if (hash == '') hash = '#' document.location.hash = hash; } function createState(baseUrl, newUrl, flexAppUrl) { return { 'baseUrl': baseUrl, 'newUrl': newUrl, 'flexAppUrl': flexAppUrl, 'title': null }; } /* Add a history entry to the browser. * baseUrl: the portion of the location prior to the '#' * newUrl: the entire new URL, including '#' and following fragment * flexAppUrl: the portion of the location following the '#' only */ function addHistoryEntry(baseUrl, newUrl, flexAppUrl) { //delete all the history entries forwardStack = []; if (browser.ie) { //Check to see if we are being asked to do a navigate for the first //history entry, and if so ignore, because it's coming from the creation //of the history iframe if (flexAppUrl == defaultHash && document.location.href == initialHref && window['_ie_firstload']) { currentHref = initialHref; return; } if ((!flexAppUrl || flexAppUrl == defaultHash) && window['_ie_firstload']) { newUrl = baseUrl + '#' + defaultHash; flexAppUrl = defaultHash; } else { // for IE, tell the history frame to go somewhere without a '#' // in order to get this entry into the browser history. getHistoryFrame().src = historyFrameSourcePrefix + flexAppUrl; } setHash(flexAppUrl); } else { //ADR if (backStack.length == 0 && initialState.flexAppUrl == flexAppUrl) { initialState = createState(baseUrl, newUrl, flexAppUrl); } else if(backStack.length > 0 && backStack[backStack.length - 1].flexAppUrl == flexAppUrl) { backStack[backStack.length - 1] = createState(baseUrl, newUrl, flexAppUrl); } if (browser.safari) { // for Safari, submit a form whose action points to the desired URL if (browser.version <= 419.3) { var file = window.location.pathname.toString(); file = file.substring(file.lastIndexOf("/")+1); getFormElement().innerHTML = '<form name="historyForm" action="'+file+'#' + flexAppUrl + '" method="GET"></form>'; //get the current elements and add them to the form var qs = window.location.search.substring(1); var qs_arr = qs.split("&"); for (var i = 0; i < qs_arr.length; i++) { var tmp = qs_arr[i].split("="); var elem = document.createElement("input"); elem.type = "hidden"; elem.name = tmp[0]; elem.value = tmp[1]; document.forms.historyForm.appendChild(elem); } document.forms.historyForm.submit(); } else { top.location.hash = flexAppUrl; } // We also have to maintain the history by hand for Safari historyHash[history.length] = flexAppUrl; _storeStates(); } else { // Otherwise, write an anchor into the page and tell the browser to go there addAnchor(flexAppUrl); setHash(flexAppUrl); } } backStack.push(createState(baseUrl, newUrl, flexAppUrl)); } function _storeStates() { if (browser.safari) { getRememberElement().value = historyHash.join(","); } } function handleBackButton() { //The "current" page is always at the top of the history stack. var current = backStack.pop(); if (!current) { return; } var last = backStack[backStack.length - 1]; if (!last && backStack.length == 0){ last = initialState; } forwardStack.push(current); } function handleForwardButton() { //summary: private method. Do not call this directly. var last = forwardStack.pop(); if (!last) { return; } backStack.push(last); } function handleArbitraryUrl() { //delete all the history entries forwardStack = []; } /* Called periodically to poll to see if we need to detect navigation that has occurred */ function checkForUrlChange() { if (browser.ie) { if (currentHref != document.location.href && currentHref + '#' != document.location.href) { //This occurs when the user has navigated to a specific URL //within the app, and didn't use browser back/forward //IE seems to have a bug where it stops updating the URL it //shows the end-user at this point, but programatically it //appears to be correct. Do a full app reload to get around //this issue. if (browser.version < 7) { currentHref = document.location.href; document.location.reload(); } else { if (getHash() != getIframeHash()) { // this.iframe.src = this.blankURL + hash; var sourceToSet = historyFrameSourcePrefix + getHash(); getHistoryFrame().src = sourceToSet; } } } } if (browser.safari) { // For Safari, we have to check to see if history.length changed. if (currentHistoryLength >= 0 && history.length != currentHistoryLength) { //alert("did change: " + history.length + ", " + historyHash.length + "|" + historyHash[history.length] + "|>" + historyHash.join("|")); // If it did change, then we have to look the old state up // in our hand-maintained array since document.location.hash // won't have changed, then call back into BrowserManager. currentHistoryLength = history.length; var flexAppUrl = historyHash[currentHistoryLength]; if (flexAppUrl == '') { //flexAppUrl = defaultHash; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } _storeStates(); } } if (browser.firefox) { if (currentHref != document.location.href) { var bsl = backStack.length; var urlActions = { back: false, forward: false, set: false } if ((window.location.hash == initialHash || window.location.href == initialHref) && (bsl == 1)) { urlActions.back = true; // FIXME: could this ever be a forward button? // we can't clear it because we still need to check for forwards. Ugg. // clearInterval(this.locationTimer); handleBackButton(); } // first check to see if we could have gone forward. We always halt on // a no-hash item. if (forwardStack.length > 0) { if (forwardStack[forwardStack.length-1].flexAppUrl == getHash()) { urlActions.forward = true; handleForwardButton(); } } // ok, that didn't work, try someplace back in the history stack if ((bsl >= 2) && (backStack[bsl - 2])) { if (backStack[bsl - 2].flexAppUrl == getHash()) { urlActions.back = true; handleBackButton(); } } if (!urlActions.back && !urlActions.forward) { var foundInStacks = { back: -1, forward: -1 } for (var i = 0; i < backStack.length; i++) { if (backStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.back = i; } } for (var i = 0; i < forwardStack.length; i++) { if (forwardStack[i].flexAppUrl == getHash() && i != (bsl - 2)) { arbitraryUrl = true; foundInStacks.forward = i; } } handleArbitraryUrl(); } // Firefox changed; do a callback into BrowserManager to tell it. currentHref = document.location.href; var flexAppUrl = getHash(); if (flexAppUrl == '') { //flexAppUrl = defaultHash; } //ADR: to fix multiple if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { pl[i].browserURLChange(flexAppUrl); } } else { getPlayer().browserURLChange(flexAppUrl); } } } //setTimeout(checkForUrlChange, 50); } /* Write an anchor into the page to legitimize it as a URL for Firefox et al. */ function addAnchor(flexAppUrl) { if (document.getElementsByName(flexAppUrl).length == 0) { getAnchorElement().innerHTML += "<a name='" + flexAppUrl + "'>" + flexAppUrl + "</a>"; } } var _initialize = function () { if (browser.ie) { var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { var iframe_location = (new String(s.src)).replace("history.js", "historyFrame.html"); } } historyFrameSourcePrefix = iframe_location + "?"; var src = historyFrameSourcePrefix; var iframe = document.createElement("iframe"); iframe.id = 'ie_historyFrame'; iframe.name = 'ie_historyFrame'; //iframe.src = historyFrameSourcePrefix; try { document.body.appendChild(iframe); } catch(e) { setTimeout(function() { document.body.appendChild(iframe); }, 0); } } if (browser.safari) { var rememberDiv = document.createElement("div"); rememberDiv.id = 'safari_rememberDiv'; document.body.appendChild(rememberDiv); rememberDiv.innerHTML = '<input type="text" id="safari_remember_field" style="width: 500px;">'; var formDiv = document.createElement("div"); formDiv.id = 'safari_formDiv'; document.body.appendChild(formDiv); var reloader_content = document.createElement('div'); reloader_content.id = 'safarireloader'; var scripts = document.getElementsByTagName('script'); for (var i = 0, s; s = scripts[i]; i++) { if (s.src.indexOf("history.js") > -1) { html = (new String(s.src)).replace(".js", ".html"); } } reloader_content.innerHTML = '<iframe id="safarireloader-iframe" src="about:blank" frameborder="no" scrolling="no"></iframe>'; document.body.appendChild(reloader_content); reloader_content.style.position = 'absolute'; reloader_content.style.left = reloader_content.style.top = '-9999px'; iframe = reloader_content.getElementsByTagName('iframe')[0]; if (document.getElementById("safari_remember_field").value != "" ) { historyHash = document.getElementById("safari_remember_field").value.split(","); } } if (browser.firefox) { var anchorDiv = document.createElement("div"); anchorDiv.id = 'firefox_anchorDiv'; document.body.appendChild(anchorDiv); } //setTimeout(checkForUrlChange, 50); } return { historyHash: historyHash, backStack: function() { return backStack; }, forwardStack: function() { return forwardStack }, getPlayer: getPlayer, initialize: function(src) { _initialize(src); }, setURL: function(url) { document.location.href = url; }, getURL: function() { return document.location.href; }, getTitle: function() { return document.title; }, setTitle: function(title) { try { backStack[backStack.length - 1].title = title; } catch(e) { } //if on safari, set the title to be the empty string. if (browser.safari) { if (title == "") { try { var tmp = window.location.href.toString(); title = tmp.substring((tmp.lastIndexOf("/")+1), tmp.lastIndexOf("#")); } catch(e) { title = ""; } } } document.title = title; }, setDefaultURL: function(def) { defaultHash = def; def = getHash(); //trailing ? is important else an extra frame gets added to the history //when navigating back to the first page. Alternatively could check //in history frame navigation to compare # and ?. if (browser.ie) { window['_ie_firstload'] = true; var sourceToSet = historyFrameSourcePrefix + def; var func = function() { getHistoryFrame().src = sourceToSet; window.location.replace("#" + def); setInterval(checkForUrlChange, 50); } try { func(); } catch(e) { window.setTimeout(function() { func(); }, 0); } } if (browser.safari) { currentHistoryLength = history.length; if (historyHash.length == 0) { historyHash[currentHistoryLength] = def; var newloc = "#" + def; window.location.replace(newloc); } else { //alert(historyHash[historyHash.length-1]); } //setHash(def); setInterval(checkForUrlChange, 50); } if (browser.firefox || browser.opera) { var reg = new RegExp("#" + def + "$"); if (window.location.toString().match(reg)) { } else { var newloc ="#" + def; window.location.replace(newloc); } setInterval(checkForUrlChange, 50); //setHash(def); } }, /* Set the current browser URL; called from inside BrowserManager to propagate * the application state out to the container. */ setBrowserURL: function(flexAppUrl, objectId) { if (browser.ie && typeof objectId != "undefined") { currentObjectId = objectId; } //fromIframe = fromIframe || false; //fromFlex = fromFlex || false; //alert("setBrowserURL: " + flexAppUrl); //flexAppUrl = (flexAppUrl == "") ? defaultHash : flexAppUrl ; var pos = document.location.href.indexOf('#'); var baseUrl = pos != -1 ? document.location.href.substr(0, pos) : document.location.href; var newUrl = baseUrl + '#' + flexAppUrl; if (document.location.href != newUrl && document.location.href + '#' != newUrl) { currentHref = newUrl; addHistoryEntry(baseUrl, newUrl, flexAppUrl); currentHistoryLength = history.length; } return false; }, browserURLChange: function(flexAppUrl) { var objectId = null; if (browser.ie && currentObjectId != null) { objectId = currentObjectId; } pendingURL = ''; if (typeof BrowserHistory_multiple != "undefined" && BrowserHistory_multiple == true) { var pl = getPlayers(); for (var i = 0; i < pl.length; i++) { try { pl[i].browserURLChange(flexAppUrl); } catch(e) { } } } else { try { getPlayer(objectId).browserURLChange(flexAppUrl); } catch(e) { } } currentObjectId = null; } } })(); // Initialization // Automated unit testing and other diagnostics function setURL(url) { document.location.href = url; } function backButton() { history.back(); } function forwardButton() { history.forward(); } function goForwardOrBackInHistory(step) { history.go(step); } //BrowserHistoryUtils.addEvent(window, "load", function() { BrowserHistory.initialize(); }); (function(i) { var u =navigator.userAgent;var e=/*@cc_on!@*/false; var st = setTimeout; if(/webkit/i.test(u)){ st(function(){ var dr=document.readyState; if(dr=="loaded"||dr=="complete"){i()} else{st(arguments.callee,10);}},10); } else if((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))){ document.addEventListener("DOMContentLoaded",i,false); } else if(e){ (function(){ var t=document.createElement('doc:rdy'); try{t.doScroll('left'); i();t=null; }catch(e){st(arguments.callee,0);}})(); } else{ window.onload=i; } })( function() {BrowserHistory.initialize();} );
JavaScript
// Flash Player Version Detection - Rev 1.6 // Detect Client Browser type // Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved. var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var version; var axo; var e; // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } return version; } // JavaScript helper required to detect Flash Player PlugIn version information function GetSwfVer(){ // NS/Opera version >= 3 check for Flash plugin in plugin array var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; else if ( isIE && isWin && !isOpera ) { flashVer = ControlVersion(); } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { versionStr = GetSwfVer(); if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { // Given "WIN 2,0,0,11" tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"] tempString = tempArray[1]; // "2,0,0,11" versionArray = tempString.split(","); // ['2', '0', '0', '11'] } else { versionArray = versionStr.split("."); } var versionMajor = versionArray[0]; var versionMinor = versionArray[1]; var versionRevision = versionArray[2]; // is the major.revision >= requested major.revision AND the minor version >= requested minor if (versionMajor > parseFloat(reqMajorVer)) { return true; } else if (versionMajor == parseFloat(reqMajorVer)) { if (versionMinor > parseFloat(reqMinorVer)) return true; else if (versionMinor == parseFloat(reqMinorVer)) { if (versionRevision >= parseFloat(reqRevision)) return true; } } return false; } } function AC_AddExtension(src, ext) { if (src.indexOf('?') != -1) return src.replace(/\?/, ext+'?'); else return src + ext; } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = ''; if (isIE && isWin && !isOpera) { str += '<object '; for (var i in objAttrs) str += i + '="' + objAttrs[i] + '" '; str += '>'; for (var i in params) str += '<param name="' + i + '" value="' + params[i] + '" /> '; str += '</object>'; } else { str += '<embed '; for (var i in embedAttrs) str += i + '="' + embedAttrs[i] + '" '; str += '> </embed>'; } document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": ret.objAttrs[args[i]] = args[i+1]; break; case "id": case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; }
JavaScript
/** * JavaScript routines for Krumo * * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function krumo() { } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Add a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.reclass = function(el, className) { if (el.className.indexOf(className) < 0) { el.className += (' ' + className); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Remove a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.unclass = function(el, className) { if (el.className.indexOf(className) > -1) { el.className = el.className.replace(className, ''); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Toggle the nodes connected to an HTML element * * @param HtmlElement el * @return void */ krumo.toggle = function(el) { var ul = el.parentNode.getElementsByTagName('ul'); for (var i=0; i<ul.length; i++) { if (ul[i].parentNode.parentNode == el.parentNode) { ul[i].parentNode.style.display = (ul[i].parentNode.style.display == 'none') ? 'block' : 'none'; } } // toggle class // if (ul[0].parentNode.style.display == 'block') { krumo.reclass(el, 'krumo-opened'); } else { krumo.unclass(el, 'krumo-opened'); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover over an HTML element * * @param HtmlElement el * @return void */ krumo.over = function(el) { krumo.reclass(el, 'krumo-hover'); } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover out an HTML element * * @param HtmlElement el * @return void */ krumo.out = function(el) { krumo.unclass(el, 'krumo-hover'); } /////////////////////////////////////////////////////////////////////////////
JavaScript
/*----------------------------------------\ | Cross Browser Tree Widget 1.1 | |-----------------------------------------| | Created by Emil A. Eklund (eae@eae.net) | | For WebFX (http://webfx.eae.net/) | |-----------------------------------------| | This script is provided as is without | | any warranty whatsoever. It may be used | | free of charge for non commerical sites | | For commerical use contact the author | | of this script for further details. | |-----------------------------------------| | Created 2000-12-11 | Updated 2001-09-06 | \----------------------------------------*/ var webFXTreeConfig = { rootIcon : 'media/images/empty.png', openRootIcon : 'media/images/empty.png', folderIcon : 'media/images/empty.png', openFolderIcon : 'media/images/empty.png', fileIcon : 'media/images/empty.png', iIcon : 'media/images/I.png', lIcon : 'media/images/L.png', lMinusIcon : 'media/images/Lminus.png', lPlusIcon : 'media/images/Lplus.png', tIcon : 'media/images/T.png', tMinusIcon : 'media/images/Tminus.png', tPlusIcon : 'media/images/Tplus.png', blankIcon : 'media/images/blank.png', defaultText : 'Tree Item', defaultAction : 'javascript:void(0);', defaultTarget : 'right', defaultBehavior : 'classic' }; var webFXTreeHandler = { idCounter : 0, idPrefix : "webfx-tree-object-", all : {}, behavior : null, selected : null, getId : function() { return this.idPrefix + this.idCounter++; }, toggle : function (oItem) { this.all[oItem.id.replace('-plus','')].toggle(); }, select : function (oItem) { this.all[oItem.id.replace('-icon','')].select(); }, focus : function (oItem) { this.all[oItem.id.replace('-anchor','')].focus(); }, blur : function (oItem) { this.all[oItem.id.replace('-anchor','')].blur(); }, keydown : function (oItem) { return this.all[oItem.id].keydown(window.event.keyCode); }, cookies : new WebFXCookie() }; /* * WebFXCookie class */ function WebFXCookie() { if (document.cookie.length) { this.cookies = ' ' + document.cookie; } } WebFXCookie.prototype.setCookie = function (key, value) { document.cookie = key + "=" + escape(value); } WebFXCookie.prototype.getCookie = function (key) { if (this.cookies) { var start = this.cookies.indexOf(' ' + key + '='); if (start == -1) { return null; } var end = this.cookies.indexOf(";", start); if (end == -1) { end = this.cookies.length; } end -= start; var cookie = this.cookies.substr(start,end); return unescape(cookie.substr(cookie.indexOf('=') + 1, cookie.length - cookie.indexOf('=') + 1)); } else { return null; } } /* * WebFXTreeAbstractNode class */ function WebFXTreeAbstractNode(sText, sAction, sTarget) { this.childNodes = []; this.id = webFXTreeHandler.getId(); this.text = sText || webFXTreeConfig.defaultText; this.action = sAction || webFXTreeConfig.defaultAction; this.targetWindow = sTarget || webFXTreeConfig.defaultTarget; this._last = false; webFXTreeHandler.all[this.id] = this; } WebFXTreeAbstractNode.prototype.add = function (node) { node.parentNode = this; this.childNodes[this.childNodes.length] = node; var root = this; if (this.childNodes.length >=2) { this.childNodes[this.childNodes.length -2]._last = false; } while (root.parentNode) { root = root.parentNode; } if (root.rendered) { if (this.childNodes.length >= 2) { document.getElementById(this.childNodes[this.childNodes.length -2].id + '-plus').src = ((this.childNodes[this.childNodes.length -2].folder)?webFXTreeConfig.tMinusIcon:webFXTreeConfig.tIcon); if (this.childNodes[this.childNodes.length -2].folder) { this.childNodes[this.childNodes.length -2].plusIcon = webFXTreeConfig.tPlusIcon; this.childNodes[this.childNodes.length -2].minusIcon = webFXTreeConfig.tMinusIcon; } this.childNodes[this.childNodes.length -2]._last = false; } this._last = true; var foo = this; while (foo.parentNode) { for (var i = 0; i < foo.parentNode.childNodes.length; i++) { if (foo.id == foo.parentNode.childNodes[i].id) { break; } } if (++i == foo.parentNode.childNodes.length) { foo.parentNode._last = true; } else { foo.parentNode._last = false; } foo = foo.parentNode; } document.getElementById(this.id + '-cont').insertAdjacentHTML("beforeEnd", node.toString()); if ((!this.folder) && (!this.openIcon)) { this.icon = webFXTreeConfig.folderIcon; this.openIcon = webFXTreeConfig.openFolderIcon; } this.folder = true; this.indent(); this.expand(); } return node; } WebFXTreeAbstractNode.prototype.toggle = function() { if (this.folder) { if (this.open) { this.collapse(); } else { this.expand(); } } } WebFXTreeAbstractNode.prototype.select = function() { document.getElementById(this.id + '-anchor').focus(); } WebFXTreeAbstractNode.prototype.focus = function() { webFXTreeHandler.selected = this; if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.openIcon; } document.getElementById(this.id + '-anchor').style.backgroundColor = 'highlight'; document.getElementById(this.id + '-anchor').style.color = 'highlighttext'; document.getElementById(this.id + '-anchor').focus(); } WebFXTreeAbstractNode.prototype.blur = function() { if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.icon; } document.getElementById(this.id + '-anchor').style.backgroundColor = 'transparent'; document.getElementById(this.id + '-anchor').style.color = 'menutext'; } WebFXTreeAbstractNode.prototype.doExpand = function() { if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.openIcon; } if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'block'; } this.open = true; webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '1'); } WebFXTreeAbstractNode.prototype.doCollapse = function() { if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.icon; } if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'none'; } this.open = false; webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '0'); } WebFXTreeAbstractNode.prototype.expandAll = function() { this.expandChildren(); if ((this.folder) && (!this.open)) { this.expand(); } } WebFXTreeAbstractNode.prototype.expandChildren = function() { for (var i = 0; i < this.childNodes.length; i++) { this.childNodes[i].expandAll(); } } WebFXTreeAbstractNode.prototype.collapseAll = function() { if ((this.folder) && (this.open)) { this.collapse(); } this.collapseChildren(); } WebFXTreeAbstractNode.prototype.collapseChildren = function() { for (var i = 0; i < this.childNodes.length; i++) { this.childNodes[i].collapseAll(); } } WebFXTreeAbstractNode.prototype.indent = function(lvl, del, last, level) { /* * Since we only want to modify items one level below ourself, * and since the rightmost indentation position is occupied by * the plus icon we set this to -2 */ if (lvl == null) { lvl = -2; } var state = 0; for (var i = this.childNodes.length - 1; i >= 0 ; i--) { state = this.childNodes[i].indent(lvl + 1, del, last, level); if (state) { return; } } if (del) { if (level >= this._level) { if (this.folder) { document.getElementById(this.id + '-plus').src = (this.open)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.lPlusIcon; this.plusIcon = webFXTreeConfig.lPlusIcon; this.minusIcon = webFXTreeConfig.lMinusIcon; } else { document.getElementById(this.id + '-plus').src = webFXTreeConfig.lIcon; } return 1; } } var foo = document.getElementById(this.id + '-indent-' + lvl); if (foo) { if ((del) && (last)) { foo._last = true; } if (foo._last) { foo.src = webFXTreeConfig.blankIcon; } else { foo.src = webFXTreeConfig.iIcon; } } return 0; } /* * WebFXTree class */ function WebFXTree(sText, sAction, sBehavior, sIcon, sOpenIcon) { this.base = WebFXTreeAbstractNode; this.base(sText, sAction); this.icon = sIcon || webFXTreeConfig.rootIcon; this.openIcon = sOpenIcon || webFXTreeConfig.openRootIcon; /* Defaults to open */ this.open = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '0')?false:true; this.folder = true; this.rendered = false; if (!webFXTreeHandler.behavior) { webFXTreeHandler.behavior = sBehavior || webFXTreeConfig.defaultBehavior; } this.targetWindow = 'right'; } WebFXTree.prototype = new WebFXTreeAbstractNode; WebFXTree.prototype.setBehavior = function (sBehavior) { webFXTreeHandler.behavior = sBehavior; }; WebFXTree.prototype.getBehavior = function (sBehavior) { return webFXTreeHandler.behavior; }; WebFXTree.prototype.getSelected = function() { if (webFXTreeHandler.selected) { return webFXTreeHandler.selected; } else { return null; } } WebFXTree.prototype.remove = function() { } WebFXTree.prototype.expand = function() { this.doExpand(); } WebFXTree.prototype.collapse = function() { this.focus(); this.doCollapse(); } WebFXTree.prototype.getFirst = function() { return null; } WebFXTree.prototype.getLast = function() { return null; } WebFXTree.prototype.getNextSibling = function() { return null; } WebFXTree.prototype.getPreviousSibling = function() { return null; } WebFXTree.prototype.keydown = function(key) { if (key == 39) { this.expand(); return false; } if (key == 37) { this.collapse(); return false; } if ((key == 40) && (this.open)) { this.childNodes[0].select(); return false; } return true; } WebFXTree.prototype.toString = function() { var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this)\">"; str += "<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" target=\"" + this.targetWindow + "\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + this.text + "</a></div>"; str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">"; for (var i = 0; i < this.childNodes.length; i++) { str += this.childNodes[i].toString(i, this.childNodes.length); } str += "</div>"; this.rendered = true; return str; }; /* * WebFXTreeItem class */ function WebFXTreeItem(sText, sAction, eParent, sIcon, sOpenIcon) { this.base = WebFXTreeAbstractNode; this.base(sText, sAction); /* Defaults to close */ this.open = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '1')?true:false; if (eParent) { eParent.add(this); } if (sIcon) { this.icon = sIcon; } if (sOpenIcon) { this.openIcon = sOpenIcon; } } WebFXTreeItem.prototype = new WebFXTreeAbstractNode; WebFXTreeItem.prototype.remove = function() { var parentNode = this.parentNode; var prevSibling = this.getPreviousSibling(true); var nextSibling = this.getNextSibling(true); var folder = this.parentNode.folder; var last = ((nextSibling) && (nextSibling.parentNode) && (nextSibling.parentNode.id == parentNode.id))?false:true; this.getPreviousSibling().focus(); this._remove(); if (parentNode.childNodes.length == 0) { parentNode.folder = false; parentNode.open = false; } if (last) { if (parentNode.id == prevSibling.id) { document.getElementById(parentNode.id + '-icon').src = webFXTreeConfig.fileIcon; } else { } } if ((!prevSibling.parentNode) || (prevSibling.parentNode != parentNode)) { parentNode.indent(null, true, last, this._level); } if (document.getElementById(prevSibling.id + '-plus')) { if (nextSibling) { if ((parentNode == prevSibling) && (parentNode.getNextSibling)) { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.tIcon; } else if (nextSibling.parentNode != prevSibling) { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.lIcon; } } else { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.lIcon; } } } WebFXTreeItem.prototype._remove = function() { for (var i = this.childNodes.length - 1; i >= 0; i--) { this.childNodes[i]._remove(); } for (var i = 0; i < this.parentNode.childNodes.length; i++) { if (this.id == this.parentNode.childNodes[i].id) { for (var j = i; j < this.parentNode.childNodes.length; j++) { this.parentNode.childNodes[i] = this.parentNode.childNodes[i+1] } this.parentNode.childNodes.length = this.parentNode.childNodes.length - 1; if (i + 1 == this.parentNode.childNodes.length) { this.parentNode._last = true; } } } webFXTreeHandler.all[this.id] = null; if (document.getElementById(this.id)) { document.getElementById(this.id).innerHTML = ""; document.getElementById(this.id).removeNode(); } } WebFXTreeItem.prototype.expand = function() { this.doExpand(); document.getElementById(this.id + '-plus').src = this.minusIcon; } WebFXTreeItem.prototype.collapse = function() { this.focus(); this.doCollapse(); document.getElementById(this.id + '-plus').src = this.plusIcon; } WebFXTreeItem.prototype.getFirst = function() { return this.childNodes[0]; } WebFXTreeItem.prototype.getLast = function() { if (this.childNodes[this.childNodes.length - 1].open) { return this.childNodes[this.childNodes.length - 1].getLast(); } else { return this.childNodes[this.childNodes.length - 1]; } } WebFXTreeItem.prototype.getNextSibling = function() { for (var i = 0; i < this.parentNode.childNodes.length; i++) { if (this == this.parentNode.childNodes[i]) { break; } } if (++i == this.parentNode.childNodes.length) { return this.parentNode.getNextSibling(); } else { return this.parentNode.childNodes[i]; } } WebFXTreeItem.prototype.getPreviousSibling = function(b) { for (var i = 0; i < this.parentNode.childNodes.length; i++) { if (this == this.parentNode.childNodes[i]) { break; } } if (i == 0) { return this.parentNode; } else { if ((this.parentNode.childNodes[--i].open) || (b && this.parentNode.childNodes[i].folder)) { return this.parentNode.childNodes[i].getLast(); } else { return this.parentNode.childNodes[i]; } } } WebFXTreeItem.prototype.keydown = function(key) { if ((key == 39) && (this.folder)) { if (!this.open) { this.expand(); return false; } else { this.getFirst().select(); return false; } } else if (key == 37) { if (this.open) { this.collapse(); return false; } else { this.parentNode.select(); return false; } } else if (key == 40) { if (this.open) { this.getFirst().select(); return false; } else { var sib = this.getNextSibling(); if (sib) { sib.select(); return false; } } } else if (key == 38) { this.getPreviousSibling().select(); return false; } return true; } WebFXTreeItem.prototype.toString = function (nItem, nItemCount) { var foo = this.parentNode; var indent = ''; if (nItem + 1 == nItemCount) { this.parentNode._last = true; } var i = 0; while (foo.parentNode) { foo = foo.parentNode; indent = "<img id=\"" + this.id + "-indent-" + i + "\" src=\"" + ((foo._last)?webFXTreeConfig.blankIcon:webFXTreeConfig.iIcon) + "\">" + indent; i++; } this._level = i; if (this.childNodes.length) { this.folder = 1; } else { this.open = false; } if ((this.folder) || (webFXTreeHandler.behavior != 'classic')) { if (!this.icon) { this.icon = webFXTreeConfig.folderIcon; } if (!this.openIcon) { this.openIcon = webFXTreeConfig.openFolderIcon; } } else if (!this.icon) { this.icon = webFXTreeConfig.fileIcon; } var label = this.text; label = label.replace('<', '<'); label = label.replace('>', '>'); var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this)\">"; str += indent; str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)):((this.parentNode._last)?webFXTreeConfig.lIcon:webFXTreeConfig.tIcon)) + "\" onclick=\"webFXTreeHandler.toggle(this);\">" str += "<img id=\"" + this.id + "-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" target=\"" + this.targetWindow + "\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></div>"; str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">"; for (var i = 0; i < this.childNodes.length; i++) { str += this.childNodes[i].toString(i,this.childNodes.length); } str += "</div>"; this.plusIcon = ((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon); this.minusIcon = ((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon); return str; }
JavaScript
Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } Array.prototype.each = function (handler, args) { for (var i = 0; i < this.length; i++) { handler.call(this[i], i, this[i], args); } return this; }; function isArray(obj) { if(obj){ return obj.constructor == Array; } else return false; } var TC = { readyList: Array(), elementList: Array(), waitList: Array(), lang: {}, vars: Array(), overlay: function (original, additional) { for(var key in additional) { original[key] = additional[key]; } return original; }, get_content: function(options){ TC.loader(); delete TC.elementList[options.id]; var data = { asynch : "true", mod: options.module, action: "get_content", element: options.element, }; if(options.options) TC.overlay(data, options.options); if(options.after_action) data = TC.overlay(data, {after_action : options.after_action}); $.post(TC.base_url + "index.php", data, function(data){ TC.loader.stop(); TC.elementList[options.id] = $.parseJSON(data); var execute = true; if(TC.readyList[options.id]){ if(TC.readyList[options.id]['wait']){ TC.readyList[options.id]['wait'].each(function(index, item){ if(!TC.elementList[item]) execute = false; }) } if(execute) TC.callElement(options.id); } }); }, callElement: function(element){ if(TC.readyList[element]['fn'])TC.readyList[element]['fn'](); if(isArray(TC.waitList[element])){ TC.waitList[element].each(function(index, item){ if(TC.readyList[item]['fn'])TC.readyList[item]['fn'](); }); } }, ready: function(element, fn, wait){ TC.readyList[element] = Array(); TC.readyList[element]['fn'] = fn; if(wait) { TC.readyList[element]['wait'] = wait; wait.each(function(index, item){ if(!TC.readyList[this]){ if(!isArray(TC.waitList[this])) TC.waitList[this] = Array(); TC.waitList[this].push(element); } }); } }, loadBlocks: function (blocks){ for(var key in blocks){ TC.get_content(blocks[key]); } }, json: function(options, fn){ TC.loader(); var data = {asynch : "true"}; var data = TC.overlay(data, options); $.getJSON(TC.base_url + "index.php", data, function(json){ //TC.loader.stop(); fn(json); TC.loader.stop(); }); }, info: { wait: Array(), list: Array(), set: function(options){ TC.info.target = options.target; TC.info.onReady = options.callback; TC.info.options.each(function(index, element){ TC.info.wait[index] = element; TC.info.wait[element] = index; TC.json({mod: element, action: "get_info"}, function(json){ if(isArray(json.info)) json.info.each(function(index, element){ TC.info.list.push(element); }); TC.info.wait.each(function(index, element, source){ if(TC.info.wait[index] == json.source){ TC.info.wait.splice(index,1); }; },json.source); if(TC.info.wait.length == 0){ TC.info.onReady() }; }); }); }, }, modal_init: function (content, fn){ $("#modal").remove(); TC.get_content({ id: "modal", module: "admin", element: "modal",} ); TC.ready("modal", function(){ $("body").append(TC.elementList['modal'].content); $("#modal .pad").append(content); fn(); $("#modal").click(function(e){ if(e.target.className == "close" || e.target.id == "modal" || e.target.className == "center"){ $("#modal").remove(); }; }); $("#modal > .center").css({ left: ($("#modal").width()-$("#modal > .center").width())/2, top: window.pageYOffset}); $("#modal > .center > .wrapper > .pad").show(0, function(){ }); }); }, loader: function(){ if($("#loader")[0]) return true; var drowFrame = function(){ ctx.clearRect(0, 0, 50, 50); for(i = 0; i < linesNum; i++){ x1 = cX+radius*Math.cos(i*archStep); y1 = cY+radius*Math.sin(i*archStep); x2 = cX+(radius-lLength)*Math.cos(i*archStep); y2 = cY+(radius-lLength)*Math.sin(i*archStep); arch = (i*archStep+archFrameStep*frame)/Math.PI/2; ctx.strokeStyle = "rgba(255,255,255," + (1-arch+Math.floor(arch)) + ")"; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.closePath(); ctx.stroke(); } } var iterateFrame = function(){ drowFrame(); frame++; } TC.loader.stop = function(){ $("#loader").remove(); } var x1, y1, x2, y2; var linesNum = 15; var cX = 25; var cY = 25; var size = 50; var cD = 15; var lWidth = 2; var lLength = 15; var archStep = Math.PI/linesNum*2; var radius = 25; var fpc = 24; var archFrameStep = Math.PI/fpc*2; var frame = 0; var spc = 500; $("body").prepend("<canvas id='loader' width=50 height=50></canvas>"); var ctx = document.getElementById("loader").getContext("2d"); setInterval(function(){ iterateFrame() }, spc/fpc ); } }
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) + '&ndash;' + 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('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, 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('&amp;') + '" />' + '<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 + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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
/*! * 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('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, 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('&amp;') + '" />' + '<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 + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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) + '&ndash;' + 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
/*! * 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) + '&ndash;' + 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('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, 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('&amp;') + '" />' + '<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 + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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
/*! * 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('&amp;').split('<').join('&lt;').split('"').join('&quot;'); }, 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('&amp;') + '" />' + '<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 + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;loop=0" />' + '<embed src="//vimeo.com/moogaloop.swf?api=1&amp;clip_id=' + pluginMediaElement.vimeoid + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1&amp;autoplay=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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&amp;playerapiid=' + settings.pluginId + '&amp;version=3&amp;autoplay=0&amp;controls=0&amp;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) + '&ndash;' + 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
/* Tokenizer for JavaScript code */ var tokenizeJavaScript = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "js-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, intended to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "js-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "js-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "js-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gimy]/); // 'y' is "sticky" option in Mozilla return {type: "regexp", style: "js-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "js-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "js-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "js-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "js-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
JavaScript
var SparqlParser = Editor.Parser = (function() { function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", "isblank", "isliteral", "union", "a"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc"]); var operatorChars = /[*+\-<>=&|]/; var tokenizeSparql = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "$" || ch == "?") { source.nextWhileMatches(/[\w\d]/); return "sp-var"; } else if (ch == "<" && !source.matches(/[\s\u00a0=]/)) { source.nextWhileMatches(/[^\s\u00a0>]/); if (source.equals(">")) source.next(); return "sp-uri"; } else if (ch == "\"" || ch == "'") { setState(inLiteral(ch)); return null; } else if (/[{}\(\),\.;\[\]]/.test(ch)) { return "sp-punc"; } else if (ch == "#") { while (!source.endOfLine()) source.next(); return "sp-comment"; } else if (operatorChars.test(ch)) { source.nextWhileMatches(operatorChars); return "sp-operator"; } else if (ch == ":") { source.nextWhileMatches(/[\w\d\._\-]/); return "sp-prefixed"; } else { source.nextWhileMatches(/[_\w\d]/); if (source.equals(":")) { source.next(); source.nextWhileMatches(/[\w\d_\-]/); return "sp-prefixed"; } var word = source.get(), type; if (ops.test(word)) type = "sp-operator"; else if (keywords.test(word)) type = "sp-keyword"; else type = "sp-word"; return {style: type, content: word}; } } function inLiteral(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) { setState(normal); break; } escaped = !escaped && ch == "\\"; } return "sp-literal"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentSparql(context) { return function(nextChars) { var firstChar = nextChars && nextChars.charAt(0); if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == matching[context.type]; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col - (closing ? context.width : 0); else return context.indent + (closing ? 0 : indentUnit); } } function parseSparql(source) { var tokens = tokenizeSparql(source); var context = null, indent = 0, col = 0; function pushContext(type, width) { context = {prev: context, indent: indent, col: col, type: type, width: width}; } function popContext() { context = context.prev; } var iter = { next: function() { var token = tokens.next(), type = token.style, content = token.content, width = token.value.length; if (content == "\n") { token.indentation = indentSparql(context); indent = col = 0; if (context && context.align == null) context.align = false; } else if (type == "whitespace" && col == 0) { indent = width; } else if (type != "sp-comment" && context && context.align == null) { context.align = true; } if (content != "\n") col += width; if (/[\[\{\(]/.test(content)) { pushContext(content, width); } else if (/[\]\}\)]/.test(content)) { while (context && context.type == "pattern") popContext(); if (context && content == matching[context.type]) popContext(); } else if (content == "." && context && context.type == "pattern") { popContext(); } else if ((type == "sp-word" || type == "sp-prefixed" || type == "sp-uri" || type == "sp-var" || type == "sp-literal") && context && /[\{\[]/.test(context.type)) { pushContext("pattern", width); } return token; }, copy: function() { var _context = context, _indent = indent, _col = col, _tokenState = tokens.state; return function(source) { tokens = tokenizeSparql(source, _tokenState); context = _context; indent = _indent; col = _col; return iter; }; } }; return iter; } return {make: parseSparql, electricChars: "}]"}; })();
JavaScript
// Minimal framing needed to use CodeMirror-style parsers to highlight // code. Load this along with tokenize.js, stringstream.js, and your // parser. Then call highlightText, passing a string as the first // argument, and as the second argument either a callback function // that will be called with an array of SPAN nodes for every line in // the code, or a DOM node to which to append these spans, and // optionally (not needed if you only loaded one parser) a parser // object. // Stuff from util.js that the parsers are using. var StopIteration = {toString: function() {return "StopIteration"}}; var Editor = {}; var indentUnit = 2; (function(){ function normaliseString(string) { var tab = ""; for (var i = 0; i < indentUnit; i++) tab += " "; string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n"); var pos = 0, parts = [], lines = string.split("\n"); for (var line = 0; line < lines.length; line++) { if (line != 0) parts.push("\n"); parts.push(lines[line]); } return { next: function() { if (pos < parts.length) return parts[pos++]; else throw StopIteration; } }; } window.highlightText = function(string, callback, parser) { parser = (parser || Editor.Parser).make(stringStream(normaliseString(string))); var line = []; if (callback.nodeType == 1) { var node = callback; callback = function(line) { for (var i = 0; i < line.length; i++) node.appendChild(line[i]); node.appendChild(document.createElement("br")); }; } try { while (true) { var token = parser.next(); if (token.value == "\n") { callback(line); line = []; } else { var span = document.createElement("span"); span.className = token.style; span.appendChild(document.createTextNode(token.value)); line.push(span); } } } catch (e) { if (e != StopIteration) throw e; } if (line.length) callback(line); } })();
JavaScript
/* This file defines an XML parser, with a few kludges to make it * useable for HTML. autoSelfClosers defines a set of tag names that * are expected to not have a closing tag, and doNotIndent specifies * the tags inside of which no indentation should happen (see Config * object). These can be disabled by passing the editor an object like * {useHTMLKludges: false} as parserConfig option. */ var XMLParser = Editor.Parser = (function() { var Kludges = { autoSelfClosers: {"br": true, "img": true, "hr": true, "link": true, "input": true, "meta": true, "col": true, "frame": true, "base": true, "area": true}, doNotIndent: {"pre": true, "!cdata": true} }; var NoKludges = {autoSelfClosers: {}, doNotIndent: {"!cdata": true}}; var UseKludges = Kludges; var alignCDATA = false; // Simple stateful tokenizer for XML documents. Returns a // MochiKit-style iterator, with a state property that contains a // function encapsulating the current state. See tokenize.js. var tokenizeXML = (function() { function inText(source, setState) { var ch = source.next(); if (ch == "<") { if (source.equals("!")) { source.next(); if (source.equals("[")) { if (source.lookAhead("[CDATA[", true)) { setState(inBlock("xml-cdata", "]]>")); return null; } else { return "xml-text"; } } else if (source.lookAhead("--", true)) { setState(inBlock("xml-comment", "-->")); return null; } else if (source.lookAhead("DOCTYPE", true)) { source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-doctype", ">")); return "xml-doctype"; } else { return "xml-text"; } } else if (source.equals("?")) { source.next(); source.nextWhileMatches(/[\w\._\-]/); setState(inBlock("xml-processing", "?>")); return "xml-processing"; } else { if (source.equals("/")) source.next(); setState(inTag); return "xml-punctuation"; } } else if (ch == "&") { while (!source.endOfLine()) { if (source.next() == ";") break; } return "xml-entity"; } else { source.nextWhileMatches(/[^&<\n]/); return "xml-text"; } } function inTag(source, setState) { var ch = source.next(); if (ch == ">") { setState(inText); return "xml-punctuation"; } else if (/[?\/]/.test(ch) && source.equals(">")) { source.next(); setState(inText); return "xml-punctuation"; } else if (ch == "=") { return "xml-punctuation"; } else if (/[\'\"]/.test(ch)) { setState(inAttribute(ch)); return null; } else { source.nextWhileMatches(/[^\s\u00a0=<>\"\'\/?]/); return "xml-name"; } } function inAttribute(quote) { return function(source, setState) { while (!source.endOfLine()) { if (source.next() == quote) { setState(inTag); break; } } return "xml-attribute"; }; } function inBlock(style, terminator) { return function(source, setState) { while (!source.endOfLine()) { if (source.lookAhead(terminator, true)) { setState(inText); break; } source.next(); } return style; }; } return function(source, startState) { return tokenizer(source, startState || inText); }; })(); // The parser. The structure of this function largely follows that of // parseJavaScript in parsejavascript.js (there is actually a bit more // shared code than I'd like), but it is quite a bit simpler. function parseXML(source) { var tokens = tokenizeXML(source), token; var cc = [base]; var tokenNr = 0, indented = 0; var currentTag = null, context = null; var consume; function push(fs) { for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } function cont() { push(arguments); consume = true; } function pass() { push(arguments); consume = false; } function markErr() { token.style += " xml-error"; } function expect(text) { return function(style, content) { if (content == text) cont(); else {markErr(); cont(arguments.callee);} }; } function pushContext(tagname, startOfLine) { var noIndent = UseKludges.doNotIndent.hasOwnProperty(tagname) || (context && context.noIndent); context = {prev: context, name: tagname, indent: indented, startOfLine: startOfLine, noIndent: noIndent}; } function popContext() { context = context.prev; } function computeIndentation(baseContext) { return function(nextChars, current) { var context = baseContext; if (context && context.noIndent) return current; if (alignCDATA && /<!\[CDATA\[/.test(nextChars)) return 0; if (context && /^<\//.test(nextChars)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }; } function base() { return pass(element, base); } var harmlessTokens = {"xml-text": true, "xml-entity": true, "xml-comment": true, "xml-processing": true, "xml-doctype": true}; function element(style, content) { if (content == "<") cont(tagname, attributes, endtag(tokenNr == 1)); else if (content == "</") cont(closetagname, expect(">")); else if (style == "xml-cdata") { if (!context || context.name != "!cdata") pushContext("!cdata"); if (/\]\]>$/.test(content)) popContext(); cont(); } else if (harmlessTokens.hasOwnProperty(style)) cont(); else {markErr(); cont();} } function tagname(style, content) { if (style == "xml-name") { currentTag = content.toLowerCase(); token.style = "xml-tagname"; cont(); } else { currentTag = null; pass(); } } function closetagname(style, content) { if (style == "xml-name") { token.style = "xml-tagname"; if (context && content.toLowerCase() == context.name) popContext(); else markErr(); } cont(); } function endtag(startOfLine) { return function(style, content) { if (content == "/>" || (content == ">" && UseKludges.autoSelfClosers.hasOwnProperty(currentTag))) cont(); else if (content == ">") {pushContext(currentTag, startOfLine); cont();} else {markErr(); cont(arguments.callee);} }; } function attributes(style) { if (style == "xml-name") {token.style = "xml-attname"; cont(attribute, attributes);} else pass(); } function attribute(style, content) { if (content == "=") cont(value); else if (content == ">" || content == "/>") pass(endtag); else pass(); } function value(style) { if (style == "xml-attribute") cont(value); else pass(); } return { indentation: function() {return indented;}, next: function(){ token = tokens.next(); if (token.style == "whitespace" && tokenNr == 0) indented = token.value.length; else tokenNr++; if (token.content == "\n") { indented = tokenNr = 0; token.indentation = computeIndentation(context); } if (token.style == "whitespace" || token.type == "xml-comment") return token; while(true){ consume = false; cc.pop()(token.style, token.content); if (consume) return token; } }, copy: function(){ var _cc = cc.concat([]), _tokenState = tokens.state, _context = context; var parser = this; return function(input){ cc = _cc.concat([]); tokenNr = indented = 0; context = _context; tokens = tokenizeXML(input, _tokenState); return parser; }; } }; } return { make: parseXML, electricChars: "/", configure: function(config) { if (config.useHTMLKludges != null) UseKludges = config.useHTMLKludges ? Kludges : NoKludges; if (config.alignCDATA) alignCDATA = config.alignCDATA; } }; })();
JavaScript
/* String streams are the things fed to parsers (which can feed them * to a tokenizer if they want). They provide peek and next methods * for looking at the current character (next 'consumes' this * character, peek does not), and a get method for retrieving all the * text that was consumed since the last time get was called. * * An easy mistake to make is to let a StopIteration exception finish * the token stream while there are still characters pending in the * string stream (hitting the end of the buffer while parsing a * token). To make it easier to detect such errors, the stringstreams * throw an exception when this happens. */ // Make a stringstream stream out of an iterator that returns strings. // This is applied to the result of traverseDOM (see codemirror.js), // and the resulting stream is fed to the parser. var stringStream = function(source){ // String that's currently being iterated over. var current = ""; // Position in that string. var pos = 0; // Accumulator for strings that have been iterated over but not // get()-ed yet. var accum = ""; // Make sure there are more characters ready, or throw // StopIteration. function ensureChars() { while (pos == current.length) { accum += current; current = ""; // In case source.next() throws pos = 0; try {current = source.next();} catch (e) { if (e != StopIteration) throw e; else return false; } } return true; } return { // peek: -> character // Return the next character in the stream. peek: function() { if (!ensureChars()) return null; return current.charAt(pos); }, // next: -> character // Get the next character, throw StopIteration if at end, check // for unused content. next: function() { if (!ensureChars()) { if (accum.length > 0) throw "End of stringstream reached without emptying buffer ('" + accum + "')."; else throw StopIteration; } return current.charAt(pos++); }, // get(): -> string // Return the characters iterated over since the last call to // .get(). get: function() { var temp = accum; accum = ""; if (pos > 0){ temp += current.slice(0, pos); current = current.slice(pos); pos = 0; } return temp; }, // Push a string back into the stream. push: function(str) { current = current.slice(0, pos) + str + current.slice(pos); }, lookAhead: function(str, consume, skipSpaces, caseInsensitive) { function cased(str) {return caseInsensitive ? str.toLowerCase() : str;} str = cased(str); var found = false; var _accum = accum, _pos = pos; if (skipSpaces) this.nextWhileMatches(/[\s\u00a0]/); while (true) { var end = pos + str.length, left = current.length - pos; if (end <= current.length) { found = str == cased(current.slice(pos, end)); pos = end; break; } else if (str.slice(0, left) == cased(current.slice(pos))) { accum += current; current = ""; try {current = source.next();} catch (e) {if (e != StopIteration) throw e; break;} pos = 0; str = str.slice(left); } else { break; } } if (!(found && consume)) { current = accum.slice(_accum.length) + current; pos = _pos; accum = _accum; } return found; }, // Wont't match past end of line. lookAheadRegex: function(regex, consume) { if (regex.source.charAt(0) != "^") throw new Error("Regexps passed to lookAheadRegex must start with ^"); // Fetch the rest of the line while (current.indexOf("\n", pos) == -1) { try {current += source.next();} catch (e) {if (e != StopIteration) throw e; break;} } var matched = current.slice(pos).match(regex); if (matched && consume) pos += matched[0].length; return matched; }, // Utils built on top of the above // more: -> boolean // Produce true if the stream isn't empty. more: function() { return this.peek() !== null; }, applies: function(test) { var next = this.peek(); return (next !== null && test(next)); }, nextWhile: function(test) { var next; while ((next = this.peek()) !== null && test(next)) this.next(); }, matches: function(re) { var next = this.peek(); return (next !== null && re.test(next)); }, nextWhileMatches: function(re) { var next; while ((next = this.peek()) !== null && re.test(next)) this.next(); }, equals: function(ch) { return ch === this.peek(); }, endOfLine: function() { var next = this.peek(); return next == null || next == "\n"; } }; };
JavaScript
/* CodeMirror main module (http://codemirror.net/) * * Implements the CodeMirror constructor and prototype, which take care * of initializing the editor frame, and providing the outside interface. */ // The CodeMirrorConfig object is used to specify a default // configuration. If you specify such an object before loading this // file, the values you put into it will override the defaults given // below. You can also assign to it after loading. var CodeMirrorConfig = window.CodeMirrorConfig || {}; var CodeMirror = (function(){ function setDefaults(object, defaults) { for (var option in defaults) { if (!object.hasOwnProperty(option)) object[option] = defaults[option]; } } function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); } function createHTMLElement(el) { if (document.createElementNS && document.documentElement.namespaceURI !== null) return document.createElementNS("http://www.w3.org/1999/xhtml", el) else return document.createElement(el) } // These default options can be overridden by passing a set of // options to a specific CodeMirror constructor. See manual.html for // their meaning. setDefaults(CodeMirrorConfig, { stylesheet: [], path: "", parserfile: [], basefiles: ["util.js", "stringstream.js", "select.js", "undo.js", "editor.js", "tokenize.js"], iframeClass: null, passDelay: 200, passTime: 50, lineNumberDelay: 200, lineNumberTime: 50, continuousScanning: false, saveFunction: null, onLoad: null, onChange: null, undoDepth: 50, undoDelay: 800, disableSpellcheck: true, textWrapping: true, readOnly: false, width: "", height: "300px", minHeight: 100, autoMatchParens: false, markParen: null, unmarkParen: null, parserConfig: null, tabMode: "indent", // or "spaces", "default", "shift" enterMode: "indent", // or "keep", "flat" electricChars: true, reindentOnLoad: false, activeTokens: null, onCursorActivity: null, lineNumbers: false, firstLineNumber: 1, onLineNumberClick: null, indentUnit: 2, domain: null, noScriptCaching: false, incrementalLoading: false }); function addLineNumberDiv(container, firstNum) { var nums = createHTMLElement("div"), scroller = createHTMLElement("div"); nums.style.position = "absolute"; nums.style.height = "100%"; if (nums.style.setExpression) { try {nums.style.setExpression("height", "this.previousSibling.offsetHeight + 'px'");} catch(e) {} // Seems to throw 'Not Implemented' on some IE8 versions } nums.style.top = "0px"; nums.style.left = "0px"; nums.style.overflow = "hidden"; container.appendChild(nums); scroller.className = "CodeMirror-line-numbers"; nums.appendChild(scroller); scroller.innerHTML = "<div>" + firstNum + "</div>"; return nums; } function frameHTML(options) { if (typeof options.parserfile == "string") options.parserfile = [options.parserfile]; if (typeof options.basefiles == "string") options.basefiles = [options.basefiles]; if (typeof options.stylesheet == "string") options.stylesheet = [options.stylesheet]; var html = ["<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head>"]; // Hack to work around a bunch of IE8-specific problems. html.push("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>"); var queryStr = options.noScriptCaching ? "?nocache=" + new Date().getTime().toString(16) : ""; forEach(options.stylesheet, function(file) { html.push("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + file + queryStr + "\"/>"); }); forEach(options.basefiles.concat(options.parserfile), function(file) { if (!/^https?:/.test(file)) file = options.path + file; html.push("<script type=\"text/javascript\" src=\"" + file + queryStr + "\"><" + "/script>"); }); html.push("</head><body style=\"border-width: 0;\" class=\"editbox\" spellcheck=\"" + (options.disableSpellcheck ? "false" : "true") + "\"></body></html>"); return html.join(""); } var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); function CodeMirror(place, options) { // Use passed options, if any, to override defaults. this.options = options = options || {}; setDefaults(options, CodeMirrorConfig); // Backward compatibility for deprecated options. if (options.dumbTabs) options.tabMode = "spaces"; else if (options.normalTab) options.tabMode = "default"; if (options.cursorActivity) options.onCursorActivity = options.cursorActivity; var frame = this.frame = createHTMLElement("iframe"); if (options.iframeClass) frame.className = options.iframeClass; frame.frameBorder = 0; frame.style.border = "0"; frame.style.width = '100%'; frame.style.height = '100%'; // display: block occasionally suppresses some Firefox bugs, so we // always add it, redundant as it sounds. frame.style.display = "block"; var div = this.wrapping = createHTMLElement("div"); div.style.position = "relative"; div.className = "CodeMirror-wrapping"; div.style.width = options.width; div.style.height = (options.height == "dynamic") ? options.minHeight + "px" : options.height; // This is used by Editor.reroutePasteEvent var teHack = this.textareaHack = createHTMLElement("textarea"); div.appendChild(teHack); teHack.style.position = "absolute"; teHack.style.left = "-10000px"; teHack.style.width = "10px"; teHack.tabIndex = 100000; // Link back to this object, so that the editor can fetch options // and add a reference to itself. frame.CodeMirror = this; if (options.domain && internetExplorer) { this.html = frameHTML(options); frame.src = "javascript:(function(){document.open();" + (options.domain ? "document.domain=\"" + options.domain + "\";" : "") + "document.write(window.frameElement.CodeMirror.html);document.close();})()"; } else { frame.src = "javascript:;"; } if (place.appendChild) place.appendChild(div); else place(div); div.appendChild(frame); if (options.lineNumbers) this.lineNumbers = addLineNumberDiv(div, options.firstLineNumber); this.win = frame.contentWindow; if (!options.domain || !internetExplorer) { this.win.document.open(); this.win.document.write(frameHTML(options)); this.win.document.close(); } } CodeMirror.prototype = { init: function() { // Deprecated, but still supported. if (this.options.initCallback) this.options.initCallback(this); if (this.options.onLoad) this.options.onLoad(this); if (this.options.lineNumbers) this.activateLineNumbers(); if (this.options.reindentOnLoad) this.reindent(); if (this.options.height == "dynamic") this.setDynamicHeight(); }, getCode: function() {return this.editor.getCode();}, setCode: function(code) {this.editor.importCode(code);}, selection: function() {this.focusIfIE(); return this.editor.selectedText();}, reindent: function() {this.editor.reindent();}, reindentSelection: function() {this.focusIfIE(); this.editor.reindentSelection(null);}, focusIfIE: function() { // in IE, a lot of selection-related functionality only works when the frame is focused if (this.win.select.ie_selection && document.activeElement != this.frame) this.focus(); }, focus: function() { this.win.focus(); if (this.editor.selectionSnapshot) // IE hack this.win.select.setBookmark(this.win.document.body, this.editor.selectionSnapshot); }, replaceSelection: function(text) { this.focus(); this.editor.replaceSelection(text); return true; }, replaceChars: function(text, start, end) { this.editor.replaceChars(text, start, end); }, getSearchCursor: function(string, fromCursor, caseFold) { return this.editor.getSearchCursor(string, fromCursor, caseFold); }, undo: function() {this.editor.history.undo();}, redo: function() {this.editor.history.redo();}, historySize: function() {return this.editor.history.historySize();}, clearHistory: function() {this.editor.history.clear();}, grabKeys: function(callback, filter) {this.editor.grabKeys(callback, filter);}, ungrabKeys: function() {this.editor.ungrabKeys();}, setParser: function(name, parserConfig) {this.editor.setParser(name, parserConfig);}, setSpellcheck: function(on) {this.win.document.body.spellcheck = on;}, setStylesheet: function(names) { if (typeof names === "string") names = [names]; var activeStylesheets = {}; var matchedNames = {}; var links = this.win.document.getElementsByTagName("link"); // Create hashes of active stylesheets and matched names. // This is O(n^2) but n is expected to be very small. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { for (var y = 0; y < names.length; y++) { var name = names[y]; if (link.href.substring(link.href.length - name.length) === name) { activeStylesheets[link.href] = true; matchedNames[name] = true; } } } } // Activate the selected stylesheets and disable the rest. for (var x = 0, link; link = links[x]; x++) { if (link.rel.indexOf("stylesheet") !== -1) { link.disabled = !(link.href in activeStylesheets); } } // Create any new stylesheets. for (var y = 0; y < names.length; y++) { var name = names[y]; if (!(name in matchedNames)) { var link = this.win.document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = name; this.win.document.getElementsByTagName('head')[0].appendChild(link); } } }, setTextWrapping: function(on) { if (on == this.options.textWrapping) return; this.win.document.body.style.whiteSpace = on ? "" : "nowrap"; this.options.textWrapping = on; if (this.lineNumbers) { this.setLineNumbers(false); this.setLineNumbers(true); } }, setIndentUnit: function(unit) {this.win.indentUnit = unit;}, setUndoDepth: function(depth) {this.editor.history.maxDepth = depth;}, setTabMode: function(mode) {this.options.tabMode = mode;}, setEnterMode: function(mode) {this.options.enterMode = mode;}, setLineNumbers: function(on) { if (on && !this.lineNumbers) { this.lineNumbers = addLineNumberDiv(this.wrapping,this.options.firstLineNumber); this.activateLineNumbers(); } else if (!on && this.lineNumbers) { this.wrapping.removeChild(this.lineNumbers); this.wrapping.style.paddingLeft = ""; this.lineNumbers = null; } }, cursorPosition: function(start) {this.focusIfIE(); return this.editor.cursorPosition(start);}, firstLine: function() {return this.editor.firstLine();}, lastLine: function() {return this.editor.lastLine();}, nextLine: function(line) {return this.editor.nextLine(line);}, prevLine: function(line) {return this.editor.prevLine(line);}, lineContent: function(line) {return this.editor.lineContent(line);}, setLineContent: function(line, content) {this.editor.setLineContent(line, content);}, removeLine: function(line){this.editor.removeLine(line);}, insertIntoLine: function(line, position, content) {this.editor.insertIntoLine(line, position, content);}, selectLines: function(startLine, startOffset, endLine, endOffset) { this.win.focus(); this.editor.selectLines(startLine, startOffset, endLine, endOffset); }, nthLine: function(n) { var line = this.firstLine(); for (; n > 1 && line !== false; n--) line = this.nextLine(line); return line; }, lineNumber: function(line) { var num = 0; while (line !== false) { num++; line = this.prevLine(line); } return num; }, jumpToLine: function(line) { if (typeof line == "number") line = this.nthLine(line); this.selectLines(line, 0); this.win.focus(); }, currentLine: function() { // Deprecated, but still there for backward compatibility return this.lineNumber(this.cursorLine()); }, cursorLine: function() { return this.cursorPosition().line; }, cursorCoords: function(start) {return this.editor.cursorCoords(start);}, activateLineNumbers: function() { var frame = this.frame, win = frame.contentWindow, doc = win.document, body = doc.body, nums = this.lineNumbers, scroller = nums.firstChild, self = this; var barWidth = null; nums.onclick = function(e) { var handler = self.options.onLineNumberClick; if (handler) { var div = (e || window.event).target || (e || window.event).srcElement; var num = div == nums ? NaN : Number(div.innerHTML); if (!isNaN(num)) handler(num, div); } }; function sizeBar() { if (frame.offsetWidth == 0) return; for (var root = frame; root.parentNode; root = root.parentNode){} if (!nums.parentNode || root != document || !win.Editor) { // Clear event handlers (their nodes might already be collected, so try/catch) try{clear();}catch(e){} clearInterval(sizeInterval); return; } if (nums.offsetWidth != barWidth) { barWidth = nums.offsetWidth; frame.parentNode.style.paddingLeft = barWidth + "px"; } } function doScroll() { nums.scrollTop = body.scrollTop || doc.documentElement.scrollTop || 0; } // Cleanup function, registered by nonWrapping and wrapping. var clear = function(){}; sizeBar(); var sizeInterval = setInterval(sizeBar, 500); function ensureEnoughLineNumbers(fill) { var lineHeight = scroller.firstChild.offsetHeight; if (lineHeight == 0) return; var targetHeight = 50 + Math.max(body.offsetHeight, Math.max(frame.offsetHeight, body.scrollHeight || 0)), lastNumber = Math.ceil(targetHeight / lineHeight); for (var i = scroller.childNodes.length; i <= lastNumber; i++) { var div = createHTMLElement("div"); div.appendChild(document.createTextNode(fill ? String(i + self.options.firstLineNumber) : "\u00a0")); scroller.appendChild(div); } } function nonWrapping() { function update() { ensureEnoughLineNumbers(true); doScroll(); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ onScroll(); onResize(); if (self.updateNumbers == update) self.updateNumbers = null; }; update(); } function wrapping() { var node, lineNum, next, pos, changes = [], styleNums = self.options.styleNumbers; function setNum(n, node) { // Does not typically happen (but can, if you mess with the // document during the numbering) if (!lineNum) lineNum = scroller.appendChild(createHTMLElement("div")); if (styleNums) styleNums(lineNum, node, n); // Changes are accumulated, so that the document layout // doesn't have to be recomputed during the pass changes.push(lineNum); changes.push(n); pos = lineNum.offsetHeight + lineNum.offsetTop; lineNum = lineNum.nextSibling; } function commitChanges() { for (var i = 0; i < changes.length; i += 2) changes[i].innerHTML = changes[i + 1]; changes = []; } function work() { if (!scroller.parentNode || scroller.parentNode != self.lineNumbers) return; var endTime = new Date().getTime() + self.options.lineNumberTime; while (node) { setNum(next++, node.previousSibling); for (; node && !win.isBR(node); node = node.nextSibling) { var bott = node.offsetTop + node.offsetHeight; while (scroller.offsetHeight && bott - 3 > pos) { var oldPos = pos; setNum("&nbsp;"); if (pos <= oldPos) break; } } if (node) node = node.nextSibling; if (new Date().getTime() > endTime) { commitChanges(); pending = setTimeout(work, self.options.lineNumberDelay); return; } } while (lineNum) setNum(next++); commitChanges(); doScroll(); } function start(firstTime) { doScroll(); ensureEnoughLineNumbers(firstTime); node = body.firstChild; lineNum = scroller.firstChild; pos = 0; next = self.options.firstLineNumber; work(); } start(true); var pending = null; function update() { if (pending) clearTimeout(pending); if (self.editor.allClean()) start(); else pending = setTimeout(update, 200); } self.updateNumbers = update; var onScroll = win.addEventHandler(win, "scroll", doScroll, true), onResize = win.addEventHandler(win, "resize", update, true); clear = function(){ if (pending) clearTimeout(pending); if (self.updateNumbers == update) self.updateNumbers = null; onScroll(); onResize(); }; } (this.options.textWrapping || this.options.styleNumbers ? wrapping : nonWrapping)(); }, setDynamicHeight: function() { var self = this, activity = self.options.onCursorActivity, win = self.win, body = win.document.body, lineHeight = null, timeout = null, vmargin = 2 * self.frame.offsetTop; body.style.overflowY = "hidden"; win.document.documentElement.style.overflowY = "hidden"; this.frame.scrolling = "no"; function updateHeight() { var trailingLines = 0, node = body.lastChild, computedHeight; while (node && win.isBR(node)) { if (!node.hackBR) trailingLines++; node = node.previousSibling; } if (node) { lineHeight = node.offsetHeight; computedHeight = node.offsetTop + (1 + trailingLines) * lineHeight; } else if (lineHeight) { computedHeight = trailingLines * lineHeight; } if (computedHeight) self.wrapping.style.height = Math.max(vmargin + computedHeight, self.options.minHeight) + "px"; } setTimeout(updateHeight, 300); self.options.onCursorActivity = function(x) { if (activity) activity(x); clearTimeout(timeout); timeout = setTimeout(updateHeight, 100); }; } }; CodeMirror.InvalidLineHandle = {toString: function(){return "CodeMirror.InvalidLineHandle";}}; CodeMirror.replace = function(element) { if (typeof element == "string") element = document.getElementById(element); return function(newElement) { element.parentNode.replaceChild(newElement, element); }; }; CodeMirror.fromTextArea = function(area, options) { if (typeof area == "string") area = document.getElementById(area); options = options || {}; if (area.style.width && options.width == null) options.width = area.style.width; if (area.style.height && options.height == null) options.height = area.style.height; if (options.content == null) options.content = area.value; function updateField() { area.value = mirror.getCode(); } if (area.form) { if (typeof area.form.addEventListener == "function") area.form.addEventListener("submit", updateField, false); else area.form.attachEvent("onsubmit", updateField); var realSubmit = area.form.submit; function wrapSubmit() { updateField(); // Can't use realSubmit.apply because IE6 is too stupid area.form.submit = realSubmit; area.form.submit(); area.form.submit = wrapSubmit; } area.form.submit = wrapSubmit; } function insert(frame) { if (area.nextSibling) area.parentNode.insertBefore(frame, area.nextSibling); else area.parentNode.appendChild(frame); } area.style.display = "none"; var mirror = new CodeMirror(insert, options); mirror.save = updateField; mirror.toTextArea = function() { updateField(); area.parentNode.removeChild(mirror.wrapping); area.style.display = ""; if (area.form) { area.form.submit = realSubmit; if (typeof area.form.removeEventListener == "function") area.form.removeEventListener("submit", updateField, false); else area.form.detachEvent("onsubmit", updateField); } }; return mirror; }; CodeMirror.isProbablySupported = function() { // This is rather awful, but can be useful. var match; if (window.opera) return Number(window.opera.version()) >= 9.52; else if (/Apple Computer, Inc/.test(navigator.vendor) && (match = navigator.userAgent.match(/Version\/(\d+(?:\.\d+)?)\./))) return Number(match[1]) >= 3; else if (document.selection && window.ActiveXObject && (match = navigator.userAgent.match(/MSIE (\d+(?:\.\d*)?)\b/))) return Number(match[1]) >= 6; else if (match = navigator.userAgent.match(/gecko\/(\d{8})/i)) return Number(match[1]) >= 20050901; else if (match = navigator.userAgent.match(/AppleWebKit\/(\d+)/)) return Number(match[1]) >= 525; else return null; }; return CodeMirror; })();
JavaScript
/* Parse function for JavaScript. Makes use of the tokenizer from * tokenizejavascript.js. Note that your parsers do not have to be * this complicated -- if you don't want to recognize local variables, * in many languages it is enough to just look for braces, semicolons, * parentheses, etc, and know when you are inside a string or comment. * * See manual.html for more info about the parser interface. */ var JSParser = Editor.Parser = (function() { // Token types that can be considered to be atoms. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; // Setting that can be used to have JSON data indent properly. var json = false; // Constructor for the lexical context objects. function JSLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // My favourite JavaScript indentation rules. function indentJS(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parseJS(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizeJavaScript(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [json ? expressions : statements]; // Context contains information about the current local scope, the // variables defined in that, and the scopes above it. var context = null; // The lexical scope, used mostly for indentation. var lexical = new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' // function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch a token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentJS(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment") return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. while(true) { consume = marked = false; // Take and execute the topmost action. cc.pop()(token.type, token.content); if (consume){ // Marked is used to change the style of the current token. if (marked) token.style = marked; // Here we differentiate between local and global variables. else if (token.type == "variable" && inScope(token.content)) token.style = "js-localvariable"; return token; } } } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, and context // objects are not mutated in a harmful way, so they can be shared // between runs of the parser. function copy(){ var _context = context, _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ context = _context; lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizeJavaScript(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Push a new scope. Will automatically link the current scope. function pushcontext(){ context = {prev: context, vars: {"this": true, "arguments": true}}; } // Pop off the current scope. function popcontext(){ context = context.prev; } // Register a variable in the current scope. function register(varname){ if (context){ mark("js-variabledef"); context.vars[varname] = true; } } // Check whether a variable is defined in the current scope. function inScope(varname){ var cursor = context; while (cursor) { if (cursor.vars[varname]) return true; cursor = cursor.prev; } return false; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function(){ lexical = new JSLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.type == ")") indented = lexical.indented; lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. function expect(wanted){ return function expecting(type){ if (type == wanted) cont(); else if (wanted == ";") pass(); else cont(arguments.callee); }; } // Looks for a statement, and then calls itself. function statements(type){ return pass(statement, statements); } function expressions(type){ return pass(expression, expressions); } // Dispatches various types of statements based on the type of the // current token. function statement(type){ if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex); else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == ";") cont(); else if (type == "function") cont(functiondef); else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); else if (type == "variable") cont(pushlex("stat"), maybelabel); else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); else if (type == "case") cont(expression, expect(":")); else if (type == "default") cont(expect(":")); else if (type == "catch") cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); else pass(pushlex("stat"), expression, expect(";"), poplex); } // Dispatch expression types. function expression(type){ if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "function") cont(functiondef); else if (type == "keyword c") cont(expression); else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); else if (type == "operator") cont(expression); else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); else cont(); } // Called for places where operators, function calls, or // subscripts are valid. Will skip on to the next action if none // is found. function maybeoperator(type, value){ if (type == "operator" && /\+\+|--/.test(value)) cont(maybeoperator); else if (type == "operator") cont(expression); else if (type == ";") pass(); else if (type == "(") cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); else if (type == ".") cont(property, maybeoperator); else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } // When a statement starts with a variable name, it might be a // label. If no colon follows, it's a regular statement. function maybelabel(type){ if (type == ":") cont(poplex, statement); else pass(maybeoperator, expect(";"), poplex); } // Property names need to have their style adjusted -- the // tokenizer thinks they are variables. function property(type){ if (type == "variable") {mark("js-property"); cont();} } // This parses a property and its value in an object literal. function objprop(type){ if (type == "variable") mark("js-property"); if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what, end){ function proceed(type) { if (type == ",") cont(what, proceed); else if (type == end) cont(); else cont(expect(end)); } return function commaSeparated(type) { if (type == end) cont(); else pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(type){ if (type == "}") cont(); else pass(statement, block); } // Variable definitions are split into two actions -- 1 looks for // a name or the end of the definition, 2 looks for an '=' sign or // a comma. function vardef1(type, value){ if (type == "variable"){register(value); cont(vardef2);} else cont(); } function vardef2(type, value){ if (value == "=") cont(expression, vardef2); else if (type == ",") cont(vardef1); } // For loops. function forspec1(type){ if (type == "var") cont(vardef1, forspec2); else if (type == ";") pass(forspec2); else if (type == "variable") cont(formaybein); else pass(forspec2); } function formaybein(type, value){ if (value == "in") cont(expression); else cont(maybeoperator, forspec2); } function forspec2(type, value){ if (type == ";") cont(forspec3); else if (value == "in") cont(expression); else cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type == ")") pass(); else cont(expression); } // A function definition creates a new context, and the variables // in its argument list have to be added to this context. function functiondef(type, value){ if (type == "variable"){register(value); cont(functiondef);} else if (type == "(") cont(pushcontext, commasep(funarg, ")"), statement, popcontext); } function funarg(type, value){ if (type == "variable"){register(value); cont();} } return parser; } return { make: parseJS, electricChars: "{}:", configure: function(obj) { if (obj.json != null) json = obj.json; } }; })();
JavaScript
/** * Storage and control for undo information within a CodeMirror * editor. 'Why on earth is such a complicated mess required for * that?', I hear you ask. The goal, in implementing this, was to make * the complexity of storing and reverting undo information depend * only on the size of the edited or restored content, not on the size * of the whole document. This makes it necessary to use a kind of * 'diff' system, which, when applied to a DOM tree, causes some * complexity and hackery. * * In short, the editor 'touches' BR elements as it parses them, and * the UndoHistory stores these. When nothing is touched in commitDelay * milliseconds, the changes are committed: It goes over all touched * nodes, throws out the ones that did not change since last commit or * are no longer in the document, and assembles the rest into zero or * more 'chains' -- arrays of adjacent lines. Links back to these * chains are added to the BR nodes, while the chain that previously * spanned these nodes is added to the undo history. Undoing a change * means taking such a chain off the undo history, restoring its * content (text is saved per line) and linking it back into the * document. */ // A history object needs to know about the DOM container holding the // document, the maximum amount of undo levels it should store, the // delay (of no input) after which it commits a set of changes, and, // unfortunately, the 'parent' window -- a window that is not in // designMode, and on which setTimeout works in every browser. function UndoHistory(container, maxDepth, commitDelay, editor) { this.container = container; this.maxDepth = maxDepth; this.commitDelay = commitDelay; this.editor = editor; // This line object represents the initial, empty editor. var initial = {text: "", from: null, to: null}; // As the borders between lines are represented by BR elements, the // start of the first line and the end of the last one are // represented by null. Since you can not store any properties // (links to line objects) in null, these properties are used in // those cases. this.first = initial; this.last = initial; // Similarly, a 'historyTouched' property is added to the BR in // front of lines that have already been touched, and 'firstTouched' // is used for the first line. this.firstTouched = false; // History is the set of committed changes, touched is the set of // nodes touched since the last commit. this.history = []; this.redoHistory = []; this.touched = []; this.lostundo = 0; } UndoHistory.prototype = { // Schedule a commit (if no other touches come in for commitDelay // milliseconds). scheduleCommit: function() { var self = this; parent.clearTimeout(this.commitTimeout); this.commitTimeout = parent.setTimeout(function(){self.tryCommit();}, this.commitDelay); }, // Mark a node as touched. Null is a valid argument. touch: function(node) { this.setTouched(node); this.scheduleCommit(); }, // Undo the last change. undo: function() { // Make sure pending changes have been committed. this.commit(); if (this.history.length) { // Take the top diff from the history, apply it, and store its // shadow in the redo history. var item = this.history.pop(); this.redoHistory.push(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, // Redo the last undone change. redo: function() { this.commit(); if (this.redoHistory.length) { // The inverse of undo, basically. var item = this.redoHistory.pop(); this.addUndoLevel(this.updateTo(item, "applyChain")); this.notifyEnvironment(); return this.chainNode(item); } }, clear: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, // Ask for the size of the un/redo histories. historySize: function() { return {undo: this.history.length, redo: this.redoHistory.length, lostundo: this.lostundo}; }, // Push a changeset into the document. push: function(from, to, lines) { var chain = []; for (var i = 0; i < lines.length; i++) { var end = (i == lines.length - 1) ? to : document.createElement("br"); chain.push({from: from, to: end, text: cleanText(lines[i])}); from = end; } this.pushChains([chain], from == null && to == null); this.notifyEnvironment(); }, pushChains: function(chains, doNotHighlight) { this.commit(doNotHighlight); this.addUndoLevel(this.updateTo(chains, "applyChain")); this.redoHistory = []; }, // Retrieve a DOM node from a chain (for scrolling to it after undo/redo). chainNode: function(chains) { for (var i = 0; i < chains.length; i++) { var start = chains[i][0], node = start && (start.from || start.to); if (node) return node; } }, // Clear the undo history, make the current document the start // position. reset: function() { this.history = []; this.redoHistory = []; this.lostundo = 0; }, textAfter: function(br) { return this.after(br).text; }, nodeAfter: function(br) { return this.after(br).to; }, nodeBefore: function(br) { return this.before(br).from; }, // Commit unless there are pending dirty nodes. tryCommit: function() { if (!window || !window.parent || !window.UndoHistory) return; // Stop when frame has been unloaded if (this.editor.highlightDirty()) this.commit(true); else this.scheduleCommit(); }, // Check whether the touched nodes hold any changes, if so, commit // them. commit: function(doNotHighlight) { parent.clearTimeout(this.commitTimeout); // Make sure there are no pending dirty nodes. if (!doNotHighlight) this.editor.highlightDirty(true); // Build set of chains. var chains = this.touchedChains(), self = this; if (chains.length) { this.addUndoLevel(this.updateTo(chains, "linkChain")); this.redoHistory = []; this.notifyEnvironment(); } }, // [ end of public interface ] // Update the document with a given set of chains, return its // shadow. updateFunc should be "applyChain" or "linkChain". In the // second case, the chains are taken to correspond the the current // document, and only the state of the line data is updated. In the // first case, the content of the chains is also pushed iinto the // document. updateTo: function(chains, updateFunc) { var shadows = [], dirty = []; for (var i = 0; i < chains.length; i++) { shadows.push(this.shadowChain(chains[i])); dirty.push(this[updateFunc](chains[i])); } if (updateFunc == "applyChain") this.notifyDirty(dirty); return shadows; }, // Notify the editor that some nodes have changed. notifyDirty: function(nodes) { forEach(nodes, method(this.editor, "addDirtyNode")) this.editor.scheduleHighlight(); }, notifyEnvironment: function() { if (this.onChange) this.onChange(this.editor); // Used by the line-wrapping line-numbering code. if (window.frameElement && window.frameElement.CodeMirror.updateNumbers) window.frameElement.CodeMirror.updateNumbers(); }, // Link a chain into the DOM nodes (or the first/last links for null // nodes). linkChain: function(chain) { for (var i = 0; i < chain.length; i++) { var line = chain[i]; if (line.from) line.from.historyAfter = line; else this.first = line; if (line.to) line.to.historyBefore = line; else this.last = line; } }, // Get the line object after/before a given node. after: function(node) { return node ? node.historyAfter : this.first; }, before: function(node) { return node ? node.historyBefore : this.last; }, // Mark a node as touched if it has not already been marked. setTouched: function(node) { if (node) { if (!node.historyTouched) { this.touched.push(node); node.historyTouched = true; } } else { this.firstTouched = true; } }, // Store a new set of undo info, throw away info if there is more of // it than allowed. addUndoLevel: function(diffs) { this.history.push(diffs); if (this.history.length > this.maxDepth) { this.history.shift(); lostundo += 1; } }, // Build chains from a set of touched nodes. touchedChains: function() { var self = this; // The temp system is a crummy hack to speed up determining // whether a (currently touched) node has a line object associated // with it. nullTemp is used to store the object for the first // line, other nodes get it stored in their historyTemp property. var nullTemp = null; function temp(node) {return node ? node.historyTemp : nullTemp;} function setTemp(node, line) { if (node) node.historyTemp = line; else nullTemp = line; } function buildLine(node) { var text = []; for (var cur = node ? node.nextSibling : self.container.firstChild; cur && (!isBR(cur) || cur.hackBR); cur = cur.nextSibling) if (!cur.hackBR && cur.currentText) text.push(cur.currentText); return {from: node, to: cur, text: cleanText(text.join(""))}; } // Filter out unchanged lines and nodes that are no longer in the // document. Build up line objects for remaining nodes. var lines = []; if (self.firstTouched) self.touched.push(null); forEach(self.touched, function(node) { if (node && (node.parentNode != self.container || node.hackBR)) return; if (node) node.historyTouched = false; else self.firstTouched = false; var line = buildLine(node), shadow = self.after(node); if (!shadow || shadow.text != line.text || shadow.to != line.to) { lines.push(line); setTemp(node, line); } }); // Get the BR element after/before the given node. function nextBR(node, dir) { var link = dir + "Sibling", search = node[link]; while (search && !isBR(search)) search = search[link]; return search; } // Assemble line objects into chains by scanning the DOM tree // around them. var chains = []; self.touched = []; forEach(lines, function(line) { // Note that this makes the loop skip line objects that have // been pulled into chains by lines before them. if (!temp(line.from)) return; var chain = [], curNode = line.from, safe = true; // Put any line objects (referred to by temp info) before this // one on the front of the array. while (true) { var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.unshift(curLine); setTemp(curNode, null); if (!curNode) break; safe = self.after(curNode); curNode = nextBR(curNode, "previous"); } curNode = line.to; safe = self.before(line.from); // Add lines after this one at end of array. while (true) { if (!curNode) break; var curLine = temp(curNode); if (!curLine) { if (safe) break; else curLine = buildLine(curNode); } chain.push(curLine); setTemp(curNode, null); safe = self.before(curNode); curNode = nextBR(curNode, "next"); } chains.push(chain); }); return chains; }, // Find the 'shadow' of a given chain by following the links in the // DOM nodes at its start and end. shadowChain: function(chain) { var shadows = [], next = this.after(chain[0].from), end = chain[chain.length - 1].to; while (true) { shadows.push(next); var nextNode = next.to; if (!nextNode || nextNode == end) break; else next = nextNode.historyAfter || this.before(end); // (The this.before(end) is a hack -- FF sometimes removes // properties from BR nodes, in which case the best we can hope // for is to not break.) } return shadows; }, // Update the DOM tree to contain the lines specified in a given // chain, link this chain into the DOM nodes. applyChain: function(chain) { // Some attempt is made to prevent the cursor from jumping // randomly when an undo or redo happens. It still behaves a bit // strange sometimes. var cursor = select.cursorPos(this.container, false), self = this; // Remove all nodes in the DOM tree between from and to (null for // start/end of container). function removeRange(from, to) { var pos = from ? from.nextSibling : self.container.firstChild; while (pos != to) { var temp = pos.nextSibling; removeElement(pos); pos = temp; } } var start = chain[0].from, end = chain[chain.length - 1].to; // Clear the space where this change has to be made. removeRange(start, end); // Insert the content specified by the chain into the DOM tree. for (var i = 0; i < chain.length; i++) { var line = chain[i]; // The start and end of the space are already correct, but BR // tags inside it have to be put back. if (i > 0) self.container.insertBefore(line.from, end); // Add the text. var node = makePartSpan(fixSpaces(line.text)); self.container.insertBefore(node, end); // See if the cursor was on this line. Put it back, adjusting // for changed line length, if it was. if (cursor && cursor.node == line.from) { var cursordiff = 0; var prev = this.after(line.from); if (prev && i == chain.length - 1) { // Only adjust if the cursor is after the unchanged part of // the line. for (var match = 0; match < cursor.offset && line.text.charAt(match) == prev.text.charAt(match); match++){} if (cursor.offset > match) cursordiff = line.text.length - prev.text.length; } select.setCursorPos(this.container, {node: line.from, offset: Math.max(0, cursor.offset + cursordiff)}); } // Cursor was in removed line, this is last new line. else if (cursor && (i == chain.length - 1) && cursor.node && cursor.node.parentNode != this.container) { select.setCursorPos(this.container, {node: line.from, offset: line.text.length}); } } // Anchor the chain in the DOM tree. this.linkChain(chain); return start; } };
JavaScript
var DummyParser = Editor.Parser = (function() { function tokenizeDummy(source) { while (!source.endOfLine()) source.next(); return "text"; } function parseDummy(source) { function indentTo(n) {return function() {return n;}} source = tokenizer(source, tokenizeDummy); var space = 0; var iter = { next: function() { var tok = source.next(); if (tok.type == "whitespace") { if (tok.value == "\n") tok.indentation = indentTo(space); else space = tok.value.length; } return tok; }, copy: function() { var _space = space; return function(_source) { space = _space; source = tokenizer(_source, tokenizeDummy); return iter; }; } }; return iter; } return {make: parseDummy}; })();
JavaScript
/* A few useful utility functions. */ // Capture a method on an object. function method(obj, name) { return function() {obj[name].apply(obj, arguments);}; } // The value used to signal the end of a sequence in iterators. var StopIteration = {toString: function() {return "StopIteration"}}; // Apply a function to each element in a sequence. function forEach(iter, f) { if (iter.next) { try {while (true) f(iter.next());} catch (e) {if (e != StopIteration) throw e;} } else { for (var i = 0; i < iter.length; i++) f(iter[i]); } } // Map a function over a sequence, producing an array of results. function map(iter, f) { var accum = []; forEach(iter, function(val) {accum.push(f(val));}); return accum; } // Create a predicate function that tests a string againsts a given // regular expression. No longer used but might be used by 3rd party // parsers. function matcher(regexp){ return function(value){return regexp.test(value);}; } // Test whether a DOM node has a certain CSS class. function hasClass(element, className) { var classes = element.className; return classes && new RegExp("(^| )" + className + "($| )").test(classes); } function removeClass(element, className) { element.className = element.className.replace(new RegExp(" " + className + "\\b", "g"), ""); return element; } // Insert a DOM node after another node. function insertAfter(newNode, oldNode) { var parent = oldNode.parentNode; parent.insertBefore(newNode, oldNode.nextSibling); return newNode; } function removeElement(node) { if (node.parentNode) node.parentNode.removeChild(node); } function clearElement(node) { while (node.firstChild) node.removeChild(node.firstChild); } // Check whether a node is contained in another one. function isAncestor(node, child) { while (child = child.parentNode) { if (node == child) return true; } return false; } // The non-breaking space character. var nbsp = "\u00a0"; var matching = {"{": "}", "[": "]", "(": ")", "}": "{", "]": "[", ")": "("}; // Standardize a few unportable event properties. function normalizeEvent(event) { if (!event.stopPropagation) { event.stopPropagation = function() {this.cancelBubble = true;}; event.preventDefault = function() {this.returnValue = false;}; } if (!event.stop) { event.stop = function() { this.stopPropagation(); this.preventDefault(); }; } if (event.type == "keypress") { event.code = (event.charCode == null) ? event.keyCode : event.charCode; event.character = String.fromCharCode(event.code); } return event; } // Portably register event handlers. function addEventHandler(node, type, handler, removeFunc) { function wrapHandler(event) { handler(normalizeEvent(event || window.event)); } if (typeof node.addEventListener == "function") { node.addEventListener(type, wrapHandler, false); if (removeFunc) return function() {node.removeEventListener(type, wrapHandler, false);}; } else { node.attachEvent("on" + type, wrapHandler); if (removeFunc) return function() {node.detachEvent("on" + type, wrapHandler);}; } } function nodeText(node) { return node.textContent || node.innerText || node.nodeValue || ""; } function nodeTop(node) { var top = 0; while (node.offsetParent) { top += node.offsetTop; node = node.offsetParent; } return top; } function isBR(node) { var nn = node.nodeName; return nn == "BR" || nn == "br"; } function isSpan(node) { var nn = node.nodeName; return nn == "SPAN" || nn == "span"; }
JavaScript
/* Functionality for finding, storing, and restoring selections * * This does not provide a generic API, just the minimal functionality * required by the CodeMirror system. */ // Namespace object. var select = {}; (function() { select.ie_selection = document.selection && document.selection.createRangeCollection; // Find the 'top-level' (defined as 'a direct child of the node // passed as the top argument') node that the given node is // contained in. Return null if the given node is not inside the top // node. function topLevelNodeAt(node, top) { while (node && node.parentNode != top) node = node.parentNode; return node; } // Find the top-level node that contains the node before this one. function topLevelNodeBefore(node, top) { while (!node.previousSibling && node.parentNode != top) node = node.parentNode; return topLevelNodeAt(node.previousSibling, top); } var fourSpaces = "\u00a0\u00a0\u00a0\u00a0"; select.scrollToNode = function(node, cursor) { if (!node) return; var element = node, body = document.body, html = document.documentElement, atEnd = !element.nextSibling || !element.nextSibling.nextSibling || !element.nextSibling.nextSibling.nextSibling; // In Opera (and recent Webkit versions), BR elements *always* // have a offsetTop property of zero. var compensateHack = 0; while (element && !element.offsetTop) { compensateHack++; element = element.previousSibling; } // atEnd is another kludge for these browsers -- if the cursor is // at the end of the document, and the node doesn't have an // offset, just scroll to the end. if (compensateHack == 0) atEnd = false; // WebKit has a bad habit of (sometimes) happily returning bogus // offsets when the document has just been changed. This seems to // always be 5/5, so we don't use those. if (webkit && element && element.offsetTop == 5 && element.offsetLeft == 5) return; var y = compensateHack * (element ? element.offsetHeight : 0), x = 0, width = (node ? node.offsetWidth : 0), pos = element; while (pos && pos.offsetParent) { y += pos.offsetTop; // Don't count X offset for <br> nodes if (!isBR(pos)) x += pos.offsetLeft; pos = pos.offsetParent; } var scroll_x = body.scrollLeft || html.scrollLeft || 0, scroll_y = body.scrollTop || html.scrollTop || 0, scroll = false, screen_width = window.innerWidth || html.clientWidth || 0; if (cursor || width < screen_width) { if (cursor) { var off = select.offsetInNode(node), size = nodeText(node).length; if (size) x += width * (off / size); } var screen_x = x - scroll_x; if (screen_x < 0 || screen_x > screen_width) { scroll_x = x; scroll = true; } } var screen_y = y - scroll_y; if (screen_y < 0 || atEnd || screen_y > (window.innerHeight || html.clientHeight || 0) - 50) { scroll_y = atEnd ? 1e6 : y; scroll = true; } if (scroll) window.scrollTo(scroll_x, scroll_y); }; select.scrollToCursor = function(container) { select.scrollToNode(select.selectionTopNode(container, true) || container.firstChild, true); }; // Used to prevent restoring a selection when we do not need to. var currentSelection = null; select.snapshotChanged = function() { if (currentSelection) currentSelection.changed = true; }; // Find the 'leaf' node (BR or text) after the given one. function baseNodeAfter(node) { var next = node.nextSibling; if (next) { while (next.firstChild) next = next.firstChild; if (next.nodeType == 3 || isBR(next)) return next; else return baseNodeAfter(next); } else { var parent = node.parentNode; while (parent && !parent.nextSibling) parent = parent.parentNode; return parent && baseNodeAfter(parent); } } // This is called by the code in editor.js whenever it is replacing // a text node. The function sees whether the given oldNode is part // of the current selection, and updates this selection if it is. // Because nodes are often only partially replaced, the length of // the part that gets replaced has to be taken into account -- the // selection might stay in the oldNode if the newNode is smaller // than the selection's offset. The offset argument is needed in // case the selection does move to the new object, and the given // length is not the whole length of the new node (part of it might // have been used to replace another node). select.snapshotReplaceNode = function(from, to, length, offset) { if (!currentSelection) return; function replace(point) { if (from == point.node) { currentSelection.changed = true; if (length && point.offset > length) { point.offset -= length; } else { point.node = to; point.offset += (offset || 0); } } else if (select.ie_selection && point.offset == 0 && point.node == baseNodeAfter(from)) { currentSelection.changed = true; } } replace(currentSelection.start); replace(currentSelection.end); }; select.snapshotMove = function(from, to, distance, relative, ifAtStart) { if (!currentSelection) return; function move(point) { if (from == point.node && (!ifAtStart || point.offset == 0)) { currentSelection.changed = true; point.node = to; if (relative) point.offset = Math.max(0, point.offset + distance); else point.offset = distance; } } move(currentSelection.start); move(currentSelection.end); }; // Most functions are defined in two ways, one for the IE selection // model, one for the W3C one. if (select.ie_selection) { function selRange() { var sel = document.selection; return sel && (sel.createRange || sel.createTextRange)(); } function selectionNode(start) { var range = selRange(); range.collapse(start); function nodeAfter(node) { var found = null; while (!found && node) { found = node.nextSibling; node = node.parentNode; } return nodeAtStartOf(found); } function nodeAtStartOf(node) { while (node && node.firstChild) node = node.firstChild; return {node: node, offset: 0}; } var containing = range.parentElement(); if (!isAncestor(document.body, containing)) return null; if (!containing.firstChild) return nodeAtStartOf(containing); var working = range.duplicate(); working.moveToElementText(containing); working.collapse(true); for (var cur = containing.firstChild; cur; cur = cur.nextSibling) { if (cur.nodeType == 3) { var size = cur.nodeValue.length; working.move("character", size); } else { working.moveToElementText(cur); working.collapse(false); } var dir = range.compareEndPoints("StartToStart", working); if (dir == 0) return nodeAfter(cur); if (dir == 1) continue; if (cur.nodeType != 3) return nodeAtStartOf(cur); working.setEndPoint("StartToEnd", range); return {node: cur, offset: size - working.text.length}; } return nodeAfter(containing); } select.markSelection = function() { currentSelection = null; var sel = document.selection; if (!sel) return; var start = selectionNode(true), end = selectionNode(false); if (!start || !end) return; currentSelection = {start: start, end: end, changed: false}; }; select.selectMarked = function() { if (!currentSelection || !currentSelection.changed) return; function makeRange(point) { var range = document.body.createTextRange(), node = point.node; if (!node) { range.moveToElementText(document.body); range.collapse(false); } else if (node.nodeType == 3) { range.moveToElementText(node.parentNode); var offset = point.offset; while (node.previousSibling) { node = node.previousSibling; offset += (node.innerText || "").length; } range.move("character", offset); } else { range.moveToElementText(node); range.collapse(true); } return range; } var start = makeRange(currentSelection.start), end = makeRange(currentSelection.end); start.setEndPoint("StartToEnd", end); start.select(); }; select.offsetInNode = function(node) { var range = selRange(); if (!range) return 0; var range2 = range.duplicate(); try {range2.moveToElementText(node);} catch(e){return 0;} range.setEndPoint("StartToStart", range2); return range.text.length; }; // Get the top-level node that one end of the cursor is inside or // after. Note that this returns false for 'no cursor', and null // for 'start of document'. select.selectionTopNode = function(container, start) { var range = selRange(); if (!range) return false; var range2 = range.duplicate(); range.collapse(start); var around = range.parentElement(); if (around && isAncestor(container, around)) { // Only use this node if the selection is not at its start. range2.moveToElementText(around); if (range.compareEndPoints("StartToStart", range2) == 1) return topLevelNodeAt(around, container); } // Move the start of a range to the start of a node, // compensating for the fact that you can't call // moveToElementText with text nodes. function moveToNodeStart(range, node) { if (node.nodeType == 3) { var count = 0, cur = node.previousSibling; while (cur && cur.nodeType == 3) { count += cur.nodeValue.length; cur = cur.previousSibling; } if (cur) { try{range.moveToElementText(cur);} catch(e){return false;} range.collapse(false); } else range.moveToElementText(node.parentNode); if (count) range.move("character", count); } else { try{range.moveToElementText(node);} catch(e){return false;} } return true; } // Do a binary search through the container object, comparing // the start of each node to the selection var start = 0, end = container.childNodes.length - 1; while (start < end) { var middle = Math.ceil((end + start) / 2), node = container.childNodes[middle]; if (!node) return false; // Don't ask. IE6 manages this sometimes. if (!moveToNodeStart(range2, node)) return false; if (range.compareEndPoints("StartToStart", range2) == 1) start = middle; else end = middle - 1; } if (start == 0) { var test1 = selRange(), test2 = test1.duplicate(); try { test2.moveToElementText(container); } catch(exception) { return null; } if (test1.compareEndPoints("StartToStart", test2) == 0) return null; } return container.childNodes[start] || null; }; // Place the cursor after this.start. This is only useful when // manually moving the cursor instead of restoring it to its old // position. select.focusAfterNode = function(node, container) { var range = document.body.createTextRange(); range.moveToElementText(node || container); range.collapse(!node); range.select(); }; select.somethingSelected = function() { var range = selRange(); return range && (range.text != ""); }; function insertAtCursor(html) { var range = selRange(); if (range) { range.pasteHTML(html); range.collapse(false); range.select(); } } // Used to normalize the effect of the enter key, since browsers // do widely different things when pressing enter in designMode. select.insertNewlineAtCursor = function() { insertAtCursor("<br>"); }; select.insertTabAtCursor = function() { insertAtCursor(fourSpaces); }; // Get the BR node at the start of the line on which the cursor // currently is, and the offset into the line. Returns null as // node if cursor is on first line. select.cursorPos = function(container, start) { var range = selRange(); if (!range) return null; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; var range2 = range.duplicate(); range.collapse(start); if (topNode) { range2.moveToElementText(topNode); range2.collapse(false); } else { // When nothing is selected, we can get all kinds of funky errors here. try { range2.moveToElementText(container); } catch (e) { return null; } range2.collapse(true); } range.setEndPoint("StartToStart", range2); return {node: topNode, offset: range.text.length}; }; select.setCursorPos = function(container, from, to) { function rangeAt(pos) { var range = document.body.createTextRange(); if (!pos.node) { range.moveToElementText(container); range.collapse(true); } else { range.moveToElementText(pos.node); range.collapse(false); } range.move("character", pos.offset); return range; } var range = rangeAt(from); if (to && to != from) range.setEndPoint("EndToEnd", rangeAt(to)); range.select(); } // Some hacks for storing and re-storing the selection when the editor loses and regains focus. select.getBookmark = function (container) { var from = select.cursorPos(container, true), to = select.cursorPos(container, false); if (from && to) return {from: from, to: to}; }; // Restore a stored selection. select.setBookmark = function(container, mark) { if (!mark) return; select.setCursorPos(container, mark.from, mark.to); }; } // W3C model else { // Find the node right at the cursor, not one of its // ancestors with a suitable offset. This goes down the DOM tree // until a 'leaf' is reached (or is it *up* the DOM tree?). function innerNode(node, offset) { while (node.nodeType != 3 && !isBR(node)) { var newNode = node.childNodes[offset] || node.nextSibling; offset = 0; while (!newNode && node.parentNode) { node = node.parentNode; newNode = node.nextSibling; } node = newNode; if (!newNode) break; } return {node: node, offset: offset}; } // Store start and end nodes, and offsets within these, and refer // back to the selection object from those nodes, so that this // object can be updated when the nodes are replaced before the // selection is restored. select.markSelection = function () { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return (currentSelection = null); var range = selection.getRangeAt(0); currentSelection = { start: innerNode(range.startContainer, range.startOffset), end: innerNode(range.endContainer, range.endOffset), changed: false }; }; select.selectMarked = function () { var cs = currentSelection; // on webkit-based browsers, it is apparently possible that the // selection gets reset even when a node that is not one of the // endpoints get messed with. the most common situation where // this occurs is when a selection is deleted or overwitten. we // check for that here. function focusIssue() { if (cs.start.node == cs.end.node && cs.start.offset == cs.end.offset) { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return true; var range = selection.getRangeAt(0), point = innerNode(range.startContainer, range.startOffset); return cs.start.node != point.node || cs.start.offset != point.offset; } } if (!cs || !(cs.changed || (webkit && focusIssue()))) return; var range = document.createRange(); function setPoint(point, which) { if (point.node) { // Some magic to generalize the setting of the start and end // of a range. if (point.offset == 0) range["set" + which + "Before"](point.node); else range["set" + which](point.node, point.offset); } else { range.setStartAfter(document.body.lastChild || document.body); } } setPoint(cs.end, "End"); setPoint(cs.start, "Start"); selectRange(range); }; // Helper for selecting a range object. function selectRange(range) { var selection = window.getSelection(); if (!selection) return; selection.removeAllRanges(); selection.addRange(range); } function selectionRange() { var selection = window.getSelection(); if (!selection || selection.rangeCount == 0) return false; else return selection.getRangeAt(0); } // Finding the top-level node at the cursor in the W3C is, as you // can see, quite an involved process. select.selectionTopNode = function(container, start) { var range = selectionRange(); if (!range) return false; var node = start ? range.startContainer : range.endContainer; var offset = start ? range.startOffset : range.endOffset; // Work around (yet another) bug in Opera's selection model. if (window.opera && !start && range.endContainer == container && range.endOffset == range.startOffset + 1 && container.childNodes[range.startOffset] && isBR(container.childNodes[range.startOffset])) offset--; // For text nodes, we look at the node itself if the cursor is // inside, or at the node before it if the cursor is at the // start. if (node.nodeType == 3){ if (offset > 0) return topLevelNodeAt(node, container); else return topLevelNodeBefore(node, container); } // Occasionally, browsers will return the HTML node as // selection. If the offset is 0, we take the start of the frame // ('after null'), otherwise, we take the last node. else if (node.nodeName.toUpperCase() == "HTML") { return (offset == 1 ? null : container.lastChild); } // If the given node is our 'container', we just look up the // correct node by using the offset. else if (node == container) { return (offset == 0) ? null : node.childNodes[offset - 1]; } // In any other case, we have a regular node. If the cursor is // at the end of the node, we use the node itself, if it is at // the start, we use the node before it, and in any other // case, we look up the child before the cursor and use that. else { if (offset == node.childNodes.length) return topLevelNodeAt(node, container); else if (offset == 0) return topLevelNodeBefore(node, container); else return topLevelNodeAt(node.childNodes[offset - 1], container); } }; select.focusAfterNode = function(node, container) { var range = document.createRange(); range.setStartBefore(container.firstChild || container); // In Opera, setting the end of a range at the end of a line // (before a BR) will cause the cursor to appear on the next // line, so we set the end inside of the start node when // possible. if (node && !node.firstChild) range.setEndAfter(node); else if (node) range.setEnd(node, node.childNodes.length); else range.setEndBefore(container.firstChild || container); range.collapse(false); selectRange(range); }; select.somethingSelected = function() { var range = selectionRange(); return range && !range.collapsed; }; select.offsetInNode = function(node) { var range = selectionRange(); if (!range) return 0; range = range.cloneRange(); range.setStartBefore(node); return range.toString().length; }; select.insertNodeAtCursor = function(node) { var range = selectionRange(); if (!range) return; range.deleteContents(); range.insertNode(node); webkitLastLineHack(document.body); // work around weirdness where Opera will magically insert a new // BR node when a BR node inside a span is moved around. makes // sure the BR ends up outside of spans. if (window.opera && isBR(node) && isSpan(node.parentNode)) { var next = node.nextSibling, p = node.parentNode, outer = p.parentNode; outer.insertBefore(node, p.nextSibling); var textAfter = ""; for (; next && next.nodeType == 3; next = next.nextSibling) { textAfter += next.nodeValue; removeElement(next); } outer.insertBefore(makePartSpan(textAfter, document), node.nextSibling); } range = document.createRange(); range.selectNode(node); range.collapse(false); selectRange(range); } select.insertNewlineAtCursor = function() { select.insertNodeAtCursor(document.createElement("BR")); }; select.insertTabAtCursor = function() { select.insertNodeAtCursor(document.createTextNode(fourSpaces)); }; select.cursorPos = function(container, start) { var range = selectionRange(); if (!range) return; var topNode = select.selectionTopNode(container, start); while (topNode && !isBR(topNode)) topNode = topNode.previousSibling; range = range.cloneRange(); range.collapse(start); if (topNode) range.setStartAfter(topNode); else range.setStartBefore(container); var text = range.toString(); return {node: topNode, offset: text.length}; }; select.setCursorPos = function(container, from, to) { var range = document.createRange(); function setPoint(node, offset, side) { if (offset == 0 && node && !node.nextSibling) { range["set" + side + "After"](node); return true; } if (!node) node = container.firstChild; else node = node.nextSibling; if (!node) return; if (offset == 0) { range["set" + side + "Before"](node); return true; } var backlog = [] function decompose(node) { if (node.nodeType == 3) backlog.push(node); else forEach(node.childNodes, decompose); } while (true) { while (node && !backlog.length) { decompose(node); node = node.nextSibling; } var cur = backlog.shift(); if (!cur) return false; var length = cur.nodeValue.length; if (length >= offset) { range["set" + side](cur, offset); return true; } offset -= length; } } to = to || from; if (setPoint(to.node, to.offset, "End") && setPoint(from.node, from.offset, "Start")) selectRange(range); }; } })();
JavaScript
/* Simple parser for CSS */ var CSSParser = Editor.Parser = (function() { var tokenizeCSS = (function() { function normal(source, setState) { var ch = source.next(); if (ch == "@") { source.nextWhileMatches(/\w/); return "css-at"; } else if (ch == "/" && source.equals("*")) { setState(inCComment); return null; } else if (ch == "<" && source.equals("!")) { setState(inSGMLComment); return null; } else if (ch == "=") { return "css-compare"; } else if (source.equals("=") && (ch == "~" || ch == "|")) { source.next(); return "css-compare"; } else if (ch == "\"" || ch == "'") { setState(inString(ch)); return null; } else if (ch == "#") { source.nextWhileMatches(/\w/); return "css-hash"; } else if (ch == "!") { source.nextWhileMatches(/[ \t]/); source.nextWhileMatches(/\w/); return "css-important"; } else if (/\d/.test(ch)) { source.nextWhileMatches(/[\w.%]/); return "css-unit"; } else if (/[,.+>*\/]/.test(ch)) { return "css-select-op"; } else if (/[;{}:\[\]]/.test(ch)) { return "css-punctuation"; } else { source.nextWhileMatches(/[\w\\\-_]/); return "css-identifier"; } } function inCComment(source, setState) { var maybeEnd = false; while (!source.endOfLine()) { var ch = source.next(); if (maybeEnd && ch == "/") { setState(normal); break; } maybeEnd = (ch == "*"); } return "css-comment"; } function inSGMLComment(source, setState) { var dashes = 0; while (!source.endOfLine()) { var ch = source.next(); if (dashes >= 2 && ch == ">") { setState(normal); break; } dashes = (ch == "-") ? dashes + 1 : 0; } return "css-comment"; } function inString(quote) { return function(source, setState) { var escaped = false; while (!source.endOfLine()) { var ch = source.next(); if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) setState(normal); return "css-string"; }; } return function(source, startState) { return tokenizer(source, startState || normal); }; })(); function indentCSS(inBraces, inRule, base) { return function(nextChars) { if (!inBraces || /^\}/.test(nextChars)) return base; else if (inRule) return base + indentUnit * 2; else return base + indentUnit; }; } // This is a very simplistic parser -- since CSS does not really // nest, it works acceptably well, but some nicer colouroing could // be provided with a more complicated parser. function parseCSS(source, basecolumn) { basecolumn = basecolumn || 0; var tokens = tokenizeCSS(source); var inBraces = false, inRule = false, inDecl = false;; var iter = { next: function() { var token = tokens.next(), style = token.style, content = token.content; if (style == "css-hash") style = token.style = inRule ? "css-colorcode" : "css-identifier"; if (style == "css-identifier") { if (inRule) token.style = "css-value"; else if (!inBraces && !inDecl) token.style = "css-selector"; } if (content == "\n") token.indentation = indentCSS(inBraces, inRule, basecolumn); if (content == "{" && inDecl == "@media") inDecl = false; else if (content == "{") inBraces = true; else if (content == "}") inBraces = inRule = inDecl = false; else if (content == ";") inRule = inDecl = false; else if (inBraces && style != "css-comment" && style != "whitespace") inRule = true; else if (!inBraces && style == "css-at") inDecl = content; return token; }, copy: function() { var _inBraces = inBraces, _inRule = inRule, _tokenState = tokens.state; return function(source) { tokens = tokenizeCSS(source, _tokenState); inBraces = _inBraces; inRule = _inRule; return iter; }; } }; return iter; } return {make: parseCSS, electricChars: "}"}; })();
JavaScript
// A framework for simple tokenizers. Takes care of newlines and // white-space, and of getting the text from the source stream into // the token object. A state is a function of two arguments -- a // string stream and a setState function. The second can be used to // change the tokenizer's state, and can be ignored for stateless // tokenizers. This function should advance the stream over a token // and return a string or object containing information about the next // token, or null to pass and have the (new) state be called to finish // the token. When a string is given, it is wrapped in a {style, type} // object. In the resulting object, the characters consumed are stored // under the content property. Any whitespace following them is also // automatically consumed, and added to the value property. (Thus, // content is the actual meaningful part of the token, while value // contains all the text it spans.) function tokenizer(source, state) { // Newlines are always a separate token. function isWhiteSpace(ch) { // The messy regexp is because IE's regexp matcher is of the // opinion that non-breaking spaces are no whitespace. return ch != "\n" && /^[\s\u00a0]*$/.test(ch); } var tokenizer = { state: state, take: function(type) { if (typeof(type) == "string") type = {style: type, type: type}; type.content = (type.content || "") + source.get(); if (!/\n$/.test(type.content)) source.nextWhile(isWhiteSpace); type.value = type.content + source.get(); return type; }, next: function () { if (!source.more()) throw StopIteration; var type; if (source.equals("\n")) { source.next(); return this.take("whitespace"); } if (source.applies(isWhiteSpace)) type = "whitespace"; else while (!type) type = this.state(source, function(s) {tokenizer.state = s;}); return this.take(type); } }; return tokenizer; }
JavaScript
var HTMLMixedParser = Editor.Parser = (function() { // tags that trigger seperate parsers var triggers = { "script": "JSParser", "style": "CSSParser" }; function checkDependencies() { var parsers = ['XMLParser']; for (var p in triggers) parsers.push(triggers[p]); for (var i in parsers) { if (!window[parsers[i]]) throw new Error(parsers[i] + " parser must be loaded for HTML mixed mode to work."); } XMLParser.configure({useHTMLKludges: true}); } function parseMixed(stream) { checkDependencies(); var htmlParser = XMLParser.make(stream), localParser = null, inTag = false; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.content == ">") { if (triggers[inTag]) { var parser = window[triggers[inTag]]; iter.next = local(parser, "</" + inTag); } inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { localParser = null; iter.next = top; return top(); } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); }; } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); iter.next = _next; inTag = _inTag; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(obj) { if (obj.triggers) triggers = obj.triggers; } }; })();
JavaScript
/* Demonstration of embedding CodeMirror in a bigger application. The * interface defined here is a mess of prompts and confirms, and * should probably not be used in a real project. */ function MirrorFrame(place, options) { this.home = document.createElement("div"); if (place.appendChild) place.appendChild(this.home); else place(this.home); var self = this; function makeButton(name, action) { var button = document.createElement("input"); button.type = "button"; button.value = name; self.home.appendChild(button); button.onclick = function(){self[action].call(self);}; } makeButton("Search", "search"); makeButton("Replace", "replace"); makeButton("Current line", "line"); makeButton("Jump to line", "jump"); makeButton("Insert constructor", "macro"); makeButton("Indent all", "reindent"); this.mirror = new CodeMirror(this.home, options); } MirrorFrame.prototype = { search: function() { var text = prompt("Enter search term:", ""); if (!text) return; var first = true; do { var cursor = this.mirror.getSearchCursor(text, first); first = false; while (cursor.findNext()) { cursor.select(); if (!confirm("Search again?")) return; } } while (confirm("End of document reached. Start over?")); }, replace: function() { // This is a replace-all, but it is possible to implement a // prompting replace. var from = prompt("Enter search string:", ""), to; if (from) to = prompt("What should it be replaced with?", ""); if (to == null) return; var cursor = this.mirror.getSearchCursor(from, false); while (cursor.findNext()) cursor.replace(to); }, jump: function() { var line = prompt("Jump to line:", ""); if (line && !isNaN(Number(line))) this.mirror.jumpToLine(Number(line)); }, line: function() { alert("The cursor is currently at line " + this.mirror.currentLine()); this.mirror.focus(); }, macro: function() { var name = prompt("Name your constructor:", ""); if (name) this.mirror.replaceSelection("function " + name + "() {\n \n}\n\n" + name + ".prototype = {\n \n};\n"); }, reindent: function() { this.mirror.reindent(); } };
JavaScript
/* The Editor object manages the content of the editable frame. It * catches events, colours nodes, and indents lines. This file also * holds some functions for transforming arbitrary DOM structures into * plain sequences of <span> and <br> elements */ var internetExplorer = document.selection && window.ActiveXObject && /MSIE/.test(navigator.userAgent); var webkit = /AppleWebKit/.test(navigator.userAgent); var safari = /Apple Computer, Inc/.test(navigator.vendor); var gecko = navigator.userAgent.match(/gecko\/(\d{8})/i); if (gecko) gecko = Number(gecko[1]); var mac = /Mac/.test(navigator.platform); // TODO this is related to the backspace-at-end-of-line bug. Remove // this if Opera gets their act together, make the version check more // broad if they don't. var brokenOpera = window.opera && /Version\/10.[56]/.test(navigator.userAgent); // TODO remove this once WebKit 533 becomes less common. var slowWebkit = /AppleWebKit\/533/.test(navigator.userAgent); // Make sure a string does not contain two consecutive 'collapseable' // whitespace characters. function makeWhiteSpace(n) { var buffer = [], nb = true; for (; n > 0; n--) { buffer.push((nb || n == 1) ? nbsp : " "); nb ^= true; } return buffer.join(""); } // Create a set of white-space characters that will not be collapsed // by the browser, but will not break text-wrapping either. function fixSpaces(string) { if (string.charAt(0) == " ") string = nbsp + string.slice(1); return string.replace(/\t/g, function() {return makeWhiteSpace(indentUnit);}) .replace(/[ \u00a0]{2,}/g, function(s) {return makeWhiteSpace(s.length);}); } function cleanText(text) { return text.replace(/\u00a0/g, " ").replace(/\u200b/g, ""); } // Create a SPAN node with the expected properties for document part // spans. function makePartSpan(value) { var text = value; if (value.nodeType == 3) text = value.nodeValue; else value = document.createTextNode(text); var span = document.createElement("span"); span.isPart = true; span.appendChild(value); span.currentText = text; return span; } function alwaysZero() {return 0;} // On webkit, when the last BR of the document does not have text // behind it, the cursor can not be put on the line after it. This // makes pressing enter at the end of the document occasionally do // nothing (or at least seem to do nothing). To work around it, this // function makes sure the document ends with a span containing a // zero-width space character. The traverseDOM iterator filters such // character out again, so that the parsers won't see them. This // function is called from a few strategic places to make sure the // zwsp is restored after the highlighting process eats it. var webkitLastLineHack = webkit ? function(container) { var last = container.lastChild; if (!last || !last.hackBR) { var br = document.createElement("br"); br.hackBR = true; container.appendChild(br); } } : function() {}; function asEditorLines(string) { var tab = makeWhiteSpace(indentUnit); return map(string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n").split("\n"), fixSpaces); } var Editor = (function(){ // The HTML elements whose content should be suffixed by a newline // when converting them to flat text. var newlineElements = {"P": true, "DIV": true, "LI": true}; // Helper function for traverseDOM. Flattens an arbitrary DOM node // into an array of textnodes and <br> tags. function simplifyDOM(root, atEnd) { var result = []; var leaving = true; function simplifyNode(node, top) { if (node.nodeType == 3) { var text = node.nodeValue = fixSpaces(node.nodeValue.replace(/[\r\u200b]/g, "").replace(/\n/g, " ")); if (text.length) leaving = false; result.push(node); } else if (isBR(node) && node.childNodes.length == 0) { leaving = true; result.push(node); } else { for (var n = node.firstChild; n; n = n.nextSibling) simplifyNode(n); if (!leaving && newlineElements.hasOwnProperty(node.nodeName.toUpperCase())) { leaving = true; if (!atEnd || !top) result.push(document.createElement("br")); } } } simplifyNode(root, true); return result; } // Creates a MochiKit-style iterator that goes over a series of DOM // nodes. The values it yields are strings, the textual content of // the nodes. It makes sure that all nodes up to and including the // one whose text is being yielded have been 'normalized' to be just // <span> and <br> elements. function traverseDOM(start){ var nodeQueue = []; // Create a function that can be used to insert nodes after the // one given as argument. function pointAt(node){ var parent = node.parentNode; var next = node.nextSibling; return function(newnode) { parent.insertBefore(newnode, next); }; } var point = null; // This an Opera-specific hack -- always insert an empty span // between two BRs, because Opera's cursor code gets terribly // confused when the cursor is between two BRs. var afterBR = true; // Insert a normalized node at the current point. If it is a text // node, wrap it in a <span>, and give that span a currentText // property -- this is used to cache the nodeValue, because // directly accessing nodeValue is horribly slow on some browsers. // The dirty property is used by the highlighter to determine // which parts of the document have to be re-highlighted. function insertPart(part){ var text = "\n"; if (part.nodeType == 3) { select.snapshotChanged(); part = makePartSpan(part); text = part.currentText; afterBR = false; } else { if (afterBR && window.opera) point(makePartSpan("")); afterBR = true; } part.dirty = true; nodeQueue.push(part); point(part); return text; } // Extract the text and newlines from a DOM node, insert them into // the document, and return the textual content. Used to replace // non-normalized nodes. function writeNode(node, end) { var simplified = simplifyDOM(node, end); for (var i = 0; i < simplified.length; i++) simplified[i] = insertPart(simplified[i]); return simplified.join(""); } // Check whether a node is a normalized <span> element. function partNode(node){ if (node.isPart && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { var text = node.firstChild.nodeValue; node.dirty = node.dirty || text != node.currentText; node.currentText = text; return !/[\n\t\r]/.test(node.currentText); } return false; } // Advance to next node, return string for current node. function next() { if (!start) throw StopIteration; var node = start; start = node.nextSibling; if (partNode(node)){ nodeQueue.push(node); afterBR = false; return node.currentText; } else if (isBR(node)) { if (afterBR && window.opera) node.parentNode.insertBefore(makePartSpan(""), node); nodeQueue.push(node); afterBR = true; return "\n"; } else { var end = !node.nextSibling; point = pointAt(node); removeElement(node); return writeNode(node, end); } } // MochiKit iterators are objects with a next function that // returns the next value or throws StopIteration when there are // no more values. return {next: next, nodes: nodeQueue}; } // Determine the text size of a processed node. function nodeSize(node) { return isBR(node) ? 1 : node.currentText.length; } // Search backwards through the top-level nodes until the next BR or // the start of the frame. function startOfLine(node) { while (node && !isBR(node)) node = node.previousSibling; return node; } function endOfLine(node, container) { if (!node) node = container.firstChild; else if (isBR(node)) node = node.nextSibling; while (node && !isBR(node)) node = node.nextSibling; return node; } function time() {return new Date().getTime();} // Client interface for searching the content of the editor. Create // these by calling CodeMirror.getSearchCursor. To use, call // findNext on the resulting object -- this returns a boolean // indicating whether anything was found, and can be called again to // skip to the next find. Use the select and replace methods to // actually do something with the found locations. function SearchCursor(editor, pattern, from, caseFold) { this.editor = editor; this.history = editor.history; this.history.commit(); this.valid = !!pattern; this.atOccurrence = false; if (caseFold == undefined) caseFold = typeof pattern == "string" && pattern == pattern.toLowerCase(); function getText(node){ var line = cleanText(editor.history.textAfter(node)); return (caseFold ? line.toLowerCase() : line); } var topPos = {node: null, offset: 0}, self = this; if (from && typeof from == "object" && typeof from.character == "number") { editor.checkLine(from.line); var pos = {node: from.line, offset: from.character}; this.pos = {from: pos, to: pos}; } else if (from) { this.pos = {from: select.cursorPos(editor.container, true) || topPos, to: select.cursorPos(editor.container, false) || topPos}; } else { this.pos = {from: topPos, to: topPos}; } if (typeof pattern != "string") { // Regexp match this.matches = function(reverse, node, offset) { if (reverse) { var line = getText(node).slice(0, offset), match = line.match(pattern), start = 0; while (match) { var ind = line.indexOf(match[0]); start += ind; line = line.slice(ind + 1); var newmatch = line.match(pattern); if (newmatch) match = newmatch; else break; } } else { var line = getText(node).slice(offset), match = line.match(pattern), start = match && offset + line.indexOf(match[0]); } if (match) { self.currentMatch = match; return {from: {node: node, offset: start}, to: {node: node, offset: start + match[0].length}}; } }; return; } if (caseFold) pattern = pattern.toLowerCase(); // Create a matcher function based on the kind of string we have. var target = pattern.split("\n"); this.matches = (target.length == 1) ? // For one-line strings, searching can be done simply by calling // indexOf or lastIndexOf on the current line. function(reverse, node, offset) { var line = getText(node), len = pattern.length, match; if (reverse ? (offset >= len && (match = line.lastIndexOf(pattern, offset - len)) != -1) : (match = line.indexOf(pattern, offset)) != -1) return {from: {node: node, offset: match}, to: {node: node, offset: match + len}}; } : // Multi-line strings require internal iteration over lines, and // some clunky checks to make sure the first match ends at the // end of the line and the last match starts at the start. function(reverse, node, offset) { var idx = (reverse ? target.length - 1 : 0), match = target[idx], line = getText(node); var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match)); if (reverse ? offsetA >= offset || offsetA != match.length : offsetA <= offset || offsetA != line.length - match.length) return; var pos = node; while (true) { if (reverse && !pos) return; pos = (reverse ? this.history.nodeBefore(pos) : this.history.nodeAfter(pos) ); if (!reverse && !pos) return; line = getText(pos); match = target[reverse ? --idx : ++idx]; if (idx > 0 && idx < target.length - 1) { if (line != match) return; else continue; } var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length); if (reverse ? offsetB != line.length - match.length : offsetB != match.length) return; return {from: {node: reverse ? pos : node, offset: reverse ? offsetB : offsetA}, to: {node: reverse ? node : pos, offset: reverse ? offsetA : offsetB}}; } }; } SearchCursor.prototype = { findNext: function() {return this.find(false);}, findPrevious: function() {return this.find(true);}, find: function(reverse) { if (!this.valid) return false; var self = this, pos = reverse ? this.pos.from : this.pos.to, node = pos.node, offset = pos.offset; // Reset the cursor if the current line is no longer in the DOM tree. if (node && !node.parentNode) { node = null; offset = 0; } function savePosAndFail() { var pos = {node: node, offset: offset}; self.pos = {from: pos, to: pos}; self.atOccurrence = false; return false; } while (true) { if (this.pos = this.matches(reverse, node, offset)) { this.atOccurrence = true; return true; } if (reverse) { if (!node) return savePosAndFail(); node = this.history.nodeBefore(node); offset = this.history.textAfter(node).length; } else { var next = this.history.nodeAfter(node); if (!next) { offset = this.history.textAfter(node).length; return savePosAndFail(); } node = next; offset = 0; } } }, select: function() { if (this.atOccurrence) { select.setCursorPos(this.editor.container, this.pos.from, this.pos.to); select.scrollToCursor(this.editor.container); } }, replace: function(string) { if (this.atOccurrence) { var fragments = this.currentMatch; if (fragments) string = string.replace(/\\(\d)/, function(m, i){return fragments[i];}); var end = this.editor.replaceRange(this.pos.from, this.pos.to, string); this.pos.to = end; this.atOccurrence = false; } }, position: function() { if (this.atOccurrence) return {line: this.pos.from.node, character: this.pos.from.offset}; } }; // The Editor object is the main inside-the-iframe interface. function Editor(options) { this.options = options; window.indentUnit = options.indentUnit; var container = this.container = document.body; this.history = new UndoHistory(container, options.undoDepth, options.undoDelay, this); var self = this; if (!Editor.Parser) throw "No parser loaded."; if (options.parserConfig && Editor.Parser.configure) Editor.Parser.configure(options.parserConfig); if (!options.readOnly && !internetExplorer) select.setCursorPos(container, {node: null, offset: 0}); this.dirty = []; this.importCode(options.content || ""); this.history.onChange = options.onChange; if (!options.readOnly) { if (options.continuousScanning !== false) { this.scanner = this.documentScanner(options.passTime); this.delayScanning(); } function setEditable() { // Use contentEditable instead of designMode on IE, since designMode frames // can not run any scripts. It would be nice if we could use contentEditable // everywhere, but it is significantly flakier than designMode on every // single non-IE browser. if (document.body.contentEditable != undefined && internetExplorer) document.body.contentEditable = "true"; else document.designMode = "on"; // Work around issue where you have to click on the actual // body of the document to focus it in IE, making focusing // hard when the document is small. if (internetExplorer && options.height != "dynamic") document.body.style.minHeight = ( window.frameElement.clientHeight - 2 * document.body.offsetTop - 5) + "px"; document.documentElement.style.borderWidth = "0"; if (!options.textWrapping) container.style.whiteSpace = "nowrap"; } // If setting the frame editable fails, try again when the user // focus it (happens when the frame is not visible on // initialisation, in Firefox). try { setEditable(); } catch(e) { var focusEvent = addEventHandler(document, "focus", function() { focusEvent(); setEditable(); }, true); } addEventHandler(document, "keydown", method(this, "keyDown")); addEventHandler(document, "keypress", method(this, "keyPress")); addEventHandler(document, "keyup", method(this, "keyUp")); function cursorActivity() {self.cursorActivity(false);} addEventHandler(internetExplorer ? document.body : window, "mouseup", cursorActivity); addEventHandler(document.body, "cut", cursorActivity); // workaround for a gecko bug [?] where going forward and then // back again breaks designmode (no more cursor) if (gecko) addEventHandler(window, "pagehide", function(){self.unloaded = true;}); addEventHandler(document.body, "paste", function(event) { cursorActivity(); var text = null; try { var clipboardData = event.clipboardData || window.clipboardData; if (clipboardData) text = clipboardData.getData('Text'); } catch(e) {} if (text !== null) { event.stop(); self.replaceSelection(text); select.scrollToCursor(self.container); } }); if (this.options.autoMatchParens) addEventHandler(document.body, "click", method(this, "scheduleParenHighlight")); } else if (!options.textWrapping) { container.style.whiteSpace = "nowrap"; } } function isSafeKey(code) { return (code >= 16 && code <= 18) || // shift, control, alt (code >= 33 && code <= 40); // arrows, home, end } Editor.prototype = { // Import a piece of code into the editor. importCode: function(code) { var lines = asEditorLines(code), chunk = 1000; if (!this.options.incrementalLoading || lines.length < chunk) { this.history.push(null, null, lines); this.history.reset(); } else { var cur = 0, self = this; function addChunk() { var chunklines = lines.slice(cur, cur + chunk); chunklines.push(""); self.history.push(self.history.nodeBefore(null), null, chunklines); self.history.reset(); cur += chunk; if (cur < lines.length) parent.setTimeout(addChunk, 1000); } addChunk(); } }, // Extract the code from the editor. getCode: function() { if (!this.container.firstChild) return ""; var accum = []; select.markSelection(); forEach(traverseDOM(this.container.firstChild), method(accum, "push")); select.selectMarked(); // On webkit, don't count last (empty) line if the webkitLastLineHack BR is present if (webkit && this.container.lastChild.hackBR) accum.pop(); webkitLastLineHack(this.container); return cleanText(accum.join("")); }, checkLine: function(node) { if (node === false || !(node == null || node.parentNode == this.container || node.hackBR)) throw parent.CodeMirror.InvalidLineHandle; }, cursorPosition: function(start) { if (start == null) start = true; var pos = select.cursorPos(this.container, start); if (pos) return {line: pos.node, character: pos.offset}; else return {line: null, character: 0}; }, firstLine: function() { return null; }, lastLine: function() { var last = this.container.lastChild; if (last) last = startOfLine(last); if (last && last.hackBR) last = startOfLine(last.previousSibling); return last; }, nextLine: function(line) { this.checkLine(line); var end = endOfLine(line, this.container); if (!end || end.hackBR) return false; else return end; }, prevLine: function(line) { this.checkLine(line); if (line == null) return false; return startOfLine(line.previousSibling); }, visibleLineCount: function() { var line = this.container.firstChild; while (line && isBR(line)) line = line.nextSibling; // BR heights are unreliable if (!line) return false; var innerHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight); return Math.floor(innerHeight / line.offsetHeight); }, selectLines: function(startLine, startOffset, endLine, endOffset) { this.checkLine(startLine); var start = {node: startLine, offset: startOffset}, end = null; if (endOffset !== undefined) { this.checkLine(endLine); end = {node: endLine, offset: endOffset}; } select.setCursorPos(this.container, start, end); select.scrollToCursor(this.container); }, lineContent: function(line) { var accum = []; for (line = line ? line.nextSibling : this.container.firstChild; line && !isBR(line); line = line.nextSibling) accum.push(nodeText(line)); return cleanText(accum.join("")); }, setLineContent: function(line, content) { this.history.commit(); this.replaceRange({node: line, offset: 0}, {node: line, offset: this.history.textAfter(line).length}, content); this.addDirtyNode(line); this.scheduleHighlight(); }, removeLine: function(line) { var node = line ? line.nextSibling : this.container.firstChild; while (node) { var next = node.nextSibling; removeElement(node); if (isBR(node)) break; node = next; } this.addDirtyNode(line); this.scheduleHighlight(); }, insertIntoLine: function(line, position, content) { var before = null; if (position == "end") { before = endOfLine(line, this.container); } else { for (var cur = line ? line.nextSibling : this.container.firstChild; cur; cur = cur.nextSibling) { if (position == 0) { before = cur; break; } var text = nodeText(cur); if (text.length > position) { before = cur.nextSibling; content = text.slice(0, position) + content + text.slice(position); removeElement(cur); break; } position -= text.length; } } var lines = asEditorLines(content); for (var i = 0; i < lines.length; i++) { if (i > 0) this.container.insertBefore(document.createElement("BR"), before); this.container.insertBefore(makePartSpan(lines[i]), before); } this.addDirtyNode(line); this.scheduleHighlight(); }, // Retrieve the selected text. selectedText: function() { var h = this.history; h.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return ""; if (start.node == end.node) return h.textAfter(start.node).slice(start.offset, end.offset); var text = [h.textAfter(start.node).slice(start.offset)]; for (var pos = h.nodeAfter(start.node); pos != end.node; pos = h.nodeAfter(pos)) text.push(h.textAfter(pos)); text.push(h.textAfter(end.node).slice(0, end.offset)); return cleanText(text.join("\n")); }, // Replace the selection with another piece of text. replaceSelection: function(text) { this.history.commit(); var start = select.cursorPos(this.container, true), end = select.cursorPos(this.container, false); if (!start || !end) return; end = this.replaceRange(start, end, text); select.setCursorPos(this.container, end); webkitLastLineHack(this.container); }, cursorCoords: function(start, internal) { var sel = select.cursorPos(this.container, start); if (!sel) return null; var off = sel.offset, node = sel.node, self = this; function measureFromNode(node, xOffset) { var y = -(document.body.scrollTop || document.documentElement.scrollTop || 0), x = -(document.body.scrollLeft || document.documentElement.scrollLeft || 0) + xOffset; forEach([node, internal ? null : window.frameElement], function(n) { while (n) {x += n.offsetLeft; y += n.offsetTop;n = n.offsetParent;} }); return {x: x, y: y, yBot: y + node.offsetHeight}; } function withTempNode(text, f) { var node = document.createElement("SPAN"); node.appendChild(document.createTextNode(text)); try {return f(node);} finally {if (node.parentNode) node.parentNode.removeChild(node);} } while (off) { node = node ? node.nextSibling : this.container.firstChild; var txt = nodeText(node); if (off < txt.length) return withTempNode(txt.substr(0, off), function(tmp) { tmp.style.position = "absolute"; tmp.style.visibility = "hidden"; tmp.className = node.className; self.container.appendChild(tmp); return measureFromNode(node, tmp.offsetWidth); }); off -= txt.length; } if (node && isSpan(node)) return measureFromNode(node, node.offsetWidth); else if (node && node.nextSibling && isSpan(node.nextSibling)) return measureFromNode(node.nextSibling, 0); else return withTempNode("\u200b", function(tmp) { if (node) node.parentNode.insertBefore(tmp, node.nextSibling); else self.container.insertBefore(tmp, self.container.firstChild); return measureFromNode(tmp, 0); }); }, reroutePasteEvent: function() { if (this.capturingPaste || window.opera || (gecko && gecko >= 20101026)) return; this.capturingPaste = true; var te = window.frameElement.CodeMirror.textareaHack; var coords = this.cursorCoords(true, true); te.style.top = coords.y + "px"; if (internetExplorer) { var snapshot = select.getBookmark(this.container); if (snapshot) this.selectionSnapshot = snapshot; } parent.focus(); te.value = ""; te.focus(); var self = this; parent.setTimeout(function() { self.capturingPaste = false; window.focus(); if (self.selectionSnapshot) // IE hack window.select.setBookmark(self.container, self.selectionSnapshot); var text = te.value; if (text) { self.replaceSelection(text); select.scrollToCursor(self.container); } }, 10); }, replaceRange: function(from, to, text) { var lines = asEditorLines(text); lines[0] = this.history.textAfter(from.node).slice(0, from.offset) + lines[0]; var lastLine = lines[lines.length - 1]; lines[lines.length - 1] = lastLine + this.history.textAfter(to.node).slice(to.offset); var end = this.history.nodeAfter(to.node); this.history.push(from.node, end, lines); return {node: this.history.nodeBefore(end), offset: lastLine.length}; }, getSearchCursor: function(string, fromCursor, caseFold) { return new SearchCursor(this, string, fromCursor, caseFold); }, // Re-indent the whole buffer reindent: function() { if (this.container.firstChild) this.indentRegion(null, this.container.lastChild); }, reindentSelection: function(direction) { if (!select.somethingSelected()) { this.indentAtCursor(direction); } else { var start = select.selectionTopNode(this.container, true), end = select.selectionTopNode(this.container, false); if (start === false || end === false) return; this.indentRegion(start, end, direction); } }, grabKeys: function(eventHandler, filter) { this.frozen = eventHandler; this.keyFilter = filter; }, ungrabKeys: function() { this.frozen = "leave"; }, setParser: function(name, parserConfig) { Editor.Parser = window[name]; parserConfig = parserConfig || this.options.parserConfig; if (parserConfig && Editor.Parser.configure) Editor.Parser.configure(parserConfig); if (this.container.firstChild) { forEach(this.container.childNodes, function(n) { if (n.nodeType != 3) n.dirty = true; }); this.addDirtyNode(this.firstChild); this.scheduleHighlight(); } }, // Intercept enter and tab, and assign their new functions. keyDown: function(event) { if (this.frozen == "leave") {this.frozen = null; this.keyFilter = null;} if (this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode, event))) { event.stop(); this.frozen(event); return; } var code = event.keyCode; // Don't scan when the user is typing. this.delayScanning(); // Schedule a paren-highlight event, if configured. if (this.options.autoMatchParens) this.scheduleParenHighlight(); // The various checks for !altKey are there because AltGr sets both // ctrlKey and altKey to true, and should not be recognised as // Control. if (code == 13) { // enter if (event.ctrlKey && !event.altKey) { this.reparseBuffer(); } else { select.insertNewlineAtCursor(); var mode = this.options.enterMode; if (mode != "flat") this.indentAtCursor(mode == "keep" ? "keep" : undefined); select.scrollToCursor(this.container); } event.stop(); } else if (code == 9 && this.options.tabMode != "default" && !event.ctrlKey) { // tab this.handleTab(!event.shiftKey); event.stop(); } else if (code == 32 && event.shiftKey && this.options.tabMode == "default") { // space this.handleTab(true); event.stop(); } else if (code == 36 && !event.shiftKey && !event.ctrlKey) { // home if (this.home()) event.stop(); } else if (code == 35 && !event.shiftKey && !event.ctrlKey) { // end if (this.end()) event.stop(); } // Only in Firefox is the default behavior for PgUp/PgDn correct. else if (code == 33 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgUp if (this.pageUp()) event.stop(); } else if (code == 34 && !event.shiftKey && !event.ctrlKey && !gecko) { // PgDn if (this.pageDown()) event.stop(); } else if ((code == 219 || code == 221) && event.ctrlKey && !event.altKey) { // [, ] this.highlightParens(event.shiftKey, true); event.stop(); } else if (event.metaKey && !event.shiftKey && (code == 37 || code == 39)) { // Meta-left/right var cursor = select.selectionTopNode(this.container); if (cursor === false || !this.container.firstChild) return; if (code == 37) select.focusAfterNode(startOfLine(cursor), this.container); else { var end = endOfLine(cursor, this.container); select.focusAfterNode(end ? end.previousSibling : this.container.lastChild, this.container); } event.stop(); } else if ((event.ctrlKey || event.metaKey) && !event.altKey) { if ((event.shiftKey && code == 90) || code == 89) { // shift-Z, Y select.scrollToNode(this.history.redo()); event.stop(); } else if (code == 90 || (safari && code == 8)) { // Z, backspace select.scrollToNode(this.history.undo()); event.stop(); } else if (code == 83 && this.options.saveFunction) { // S this.options.saveFunction(); event.stop(); } else if (code == 86 && !mac) { // V this.reroutePasteEvent(); } } }, // Check for characters that should re-indent the current line, // and prevent Opera from handling enter and tab anyway. keyPress: function(event) { var electric = this.options.electricChars && Editor.Parser.electricChars, self = this; // Hack for Opera, and Firefox on OS X, in which stopping a // keydown event does not prevent the associated keypress event // from happening, so we have to cancel enter and tab again // here. if ((this.frozen && (!this.keyFilter || this.keyFilter(event.keyCode || event.code, event))) || event.code == 13 || (event.code == 9 && this.options.tabMode != "default") || (event.code == 32 && event.shiftKey && this.options.tabMode == "default")) event.stop(); else if (mac && (event.ctrlKey || event.metaKey) && event.character == "v") { this.reroutePasteEvent(); } else if (electric && electric.indexOf(event.character) != -1) parent.setTimeout(function(){self.indentAtCursor(null);}, 0); // Work around a bug where pressing backspace at the end of a // line, or delete at the start, often causes the cursor to jump // to the start of the line in Opera 10.60. else if (brokenOpera) { if (event.code == 8) { // backspace var sel = select.selectionTopNode(this.container), self = this, next = sel ? sel.nextSibling : this.container.firstChild; if (sel !== false && next && isBR(next)) parent.setTimeout(function(){ if (select.selectionTopNode(self.container) == next) select.focusAfterNode(next.previousSibling, self.container); }, 20); } else if (event.code == 46) { // delete var sel = select.selectionTopNode(this.container), self = this; if (sel && isBR(sel)) { parent.setTimeout(function(){ if (select.selectionTopNode(self.container) != sel) select.focusAfterNode(sel, self.container); }, 20); } } } // In 533.* WebKit versions, when the document is big, typing // something at the end of a line causes the browser to do some // kind of stupid heavy operation, creating delays of several // seconds before the typed characters appear. This very crude // hack inserts a temporary zero-width space after the cursor to // make it not be at the end of the line. else if (slowWebkit) { var sel = select.selectionTopNode(this.container), next = sel ? sel.nextSibling : this.container.firstChild; // Doesn't work on empty lines, for some reason those always // trigger the delay. if (sel && next && isBR(next) && !isBR(sel)) { var cheat = document.createTextNode("\u200b"); this.container.insertBefore(cheat, next); parent.setTimeout(function() { if (cheat.nodeValue == "\u200b") removeElement(cheat); else cheat.nodeValue = cheat.nodeValue.replace("\u200b", ""); }, 20); } } // Magic incantation that works abound a webkit bug when you // can't type on a blank line following a line that's wider than // the window. if (webkit && !this.options.textWrapping) setTimeout(function () { var node = select.selectionTopNode(self.container, true); if (node && node.nodeType == 3 && node.previousSibling && isBR(node.previousSibling) && node.nextSibling && isBR(node.nextSibling)) node.parentNode.replaceChild(document.createElement("BR"), node.previousSibling); }, 50); }, // Mark the node at the cursor dirty when a non-safe key is // released. keyUp: function(event) { this.cursorActivity(isSafeKey(event.keyCode)); }, // Indent the line following a given <br>, or null for the first // line. If given a <br> element, this must have been highlighted // so that it has an indentation method. Returns the whitespace // element that has been modified or created (if any). indentLineAfter: function(start, direction) { function whiteSpaceAfter(node) { var ws = node ? node.nextSibling : self.container.firstChild; if (!ws || !hasClass(ws, "whitespace")) return null; return ws; } // whiteSpace is the whitespace span at the start of the line, // or null if there is no such node. var self = this, whiteSpace = whiteSpaceAfter(start); var newIndent = 0, curIndent = whiteSpace ? whiteSpace.currentText.length : 0; var firstText = whiteSpace ? whiteSpace.nextSibling : (start ? start.nextSibling : this.container.firstChild); if (direction == "keep") { if (start) { var prevWS = whiteSpaceAfter(startOfLine(start.previousSibling)) if (prevWS) newIndent = prevWS.currentText.length; } } else { // Sometimes the start of the line can influence the correct // indentation, so we retrieve it. var nextChars = (start && firstText && firstText.currentText) ? firstText.currentText : ""; // Ask the lexical context for the correct indentation, and // compute how much this differs from the current indentation. if (direction != null && this.options.tabMode == "shift") newIndent = direction ? curIndent + indentUnit : Math.max(0, curIndent - indentUnit) else if (start) newIndent = start.indentation(nextChars, curIndent, direction, firstText); else if (Editor.Parser.firstIndentation) newIndent = Editor.Parser.firstIndentation(nextChars, curIndent, direction, firstText); } var indentDiff = newIndent - curIndent; // If there is too much, this is just a matter of shrinking a span. if (indentDiff < 0) { if (newIndent == 0) { if (firstText) select.snapshotMove(whiteSpace.firstChild, firstText.firstChild || firstText, 0); removeElement(whiteSpace); whiteSpace = null; } else { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; } } // Not enough... else if (indentDiff > 0) { // If there is whitespace, we grow it. if (whiteSpace) { whiteSpace.currentText = makeWhiteSpace(newIndent); whiteSpace.firstChild.nodeValue = whiteSpace.currentText; select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, indentDiff, true); } // Otherwise, we have to add a new whitespace node. else { whiteSpace = makePartSpan(makeWhiteSpace(newIndent)); whiteSpace.className = "whitespace"; if (start) insertAfter(whiteSpace, start); else this.container.insertBefore(whiteSpace, this.container.firstChild); select.snapshotMove(firstText && (firstText.firstChild || firstText), whiteSpace.firstChild, newIndent, false, true); } } // Make sure cursor ends up after the whitespace else if (whiteSpace) { select.snapshotMove(whiteSpace.firstChild, whiteSpace.firstChild, newIndent, false); } if (indentDiff != 0) this.addDirtyNode(start); }, // Re-highlight the selected part of the document. highlightAtCursor: function() { var pos = select.selectionTopNode(this.container, true); var to = select.selectionTopNode(this.container, false); if (pos === false || to === false) return false; select.markSelection(); if (this.highlight(pos, endOfLine(to, this.container), true, 20) === false) return false; select.selectMarked(); return true; }, // When tab is pressed with text selected, the whole selection is // re-indented, when nothing is selected, the line with the cursor // is re-indented. handleTab: function(direction) { if (this.options.tabMode == "spaces") select.insertTabAtCursor(); else this.reindentSelection(direction); }, // Custom home behaviour that doesn't land the cursor in front of // leading whitespace unless pressed twice. home: function() { var cur = select.selectionTopNode(this.container, true), start = cur; if (cur === false || !(!cur || cur.isPart || isBR(cur)) || !this.container.firstChild) return false; while (cur && !isBR(cur)) cur = cur.previousSibling; var next = cur ? cur.nextSibling : this.container.firstChild; if (next && next != start && next.isPart && hasClass(next, "whitespace")) select.focusAfterNode(next, this.container); else select.focusAfterNode(cur, this.container); select.scrollToCursor(this.container); return true; }, // Some browsers (Opera) don't manage to handle the end key // properly in the face of vertical scrolling. end: function() { var cur = select.selectionTopNode(this.container, true); if (cur === false) return false; cur = endOfLine(cur, this.container); if (!cur) return false; select.focusAfterNode(cur.previousSibling, this.container); select.scrollToCursor(this.container); return true; }, pageUp: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to keep one line on the screen. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { line = this.prevLine(line); if (line === false) break; } if (i == 0) return false; // Already at first line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, pageDown: function() { var line = this.cursorPosition().line, scrollAmount = this.visibleLineCount(); if (line === false || scrollAmount === false) return false; // Try to move to the last line of the current page. scrollAmount -= 2; for (var i = 0; i < scrollAmount; i++) { var nextLine = this.nextLine(line); if (nextLine === false) break; line = nextLine; } if (i == 0) return false; // Already at last line select.setCursorPos(this.container, {node: line, offset: 0}); select.scrollToCursor(this.container); return true; }, // Delay (or initiate) the next paren highlight event. scheduleParenHighlight: function() { if (this.parenEvent) parent.clearTimeout(this.parenEvent); var self = this; this.parenEvent = parent.setTimeout(function(){self.highlightParens();}, 300); }, // Take the token before the cursor. If it contains a character in // '()[]{}', search for the matching paren/brace/bracket, and // highlight them in green for a moment, or red if no proper match // was found. highlightParens: function(jump, fromKey) { var self = this, mark = this.options.markParen; if (typeof mark == "string") mark = [mark, mark]; // give the relevant nodes a colour. function highlight(node, ok) { if (!node) return; if (!mark) { node.style.fontWeight = "bold"; node.style.color = ok ? "#8F8" : "#F88"; } else if (mark.call) mark(node, ok); else node.className += " " + mark[ok ? 0 : 1]; } function unhighlight(node) { if (!node) return; if (mark && !mark.call) removeClass(removeClass(node, mark[0]), mark[1]); else if (self.options.unmarkParen) self.options.unmarkParen(node); else { node.style.fontWeight = ""; node.style.color = ""; } } if (!fromKey && self.highlighted) { unhighlight(self.highlighted[0]); unhighlight(self.highlighted[1]); } if (!window || !window.parent || !window.select) return; // Clear the event property. if (this.parenEvent) parent.clearTimeout(this.parenEvent); this.parenEvent = null; // Extract a 'paren' from a piece of text. function paren(node) { if (node.currentText) { var match = node.currentText.match(/^[\s\u00a0]*([\(\)\[\]{}])[\s\u00a0]*$/); return match && match[1]; } } // Determine the direction a paren is facing. function forward(ch) { return /[\(\[\{]/.test(ch); } var ch, cursor = select.selectionTopNode(this.container, true); if (!cursor || !this.highlightAtCursor()) return; cursor = select.selectionTopNode(this.container, true); if (!(cursor && ((ch = paren(cursor)) || (cursor = cursor.nextSibling) && (ch = paren(cursor))))) return; // We only look for tokens with the same className. var className = cursor.className, dir = forward(ch), match = matching[ch]; // Since parts of the document might not have been properly // highlighted, and it is hard to know in advance which part we // have to scan, we just try, and when we find dirty nodes we // abort, parse them, and re-try. function tryFindMatch() { var stack = [], ch, ok = true; for (var runner = cursor; runner; runner = dir ? runner.nextSibling : runner.previousSibling) { if (runner.className == className && isSpan(runner) && (ch = paren(runner))) { if (forward(ch) == dir) stack.push(ch); else if (!stack.length) ok = false; else if (stack.pop() != matching[ch]) ok = false; if (!stack.length) break; } else if (runner.dirty || !isSpan(runner) && !isBR(runner)) { return {node: runner, status: "dirty"}; } } return {node: runner, status: runner && ok}; } while (true) { var found = tryFindMatch(); if (found.status == "dirty") { this.highlight(found.node, endOfLine(found.node)); // Needed because in some corner cases a highlight does not // reach a node. found.node.dirty = false; continue; } else { highlight(cursor, found.status); highlight(found.node, found.status); if (fromKey) parent.setTimeout(function() {unhighlight(cursor); unhighlight(found.node);}, 500); else self.highlighted = [cursor, found.node]; if (jump && found.node) select.focusAfterNode(found.node.previousSibling, this.container); break; } } }, // Adjust the amount of whitespace at the start of the line that // the cursor is on so that it is indented properly. indentAtCursor: function(direction) { if (!this.container.firstChild) return; // The line has to have up-to-date lexical information, so we // highlight it first. if (!this.highlightAtCursor()) return; var cursor = select.selectionTopNode(this.container, false); // If we couldn't determine the place of the cursor, // there's nothing to indent. if (cursor === false) return; select.markSelection(); this.indentLineAfter(startOfLine(cursor), direction); select.selectMarked(); }, // Indent all lines whose start falls inside of the current // selection. indentRegion: function(start, end, direction) { var current = (start = startOfLine(start)), before = start && startOfLine(start.previousSibling); if (!isBR(end)) end = endOfLine(end, this.container); this.addDirtyNode(start); do { var next = endOfLine(current, this.container); if (current) this.highlight(before, next, true); this.indentLineAfter(current, direction); before = current; current = next; } while (current != end); select.setCursorPos(this.container, {node: start, offset: 0}, {node: end, offset: 0}); }, // Find the node that the cursor is in, mark it as dirty, and make // sure a highlight pass is scheduled. cursorActivity: function(safe) { // pagehide event hack above if (this.unloaded) { window.document.designMode = "off"; window.document.designMode = "on"; this.unloaded = false; } if (internetExplorer) { this.container.createTextRange().execCommand("unlink"); clearTimeout(this.saveSelectionSnapshot); var self = this; this.saveSelectionSnapshot = setTimeout(function() { var snapshot = select.getBookmark(self.container); if (snapshot) self.selectionSnapshot = snapshot; }, 200); } var activity = this.options.onCursorActivity; if (!safe || activity) { var cursor = select.selectionTopNode(this.container, false); if (cursor === false || !this.container.firstChild) return; cursor = cursor || this.container.firstChild; if (activity) activity(cursor); if (!safe) { this.scheduleHighlight(); this.addDirtyNode(cursor); } } }, reparseBuffer: function() { forEach(this.container.childNodes, function(node) {node.dirty = true;}); if (this.container.firstChild) this.addDirtyNode(this.container.firstChild); }, // Add a node to the set of dirty nodes, if it isn't already in // there. addDirtyNode: function(node) { node = node || this.container.firstChild; if (!node) return; for (var i = 0; i < this.dirty.length; i++) if (this.dirty[i] == node) return; if (node.nodeType != 3) node.dirty = true; this.dirty.push(node); }, allClean: function() { return !this.dirty.length; }, // Cause a highlight pass to happen in options.passDelay // milliseconds. Clear the existing timeout, if one exists. This // way, the passes do not happen while the user is typing, and // should as unobtrusive as possible. scheduleHighlight: function() { // Timeouts are routed through the parent window, because on // some browsers designMode windows do not fire timeouts. var self = this; parent.clearTimeout(this.highlightTimeout); this.highlightTimeout = parent.setTimeout(function(){self.highlightDirty();}, this.options.passDelay); }, // Fetch one dirty node, and remove it from the dirty set. getDirtyNode: function() { while (this.dirty.length > 0) { var found = this.dirty.pop(); // IE8 sometimes throws an unexplainable 'invalid argument' // exception for found.parentNode try { // If the node has been coloured in the meantime, or is no // longer in the document, it should not be returned. while (found && found.parentNode != this.container) found = found.parentNode; if (found && (found.dirty || found.nodeType == 3)) return found; } catch (e) {} } return null; }, // Pick dirty nodes, and highlight them, until options.passTime // milliseconds have gone by. The highlight method will continue // to next lines as long as it finds dirty nodes. It returns // information about the place where it stopped. If there are // dirty nodes left after this function has spent all its lines, // it shedules another highlight to finish the job. highlightDirty: function(force) { // Prevent FF from raising an error when it is firing timeouts // on a page that's no longer loaded. if (!window || !window.parent || !window.select) return false; if (!this.options.readOnly) select.markSelection(); var start, endTime = force ? null : time() + this.options.passTime; while ((time() < endTime || force) && (start = this.getDirtyNode())) { var result = this.highlight(start, endTime); if (result && result.node && result.dirty) this.addDirtyNode(result.node.nextSibling); } if (!this.options.readOnly) select.selectMarked(); if (start) this.scheduleHighlight(); return this.dirty.length == 0; }, // Creates a function that, when called through a timeout, will // continuously re-parse the document. documentScanner: function(passTime) { var self = this, pos = null; return function() { // FF timeout weirdness workaround. if (!window || !window.parent || !window.select) return; // If the current node is no longer in the document... oh // well, we start over. if (pos && pos.parentNode != self.container) pos = null; select.markSelection(); var result = self.highlight(pos, time() + passTime, true); select.selectMarked(); var newPos = result ? (result.node && result.node.nextSibling) : null; pos = (pos == newPos) ? null : newPos; self.delayScanning(); }; }, // Starts the continuous scanning process for this document after // a given interval. delayScanning: function() { if (this.scanner) { parent.clearTimeout(this.documentScan); this.documentScan = parent.setTimeout(this.scanner, this.options.continuousScanning); } }, // The function that does the actual highlighting/colouring (with // help from the parser and the DOM normalizer). Its interface is // rather overcomplicated, because it is used in different // situations: ensuring that a certain line is highlighted, or // highlighting up to X milliseconds starting from a certain // point. The 'from' argument gives the node at which it should // start. If this is null, it will start at the beginning of the // document. When a timestamp is given with the 'target' argument, // it will stop highlighting at that time. If this argument holds // a DOM node, it will highlight until it reaches that node. If at // any time it comes across two 'clean' lines (no dirty nodes), it // will stop, except when 'cleanLines' is true. maxBacktrack is // the maximum number of lines to backtrack to find an existing // parser instance. This is used to give up in situations where a // highlight would take too long and freeze the browser interface. highlight: function(from, target, cleanLines, maxBacktrack){ var container = this.container, self = this, active = this.options.activeTokens; var endTime = (typeof target == "number" ? target : null); if (!container.firstChild) return false; // Backtrack to the first node before from that has a partial // parse stored. while (from && (!from.parserFromHere || from.dirty)) { if (maxBacktrack != null && isBR(from) && (--maxBacktrack) < 0) return false; from = from.previousSibling; } // If we are at the end of the document, do nothing. if (from && !from.nextSibling) return false; // Check whether a part (<span> node) and the corresponding token // match. function correctPart(token, part){ return !part.reduced && part.currentText == token.value && part.className == token.style; } // Shorten the text associated with a part by chopping off // characters from the front. Note that only the currentText // property gets changed. For efficiency reasons, we leave the // nodeValue alone -- we set the reduced flag to indicate that // this part must be replaced. function shortenPart(part, minus){ part.currentText = part.currentText.substring(minus); part.reduced = true; } // Create a part corresponding to a given token. function tokenPart(token){ var part = makePartSpan(token.value); part.className = token.style; return part; } function maybeTouch(node) { if (node) { var old = node.oldNextSibling; if (lineDirty || old === undefined || node.nextSibling != old) self.history.touch(node); node.oldNextSibling = node.nextSibling; } else { var old = self.container.oldFirstChild; if (lineDirty || old === undefined || self.container.firstChild != old) self.history.touch(null); self.container.oldFirstChild = self.container.firstChild; } } // Get the token stream. If from is null, we start with a new // parser from the start of the frame, otherwise a partial parse // is resumed. var traversal = traverseDOM(from ? from.nextSibling : container.firstChild), stream = stringStream(traversal), parsed = from ? from.parserFromHere(stream) : Editor.Parser.make(stream); function surroundedByBRs(node) { return (node.previousSibling == null || isBR(node.previousSibling)) && (node.nextSibling == null || isBR(node.nextSibling)); } // parts is an interface to make it possible to 'delay' fetching // the next DOM node until we are completely done with the one // before it. This is necessary because often the next node is // not yet available when we want to proceed past the current // one. var parts = { current: null, // Fetch current node. get: function(){ if (!this.current) this.current = traversal.nodes.shift(); return this.current; }, // Advance to the next part (do not fetch it yet). next: function(){ this.current = null; }, // Remove the current part from the DOM tree, and move to the // next. remove: function(){ container.removeChild(this.get()); this.current = null; }, // Advance to the next part that is not empty, discarding empty // parts. getNonEmpty: function(){ var part = this.get(); // Allow empty nodes when they are alone on a line, needed // for the FF cursor bug workaround (see select.js, // insertNewlineAtCursor). while (part && isSpan(part) && part.currentText == "") { // Leave empty nodes that are alone on a line alone in // Opera, since that browsers doesn't deal well with // having 2 BRs in a row. if (window.opera && surroundedByBRs(part)) { this.next(); part = this.get(); } else { var old = part; this.remove(); part = this.get(); // Adjust selection information, if any. See select.js for details. select.snapshotMove(old.firstChild, part && (part.firstChild || part), 0); } } return part; } }; var lineDirty = false, prevLineDirty = true, lineNodes = 0; // This forEach loops over the tokens from the parsed stream, and // at the same time uses the parts object to proceed through the // corresponding DOM nodes. forEach(parsed, function(token){ var part = parts.getNonEmpty(); if (token.value == "\n"){ // The idea of the two streams actually staying synchronized // is such a long shot that we explicitly check. if (!isBR(part)) throw "Parser out of sync. Expected BR."; if (part.dirty || !part.indentation) lineDirty = true; maybeTouch(from); from = part; // Every <br> gets a copy of the parser state and a lexical // context assigned to it. The first is used to be able to // later resume parsing from this point, the second is used // for indentation. part.parserFromHere = parsed.copy(); part.indentation = token.indentation || alwaysZero; part.dirty = false; // If the target argument wasn't an integer, go at least // until that node. if (endTime == null && part == target) throw StopIteration; // A clean line with more than one node means we are done. // Throwing a StopIteration is the way to break out of a // MochiKit forEach loop. if ((endTime != null && time() >= endTime) || (!lineDirty && !prevLineDirty && lineNodes > 1 && !cleanLines)) throw StopIteration; prevLineDirty = lineDirty; lineDirty = false; lineNodes = 0; parts.next(); } else { if (!isSpan(part)) throw "Parser out of sync. Expected SPAN."; if (part.dirty) lineDirty = true; lineNodes++; // If the part matches the token, we can leave it alone. if (correctPart(token, part)){ if (active && part.dirty) active(part, token, self); part.dirty = false; parts.next(); } // Otherwise, we have to fix it. else { lineDirty = true; // Insert the correct part. var newPart = tokenPart(token); container.insertBefore(newPart, part); if (active) active(newPart, token, self); var tokensize = token.value.length; var offset = 0; // Eat up parts until the text for this token has been // removed, adjusting the stored selection info (see // select.js) in the process. while (tokensize > 0) { part = parts.get(); var partsize = part.currentText.length; select.snapshotReplaceNode(part.firstChild, newPart.firstChild, tokensize, offset); if (partsize > tokensize){ shortenPart(part, tokensize); tokensize = 0; } else { tokensize -= partsize; offset += partsize; parts.remove(); } } } } }); maybeTouch(from); webkitLastLineHack(this.container); // The function returns some status information that is used by // hightlightDirty to determine whether and where it has to // continue. return {node: parts.getNonEmpty(), dirty: lineDirty}; } }; return Editor; })(); addEventHandler(window, "load", function() { var CodeMirror = window.frameElement.CodeMirror; var e = CodeMirror.editor = new Editor(CodeMirror.options); parent.setTimeout(method(CodeMirror, "init"), 0); });
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Parse function for PHP. Makes use of the tokenizer from tokenizephp.js. Based on parsejavascript.js by Marijn Haverbeke. Features: + special "deprecated" style for PHP4 keywords like 'var' + support for PHP 5.3 keywords: 'namespace', 'use' + 911 predefined constants, 1301 predefined functions, 105 predeclared classes from a typical PHP installation in a LAMP environment + new feature: syntax error flagging, thus enabling strict parsing of: + function definitions with explicitly or implicitly typed arguments and default values + modifiers (public, static etc.) applied to method and member definitions + foreach(array_expression as $key [=> $value]) loops + differentiation between single-quoted strings and double-quoted interpolating strings */ // add the Array.indexOf method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array/IndexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } var PHPParser = Editor.Parser = (function() { // Token types that can be considered to be atoms, part of operator expressions var atomicTypes = { "atom": true, "number": true, "variable": true, "string": true }; // Constructor for the lexical context objects. function PHPLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // PHP indentation rules function indentPHP(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parsePHP(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizePHP(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [statements]; // The lexical scope, used mostly for indentation. var lexical = new PHPLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; // parsing is accomplished by calling next() repeatedly function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch the next token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentPHP(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment" || token.type == "string_not_terminated" ) return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. 'marked' is used to change the style of the current token. while(true) { consume = marked = false; // Take and execute the topmost action. var action = cc.pop(); action(token); if (consume){ if (marked) token.style = marked; // Here we differentiate between local and global variables. return token; } } return 1; // Firebug workaround for http://code.google.com/p/fbug/issues/detail?id=1239#c1 } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, so they can // be shared between runs of the parser. function copy(){ var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizePHP(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Add a lyer of style to the current token, for example syntax-error function mark_add(style){ marked = marked + ' ' + style; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function pushlexing() { lexical = new PHPLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ if (lexical.prev) lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. This will ignore (and recover from) syntax errors. function expect(wanted){ return function expecting(token){ if (token.type == wanted) cont(); // consume the token else { cont(arguments.callee); // continue expecting() - call itself } }; } // Require a specific token type, or one of the tokens passed in the 'wanted' array // Used to detect blatant syntax errors. 'execute' is used to pass extra code // to be executed if the token is matched. For example, a '(' match could // 'execute' a cont( compasep(funcarg), require(")") ) function require(wanted, execute){ return function requiring(token){ var ok; var type = token.type; if (typeof(wanted) == "string") ok = (type == wanted) -1; else ok = wanted.indexOf(type); if (ok >= 0) { if (execute && typeof(execute[ok]) == "function") pass(execute[ok]); else cont(); } else { if (!marked) mark(token.style); mark_add("syntax-error"); cont(arguments.callee); } }; } // Looks for a statement, and then calls itself. function statements(token){ return pass(statement, statements); } // Dispatches various types of statements based on the type of the current token. function statement(token){ var type = token.type; if (type == "keyword a") cont(pushlex("form"), expression, altsyntax, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), altsyntax, statement, poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == "function") funcdef(); // technically, "class implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "class") classdef(); else if (type == "foreach") cont(pushlex("form"), require("("), pushlex(")"), expression, require("as"), require("variable"), /* => $value */ expect(")"), altsyntax, poplex, statement, poplex); else if (type == "for") cont(pushlex("form"), require("("), pushlex(")"), expression, require(";"), expression, require(";"), expression, require(")"), altsyntax, poplex, statement, poplex); // public final function foo(), protected static $bar; else if (type == "modifier") cont(require(["modifier", "variable", "function", "abstract"], [null, commasep(require("variable")), funcdef, absfun])); else if (type == "abstract") abs(); else if (type == "switch") cont(pushlex("form"), require("("), expression, require(")"), pushlex("}", "switch"), require([":", "{"]), block, poplex, poplex); else if (type == "case") cont(expression, require(":")); else if (type == "default") cont(require(":")); else if (type == "catch") cont(pushlex("form"), require("("), require("t_string"), require("variable"), require(")"), statement, poplex); else if (type == "const") cont(require("t_string")); // 'const static x=5' is a syntax error // technically, "namespace implode {...}" is correct, but we'll flag that as an error because it overrides a predefined function else if (type == "namespace") cont(namespacedef, require(";")); // $variables may be followed by operators, () for variable function calls, or [] subscripts else pass(pushlex("stat"), expression, require(";"), poplex); } // Dispatch expression types. function expression(token){ var type = token.type; if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "<<<") cont(require("string"), maybeoperator); // heredoc/nowdoc else if (type == "t_string") cont(maybe_double_colon, maybeoperator); else if (type == "keyword c" || type == "operator") cont(expression); // lambda else if (type == "function") lambdadef(); // function call or parenthesized expression: $a = ($b + 1) * 2; else if (type == "(") cont(pushlex(")"), commasep(expression), require(")"), poplex, maybeoperator); } // Called for places where operators, function calls, or subscripts are // valid. Will skip on to the next action if none is found. function maybeoperator(token){ var type = token.type; if (type == "operator") { if (token.content == "?") cont(expression, require(":"), expression); // ternary operator else cont(expression); } else if (type == "(") cont(pushlex(")"), expression, commasep(expression), require(")"), poplex, maybeoperator /* $varfunc() + 3 */); else if (type == "[") cont(pushlex("]"), expression, require("]"), maybeoperator /* for multidimensional arrays, or $func[$i]() */, poplex); } // A regular use of the double colon to specify a class, as in self::func() or myclass::$var; // Differs from `namespace` or `use` in that only one class can be the parent; chains (A::B::$var) are a syntax error. function maybe_double_colon(token) { if (token.type == "t_double_colon") // A::$var, A::func(), A::const cont(require(["t_string", "variable"]), maybeoperator); else { // a t_string wasn't followed by ::, such as in a function call: foo() pass(expression) } } // the declaration or definition of a function function funcdef() { cont(require("t_string"), require("("), pushlex(")"), commasep(funcarg), require(")"), poplex, block); } // the declaration or definition of a lambda function lambdadef() { cont(require("("), pushlex(")"), commasep(funcarg), require(")"), maybe_lambda_use, poplex, require("{"), pushlex("}"), block, poplex); } // optional lambda 'use' statement function maybe_lambda_use(token) { if(token.type == "namespace") { cont(require('('), commasep(funcarg), require(')')); } else { pass(expression); } } // the definition of a class function classdef() { cont(require("t_string"), expect("{"), pushlex("}"), block, poplex); } // either funcdef if the current token is "function", or the keyword "function" + funcdef function absfun(token) { if(token.type == "function") funcdef(); else cont(require(["function"], [funcdef])); } // the abstract class or function (with optional modifier) function abs(token) { cont(require(["modifier", "function", "class"], [absfun, funcdef, classdef])); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what){ function proceed(token) { if (token.type == ",") cont(what, proceed); } return function commaSeparated() { pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(token) { if (token.type == "}") cont(); else pass(statement, block); } function empty_parens_if_array(token) { if(token.content == "array") cont(require("("), require(")")); } function maybedefaultparameter(token){ if (token.content == "=") cont(require(["t_string", "string", "number", "atom"], [empty_parens_if_array, null, null])); } function var_or_reference(token) { if(token.type == "variable") cont(maybedefaultparameter); else if(token.content == "&") cont(require("variable"), maybedefaultparameter); } // support for default arguments: http://us.php.net/manual/en/functions.arguments.php#functions.arguments.default function funcarg(token){ // function foo(myclass $obj) {...} or function foo(myclass &objref) {...} if (token.type == "t_string") cont(var_or_reference); // function foo($var) {...} or function foo(&$ref) {...} else var_or_reference(token); } // A namespace definition or use function maybe_double_colon_def(token) { if (token.type == "t_double_colon") cont(namespacedef); } function namespacedef(token) { pass(require("t_string"), maybe_double_colon_def); } function altsyntax(token){ if(token.content==':') cont(altsyntaxBlock,poplex); } function altsyntaxBlock(token){ if (token.type == "altsyntaxend") cont(require(';')); else pass(statement, altsyntaxBlock); } return parser; } return {make: parsePHP, electricChars: "{}:"}; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Vlad Dan Dascalescu <dandv@yahoo-inc.com> Tokenizer for PHP code References: + http://php.net/manual/en/reserved.php + http://php.net/tokens + get_defined_constants(), get_defined_functions(), get_declared_classes() executed on a realistic (not vanilla) PHP installation with typical LAMP modules. Specifically, the PHP bundled with the Uniform Web Server (www.uniformserver.com). */ // add the forEach method for JS engines that don't support it (e.g. IE) // code from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this); } }; } var tokenizePHP = (function() { /* A map of PHP's reserved words (keywords, predefined classes, functions and constants. Each token has a type ('keyword', 'operator' etc.) and a style. The style corresponds to the CSS span class in phpcolors.css. Keywords can be of three types: a - takes an expression and forms a statement - e.g. if b - takes just a statement - e.g. else c - takes an optinoal expression, but no statement - e.g. return This distinction gives the parser enough information to parse correct code correctly (we don't care that much how we parse incorrect code). Reference: http://us.php.net/manual/en/reserved.php */ var keywords = function(){ function token(type, style){ return {type: type, style: style}; } var result = {}; // for each(var element in ["...", "..."]) can pick up elements added to // Array.prototype, so we'll use the loop structure below. See also // http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in // keywords that take an expression and form a statement ["if", "elseif", "while", "declare"].forEach(function(element, index, array) { result[element] = token("keyword a", "php-keyword"); }); // keywords that take just a statement ["do", "else", "try" ].forEach(function(element, index, array) { result[element] = token("keyword b", "php-keyword"); }); // keywords that take an optional expression, but no statement ["return", "break", "continue", // the expression is optional "new", "clone", "throw" // the expression is mandatory ].forEach(function(element, index, array) { result[element] = token("keyword c", "php-keyword"); }); ["__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__", "__METHOD__", "__NAMESPACE__"].forEach(function(element, index, array) { result[element] = token("atom", "php-compile-time-constant"); }); ["true", "false", "null"].forEach(function(element, index, array) { result[element] = token("atom", "php-atom"); }); ["and", "or", "xor", "instanceof"].forEach(function(element, index, array) { result[element] = token("operator", "php-keyword php-operator"); }); ["class", "interface"].forEach(function(element, index, array) { result[element] = token("class", "php-keyword"); }); ["namespace", "use", "extends", "implements"].forEach(function(element, index, array) { result[element] = token("namespace", "php-keyword"); }); // reserved "language constructs"... http://php.net/manual/en/reserved.php [ "die", "echo", "empty", "exit", "eval", "include", "include_once", "isset", "list", "require", "require_once", "return", "print", "unset", "array" // a keyword rather, but mandates a parenthesized parameter list ].forEach(function(element, index, array) { result[element] = token("t_string", "php-reserved-language-construct"); }); result["switch"] = token("switch", "php-keyword"); result["case"] = token("case", "php-keyword"); result["default"] = token("default", "php-keyword"); result["catch"] = token("catch", "php-keyword"); result["function"] = token("function", "php-keyword"); // http://php.net/manual/en/control-structures.alternative-syntax.php must be followed by a ':' ["endif", "endwhile", "endfor", "endforeach", "endswitch", "enddeclare"].forEach(function(element, index, array) { result[element] = token("altsyntaxend", "php-keyword"); }); result["const"] = token("const", "php-keyword"); ["final", "private", "protected", "public", "global", "static"].forEach(function(element, index, array) { result[element] = token("modifier", "php-keyword"); }); result["var"] = token("modifier", "php-keyword deprecated"); result["abstract"] = token("abstract", "php-keyword"); result["foreach"] = token("foreach", "php-keyword"); result["as"] = token("as", "php-keyword"); result["for"] = token("for", "php-keyword"); // PHP built-in functions - output of get_defined_functions()["internal"] [ "zend_version", "func_num_args", "func_get_arg", "func_get_args", "strlen", "strcmp", "strncmp", "strcasecmp", "strncasecmp", "each", "error_reporting", "define", "defined", "get_class", "get_parent_class", "method_exists", "property_exists", "class_exists", "interface_exists", "function_exists", "get_included_files", "get_required_files", "is_subclass_of", "is_a", "get_class_vars", "get_object_vars", "get_class_methods", "trigger_error", "user_error", "set_error_handler", "restore_error_handler", "set_exception_handler", "restore_exception_handler", "get_declared_classes", "get_declared_interfaces", "get_defined_functions", "get_defined_vars", "create_function", "get_resource_type", "get_loaded_extensions", "extension_loaded", "get_extension_funcs", "get_defined_constants", "debug_backtrace", "debug_print_backtrace", "bcadd", "bcsub", "bcmul", "bcdiv", "bcmod", "bcpow", "bcsqrt", "bcscale", "bccomp", "bcpowmod", "jdtogregorian", "gregoriantojd", "jdtojulian", "juliantojd", "jdtojewish", "jewishtojd", "jdtofrench", "frenchtojd", "jddayofweek", "jdmonthname", "easter_date", "easter_days", "unixtojd", "jdtounix", "cal_to_jd", "cal_from_jd", "cal_days_in_month", "cal_info", "variant_set", "variant_add", "variant_cat", "variant_sub", "variant_mul", "variant_and", "variant_div", "variant_eqv", "variant_idiv", "variant_imp", "variant_mod", "variant_or", "variant_pow", "variant_xor", "variant_abs", "variant_fix", "variant_int", "variant_neg", "variant_not", "variant_round", "variant_cmp", "variant_date_to_timestamp", "variant_date_from_timestamp", "variant_get_type", "variant_set_type", "variant_cast", "com_create_guid", "com_event_sink", "com_print_typeinfo", "com_message_pump", "com_load_typelib", "com_get_active_object", "ctype_alnum", "ctype_alpha", "ctype_cntrl", "ctype_digit", "ctype_lower", "ctype_graph", "ctype_print", "ctype_punct", "ctype_space", "ctype_upper", "ctype_xdigit", "strtotime", "date", "idate", "gmdate", "mktime", "gmmktime", "checkdate", "strftime", "gmstrftime", "time", "localtime", "getdate", "date_create", "date_parse", "date_format", "date_modify", "date_timezone_get", "date_timezone_set", "date_offset_get", "date_time_set", "date_date_set", "date_isodate_set", "timezone_open", "timezone_name_get", "timezone_name_from_abbr", "timezone_offset_get", "timezone_transitions_get", "timezone_identifiers_list", "timezone_abbreviations_list", "date_default_timezone_set", "date_default_timezone_get", "date_sunrise", "date_sunset", "date_sun_info", "filter_input", "filter_var", "filter_input_array", "filter_var_array", "filter_list", "filter_has_var", "filter_id", "ftp_connect", "ftp_login", "ftp_pwd", "ftp_cdup", "ftp_chdir", "ftp_exec", "ftp_raw", "ftp_mkdir", "ftp_rmdir", "ftp_chmod", "ftp_alloc", "ftp_nlist", "ftp_rawlist", "ftp_systype", "ftp_pasv", "ftp_get", "ftp_fget", "ftp_put", "ftp_fput", "ftp_size", "ftp_mdtm", "ftp_rename", "ftp_delete", "ftp_site", "ftp_close", "ftp_set_option", "ftp_get_option", "ftp_nb_fget", "ftp_nb_get", "ftp_nb_continue", "ftp_nb_put", "ftp_nb_fput", "ftp_quit", "hash", "hash_file", "hash_hmac", "hash_hmac_file", "hash_init", "hash_update", "hash_update_stream", "hash_update_file", "hash_final", "hash_algos", "iconv", "ob_iconv_handler", "iconv_get_encoding", "iconv_set_encoding", "iconv_strlen", "iconv_substr", "iconv_strpos", "iconv_strrpos", "iconv_mime_encode", "iconv_mime_decode", "iconv_mime_decode_headers", "json_encode", "json_decode", "odbc_autocommit", "odbc_binmode", "odbc_close", "odbc_close_all", "odbc_columns", "odbc_commit", "odbc_connect", "odbc_cursor", "odbc_data_source", "odbc_execute", "odbc_error", "odbc_errormsg", "odbc_exec", "odbc_fetch_array", "odbc_fetch_object", "odbc_fetch_row", "odbc_fetch_into", "odbc_field_len", "odbc_field_scale", "odbc_field_name", "odbc_field_type", "odbc_field_num", "odbc_free_result", "odbc_gettypeinfo", "odbc_longreadlen", "odbc_next_result", "odbc_num_fields", "odbc_num_rows", "odbc_pconnect", "odbc_prepare", "odbc_result", "odbc_result_all", "odbc_rollback", "odbc_setoption", "odbc_specialcolumns", "odbc_statistics", "odbc_tables", "odbc_primarykeys", "odbc_columnprivileges", "odbc_tableprivileges", "odbc_foreignkeys", "odbc_procedures", "odbc_procedurecolumns", "odbc_do", "odbc_field_precision", "preg_match", "preg_match_all", "preg_replace", "preg_replace_callback", "preg_split", "preg_quote", "preg_grep", "preg_last_error", "session_name", "session_module_name", "session_save_path", "session_id", "session_regenerate_id", "session_decode", "session_register", "session_unregister", "session_is_registered", "session_encode", "session_start", "session_destroy", "session_unset", "session_set_save_handler", "session_cache_limiter", "session_cache_expire", "session_set_cookie_params", "session_get_cookie_params", "session_write_close", "session_commit", "spl_classes", "spl_autoload", "spl_autoload_extensions", "spl_autoload_register", "spl_autoload_unregister", "spl_autoload_functions", "spl_autoload_call", "class_parents", "class_implements", "spl_object_hash", "iterator_to_array", "iterator_count", "iterator_apply", "constant", "bin2hex", "sleep", "usleep", "flush", "wordwrap", "htmlspecialchars", "htmlentities", "html_entity_decode", "htmlspecialchars_decode", "get_html_translation_table", "sha1", "sha1_file", "md5", "md5_file", "crc32", "iptcparse", "iptcembed", "getimagesize", "image_type_to_mime_type", "image_type_to_extension", "phpinfo", "phpversion", "phpcredits", "php_logo_guid", "php_real_logo_guid", "php_egg_logo_guid", "zend_logo_guid", "php_sapi_name", "php_uname", "php_ini_scanned_files", "strnatcmp", "strnatcasecmp", "substr_count", "strspn", "strcspn", "strtok", "strtoupper", "strtolower", "strpos", "stripos", "strrpos", "strripos", "strrev", "hebrev", "hebrevc", "nl2br", "basename", "dirname", "pathinfo", "stripslashes", "stripcslashes", "strstr", "stristr", "strrchr", "str_shuffle", "str_word_count", "str_split", "strpbrk", "substr_compare", "strcoll", "substr", "substr_replace", "quotemeta", "ucfirst", "ucwords", "strtr", "addslashes", "addcslashes", "rtrim", "str_replace", "str_ireplace", "str_repeat", "count_chars", "chunk_split", "trim", "ltrim", "strip_tags", "similar_text", "explode", "implode", "setlocale", "localeconv", "soundex", "levenshtein", "chr", "ord", "parse_str", "str_pad", "chop", "strchr", "sprintf", "printf", "vprintf", "vsprintf", "fprintf", "vfprintf", "sscanf", "fscanf", "parse_url", "urlencode", "urldecode", "rawurlencode", "rawurldecode", "http_build_query", "unlink", "exec", "system", "escapeshellcmd", "escapeshellarg", "passthru", "shell_exec", "proc_open", "proc_close", "proc_terminate", "proc_get_status", "rand", "srand", "getrandmax", "mt_rand", "mt_srand", "mt_getrandmax", "getservbyname", "getservbyport", "getprotobyname", "getprotobynumber", "getmyuid", "getmygid", "getmypid", "getmyinode", "getlastmod", "base64_decode", "base64_encode", "convert_uuencode", "convert_uudecode", "abs", "ceil", "floor", "round", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "sinh", "cosh", "tanh", "pi", "is_finite", "is_nan", "is_infinite", "pow", "exp", "log", "log10", "sqrt", "hypot", "deg2rad", "rad2deg", "bindec", "hexdec", "octdec", "decbin", "decoct", "dechex", "base_convert", "number_format", "fmod", "ip2long", "long2ip", "getenv", "putenv", "microtime", "gettimeofday", "uniqid", "quoted_printable_decode", "convert_cyr_string", "get_current_user", "set_time_limit", "get_cfg_var", "magic_quotes_runtime", "set_magic_quotes_runtime", "get_magic_quotes_gpc", "get_magic_quotes_runtime", "import_request_variables", "error_log", "error_get_last", "call_user_func", "call_user_func_array", "call_user_method", "call_user_method_array", "serialize", "unserialize", "var_dump", "var_export", "debug_zval_dump", "print_r", "memory_get_usage", "memory_get_peak_usage", "register_shutdown_function", "register_tick_function", "unregister_tick_function", "highlight_file", "show_source", "highlight_string", "php_strip_whitespace", "ini_get", "ini_get_all", "ini_set", "ini_alter", "ini_restore", "get_include_path", "set_include_path", "restore_include_path", "setcookie", "setrawcookie", "header", "headers_sent", "headers_list", "connection_aborted", "connection_status", "ignore_user_abort", "parse_ini_file", "is_uploaded_file", "move_uploaded_file", "gethostbyaddr", "gethostbyname", "gethostbynamel", "intval", "floatval", "doubleval", "strval", "gettype", "settype", "is_null", "is_resource", "is_bool", "is_long", "is_float", "is_int", "is_integer", "is_double", "is_real", "is_numeric", "is_string", "is_array", "is_object", "is_scalar", "is_callable", "ereg", "ereg_replace", "eregi", "eregi_replace", "split", "spliti", "join", "sql_regcase", "dl", "pclose", "popen", "readfile", "rewind", "rmdir", "umask", "fclose", "feof", "fgetc", "fgets", "fgetss", "fread", "fopen", "fpassthru", "ftruncate", "fstat", "fseek", "ftell", "fflush", "fwrite", "fputs", "mkdir", "rename", "copy", "tempnam", "tmpfile", "file", "file_get_contents", "file_put_contents", "stream_select", "stream_context_create", "stream_context_set_params", "stream_context_set_option", "stream_context_get_options", "stream_context_get_default", "stream_filter_prepend", "stream_filter_append", "stream_filter_remove", "stream_socket_client", "stream_socket_server", "stream_socket_accept", "stream_socket_get_name", "stream_socket_recvfrom", "stream_socket_sendto", "stream_socket_enable_crypto", "stream_socket_shutdown", "stream_copy_to_stream", "stream_get_contents", "fgetcsv", "fputcsv", "flock", "get_meta_tags", "stream_set_write_buffer", "set_file_buffer", "set_socket_blocking", "stream_set_blocking", "socket_set_blocking", "stream_get_meta_data", "stream_get_line", "stream_wrapper_register", "stream_register_wrapper", "stream_wrapper_unregister", "stream_wrapper_restore", "stream_get_wrappers", "stream_get_transports", "get_headers", "stream_set_timeout", "socket_set_timeout", "socket_get_status", "realpath", "fsockopen", "pfsockopen", "pack", "unpack", "get_browser", "crypt", "opendir", "closedir", "chdir", "getcwd", "rewinddir", "readdir", "dir", "scandir", "glob", "fileatime", "filectime", "filegroup", "fileinode", "filemtime", "fileowner", "fileperms", "filesize", "filetype", "file_exists", "is_writable", "is_writeable", "is_readable", "is_executable", "is_file", "is_dir", "is_link", "stat", "lstat", "chown", "chgrp", "chmod", "touch", "clearstatcache", "disk_total_space", "disk_free_space", "diskfreespace", "mail", "ezmlm_hash", "openlog", "syslog", "closelog", "define_syslog_variables", "lcg_value", "metaphone", "ob_start", "ob_flush", "ob_clean", "ob_end_flush", "ob_end_clean", "ob_get_flush", "ob_get_clean", "ob_get_length", "ob_get_level", "ob_get_status", "ob_get_contents", "ob_implicit_flush", "ob_list_handlers", "ksort", "krsort", "natsort", "natcasesort", "asort", "arsort", "sort", "rsort", "usort", "uasort", "uksort", "shuffle", "array_walk", "array_walk_recursive", "count", "end", "prev", "next", "reset", "current", "key", "min", "max", "in_array", "array_search", "extract", "compact", "array_fill", "array_fill_keys", "range", "array_multisort", "array_push", "array_pop", "array_shift", "array_unshift", "array_splice", "array_slice", "array_merge", "array_merge_recursive", "array_keys", "array_values", "array_count_values", "array_reverse", "array_reduce", "array_pad", "array_flip", "array_change_key_case", "array_rand", "array_unique", "array_intersect", "array_intersect_key", "array_intersect_ukey", "array_uintersect", "array_intersect_assoc", "array_uintersect_assoc", "array_intersect_uassoc", "array_uintersect_uassoc", "array_diff", "array_diff_key", "array_diff_ukey", "array_udiff", "array_diff_assoc", "array_udiff_assoc", "array_diff_uassoc", "array_udiff_uassoc", "array_sum", "array_product", "array_filter", "array_map", "array_chunk", "array_combine", "array_key_exists", "pos", "sizeof", "key_exists", "assert", "assert_options", "version_compare", "str_rot13", "stream_get_filters", "stream_filter_register", "stream_bucket_make_writeable", "stream_bucket_prepend", "stream_bucket_append", "stream_bucket_new", "output_add_rewrite_var", "output_reset_rewrite_vars", "sys_get_temp_dir", "token_get_all", "token_name", "readgzfile", "gzrewind", "gzclose", "gzeof", "gzgetc", "gzgets", "gzgetss", "gzread", "gzopen", "gzpassthru", "gzseek", "gztell", "gzwrite", "gzputs", "gzfile", "gzcompress", "gzuncompress", "gzdeflate", "gzinflate", "gzencode", "ob_gzhandler", "zlib_get_coding_type", "libxml_set_streams_context", "libxml_use_internal_errors", "libxml_get_last_error", "libxml_clear_errors", "libxml_get_errors", "dom_import_simplexml", "simplexml_load_file", "simplexml_load_string", "simplexml_import_dom", "wddx_serialize_value", "wddx_serialize_vars", "wddx_packet_start", "wddx_packet_end", "wddx_add_vars", "wddx_deserialize", "xml_parser_create", "xml_parser_create_ns", "xml_set_object", "xml_set_element_handler", "xml_set_character_data_handler", "xml_set_processing_instruction_handler", "xml_set_default_handler", "xml_set_unparsed_entity_decl_handler", "xml_set_notation_decl_handler", "xml_set_external_entity_ref_handler", "xml_set_start_namespace_decl_handler", "xml_set_end_namespace_decl_handler", "xml_parse", "xml_parse_into_struct", "xml_get_error_code", "xml_error_string", "xml_get_current_line_number", "xml_get_current_column_number", "xml_get_current_byte_index", "xml_parser_free", "xml_parser_set_option", "xml_parser_get_option", "utf8_encode", "utf8_decode", "xmlwriter_open_uri", "xmlwriter_open_memory", "xmlwriter_set_indent", "xmlwriter_set_indent_string", "xmlwriter_start_comment", "xmlwriter_end_comment", "xmlwriter_start_attribute", "xmlwriter_end_attribute", "xmlwriter_write_attribute", "xmlwriter_start_attribute_ns", "xmlwriter_write_attribute_ns", "xmlwriter_start_element", "xmlwriter_end_element", "xmlwriter_full_end_element", "xmlwriter_start_element_ns", "xmlwriter_write_element", "xmlwriter_write_element_ns", "xmlwriter_start_pi", "xmlwriter_end_pi", "xmlwriter_write_pi", "xmlwriter_start_cdata", "xmlwriter_end_cdata", "xmlwriter_write_cdata", "xmlwriter_text", "xmlwriter_write_raw", "xmlwriter_start_document", "xmlwriter_end_document", "xmlwriter_write_comment", "xmlwriter_start_dtd", "xmlwriter_end_dtd", "xmlwriter_write_dtd", "xmlwriter_start_dtd_element", "xmlwriter_end_dtd_element", "xmlwriter_write_dtd_element", "xmlwriter_start_dtd_attlist", "xmlwriter_end_dtd_attlist", "xmlwriter_write_dtd_attlist", "xmlwriter_start_dtd_entity", "xmlwriter_end_dtd_entity", "xmlwriter_write_dtd_entity", "xmlwriter_output_memory", "xmlwriter_flush", "gd_info", "imagearc", "imageellipse", "imagechar", "imagecharup", "imagecolorat", "imagecolorallocate", "imagepalettecopy", "imagecreatefromstring", "imagecolorclosest", "imagecolordeallocate", "imagecolorresolve", "imagecolorexact", "imagecolorset", "imagecolortransparent", "imagecolorstotal", "imagecolorsforindex", "imagecopy", "imagecopymerge", "imagecopymergegray", "imagecopyresized", "imagecreate", "imagecreatetruecolor", "imageistruecolor", "imagetruecolortopalette", "imagesetthickness", "imagefilledarc", "imagefilledellipse", "imagealphablending", "imagesavealpha", "imagecolorallocatealpha", "imagecolorresolvealpha", "imagecolorclosestalpha", "imagecolorexactalpha", "imagecopyresampled", "imagegrabwindow", "imagegrabscreen", "imagerotate", "imageantialias", "imagesettile", "imagesetbrush", "imagesetstyle", "imagecreatefrompng", "imagecreatefromgif", "imagecreatefromjpeg", "imagecreatefromwbmp", "imagecreatefromxbm", "imagecreatefromgd", "imagecreatefromgd2", "imagecreatefromgd2part", "imagepng", "imagegif", "imagejpeg", "imagewbmp", "imagegd", "imagegd2", "imagedestroy", "imagegammacorrect", "imagefill", "imagefilledpolygon", "imagefilledrectangle", "imagefilltoborder", "imagefontwidth", "imagefontheight", "imageinterlace", "imageline", "imageloadfont", "imagepolygon", "imagerectangle", "imagesetpixel", "imagestring", "imagestringup", "imagesx", "imagesy", "imagedashedline", "imagettfbbox", "imagettftext", "imageftbbox", "imagefttext", "imagepsloadfont", "imagepsfreefont", "imagepsencodefont", "imagepsextendfont", "imagepsslantfont", "imagepstext", "imagepsbbox", "imagetypes", "jpeg2wbmp", "png2wbmp", "image2wbmp", "imagelayereffect", "imagecolormatch", "imagexbm", "imagefilter", "imageconvolution", "mb_convert_case", "mb_strtoupper", "mb_strtolower", "mb_language", "mb_internal_encoding", "mb_http_input", "mb_http_output", "mb_detect_order", "mb_substitute_character", "mb_parse_str", "mb_output_handler", "mb_preferred_mime_name", "mb_strlen", "mb_strpos", "mb_strrpos", "mb_stripos", "mb_strripos", "mb_strstr", "mb_strrchr", "mb_stristr", "mb_strrichr", "mb_substr_count", "mb_substr", "mb_strcut", "mb_strwidth", "mb_strimwidth", "mb_convert_encoding", "mb_detect_encoding", "mb_list_encodings", "mb_convert_kana", "mb_encode_mimeheader", "mb_decode_mimeheader", "mb_convert_variables", "mb_encode_numericentity", "mb_decode_numericentity", "mb_send_mail", "mb_get_info", "mb_check_encoding", "mb_regex_encoding", "mb_regex_set_options", "mb_ereg", "mb_eregi", "mb_ereg_replace", "mb_eregi_replace", "mb_split", "mb_ereg_match", "mb_ereg_search", "mb_ereg_search_pos", "mb_ereg_search_regs", "mb_ereg_search_init", "mb_ereg_search_getregs", "mb_ereg_search_getpos", "mb_ereg_search_setpos", "mbregex_encoding", "mbereg", "mberegi", "mbereg_replace", "mberegi_replace", "mbsplit", "mbereg_match", "mbereg_search", "mbereg_search_pos", "mbereg_search_regs", "mbereg_search_init", "mbereg_search_getregs", "mbereg_search_getpos", "mbereg_search_setpos", "mysql_connect", "mysql_pconnect", "mysql_close", "mysql_select_db", "mysql_query", "mysql_unbuffered_query", "mysql_db_query", "mysql_list_dbs", "mysql_list_tables", "mysql_list_fields", "mysql_list_processes", "mysql_error", "mysql_errno", "mysql_affected_rows", "mysql_insert_id", "mysql_result", "mysql_num_rows", "mysql_num_fields", "mysql_fetch_row", "mysql_fetch_array", "mysql_fetch_assoc", "mysql_fetch_object", "mysql_data_seek", "mysql_fetch_lengths", "mysql_fetch_field", "mysql_field_seek", "mysql_free_result", "mysql_field_name", "mysql_field_table", "mysql_field_len", "mysql_field_type", "mysql_field_flags", "mysql_escape_string", "mysql_real_escape_string", "mysql_stat", "mysql_thread_id", "mysql_client_encoding", "mysql_ping", "mysql_get_client_info", "mysql_get_host_info", "mysql_get_proto_info", "mysql_get_server_info", "mysql_info", "mysql_set_charset", "mysql", "mysql_fieldname", "mysql_fieldtable", "mysql_fieldlen", "mysql_fieldtype", "mysql_fieldflags", "mysql_selectdb", "mysql_freeresult", "mysql_numfields", "mysql_numrows", "mysql_listdbs", "mysql_listtables", "mysql_listfields", "mysql_db_name", "mysql_dbname", "mysql_tablename", "mysql_table_name", "mysqli_affected_rows", "mysqli_autocommit", "mysqli_change_user", "mysqli_character_set_name", "mysqli_close", "mysqli_commit", "mysqli_connect", "mysqli_connect_errno", "mysqli_connect_error", "mysqli_data_seek", "mysqli_debug", "mysqli_disable_reads_from_master", "mysqli_disable_rpl_parse", "mysqli_dump_debug_info", "mysqli_enable_reads_from_master", "mysqli_enable_rpl_parse", "mysqli_embedded_server_end", "mysqli_embedded_server_start", "mysqli_errno", "mysqli_error", "mysqli_stmt_execute", "mysqli_execute", "mysqli_fetch_field", "mysqli_fetch_fields", "mysqli_fetch_field_direct", "mysqli_fetch_lengths", "mysqli_fetch_array", "mysqli_fetch_assoc", "mysqli_fetch_object", "mysqli_fetch_row", "mysqli_field_count", "mysqli_field_seek", "mysqli_field_tell", "mysqli_free_result", "mysqli_get_charset", "mysqli_get_client_info", "mysqli_get_client_version", "mysqli_get_host_info", "mysqli_get_proto_info", "mysqli_get_server_info", "mysqli_get_server_version", "mysqli_get_warnings", "mysqli_init", "mysqli_info", "mysqli_insert_id", "mysqli_kill", "mysqli_set_local_infile_default", "mysqli_set_local_infile_handler", "mysqli_master_query", "mysqli_more_results", "mysqli_multi_query", "mysqli_next_result", "mysqli_num_fields", "mysqli_num_rows", "mysqli_options", "mysqli_ping", "mysqli_prepare", "mysqli_report", "mysqli_query", "mysqli_real_connect", "mysqli_real_escape_string", "mysqli_real_query", "mysqli_rollback", "mysqli_rpl_parse_enabled", "mysqli_rpl_probe", "mysqli_rpl_query_type", "mysqli_select_db", "mysqli_set_charset", "mysqli_stmt_attr_get", "mysqli_stmt_attr_set", "mysqli_stmt_field_count", "mysqli_stmt_init", "mysqli_stmt_prepare", "mysqli_stmt_result_metadata", "mysqli_stmt_send_long_data", "mysqli_stmt_bind_param", "mysqli_stmt_bind_result", "mysqli_stmt_fetch", "mysqli_stmt_free_result", "mysqli_stmt_get_warnings", "mysqli_stmt_insert_id", "mysqli_stmt_reset", "mysqli_stmt_param_count", "mysqli_send_query", "mysqli_slave_query", "mysqli_sqlstate", "mysqli_ssl_set", "mysqli_stat", "mysqli_stmt_affected_rows", "mysqli_stmt_close", "mysqli_stmt_data_seek", "mysqli_stmt_errno", "mysqli_stmt_error", "mysqli_stmt_num_rows", "mysqli_stmt_sqlstate", "mysqli_store_result", "mysqli_stmt_store_result", "mysqli_thread_id", "mysqli_thread_safe", "mysqli_use_result", "mysqli_warning_count", "mysqli_bind_param", "mysqli_bind_result", "mysqli_client_encoding", "mysqli_escape_string", "mysqli_fetch", "mysqli_param_count", "mysqli_get_metadata", "mysqli_send_long_data", "mysqli_set_opt", "pdo_drivers", "socket_select", "socket_create", "socket_create_listen", "socket_accept", "socket_set_nonblock", "socket_set_block", "socket_listen", "socket_close", "socket_write", "socket_read", "socket_getsockname", "socket_getpeername", "socket_connect", "socket_strerror", "socket_bind", "socket_recv", "socket_send", "socket_recvfrom", "socket_sendto", "socket_get_option", "socket_set_option", "socket_shutdown", "socket_last_error", "socket_clear_error", "socket_getopt", "socket_setopt", "eaccelerator_put", "eaccelerator_get", "eaccelerator_rm", "eaccelerator_gc", "eaccelerator_lock", "eaccelerator_unlock", "eaccelerator_caching", "eaccelerator_optimizer", "eaccelerator_clear", "eaccelerator_clean", "eaccelerator_info", "eaccelerator_purge", "eaccelerator_cached_scripts", "eaccelerator_removed_scripts", "eaccelerator_list_keys", "eaccelerator_encode", "eaccelerator_load", "_eaccelerator_loader_file", "_eaccelerator_loader_line", "eaccelerator_set_session_handlers", "_eaccelerator_output_handler", "eaccelerator_cache_page", "eaccelerator_rm_page", "eaccelerator_cache_output", "eaccelerator_cache_result", "xdebug_get_stack_depth", "xdebug_get_function_stack", "xdebug_print_function_stack", "xdebug_get_declared_vars", "xdebug_call_class", "xdebug_call_function", "xdebug_call_file", "xdebug_call_line", "xdebug_var_dump", "xdebug_debug_zval", "xdebug_debug_zval_stdout", "xdebug_enable", "xdebug_disable", "xdebug_is_enabled", "xdebug_break", "xdebug_start_trace", "xdebug_stop_trace", "xdebug_get_tracefile_name", "xdebug_get_profiler_filename", "xdebug_dump_aggr_profiling_data", "xdebug_clear_aggr_profiling_data", "xdebug_memory_usage", "xdebug_peak_memory_usage", "xdebug_time_index", "xdebug_start_error_collection", "xdebug_stop_error_collection", "xdebug_get_collected_errors", "xdebug_start_code_coverage", "xdebug_stop_code_coverage", "xdebug_get_code_coverage", "xdebug_get_function_count", "xdebug_dump_superglobals", "_", /* alias for gettext()*/ "get_called_class","class_alias","gc_collect_cycles","gc_enabled","gc_enable", "gc_disable","date_create_from_format","date_parse_from_format", "date_get_last_errors","date_add","date_sub","date_diff","date_timestamp_set", "date_timestamp_get","timezone_location_get","timezone_version_get", "date_interval_create_from_date_string","date_interval_format", "libxml_disable_entity_loader","openssl_pkey_free","openssl_pkey_new", "openssl_pkey_export","openssl_pkey_export_to_file","openssl_pkey_get_private", "openssl_pkey_get_public","openssl_pkey_get_details","openssl_free_key", "openssl_get_privatekey","openssl_get_publickey","openssl_x509_read", "openssl_x509_free","openssl_x509_parse","openssl_x509_checkpurpose", "openssl_x509_check_private_key","openssl_x509_export","openssl_x509_export_to_file", "openssl_pkcs12_export","openssl_pkcs12_export_to_file","openssl_pkcs12_read", "openssl_csr_new","openssl_csr_export","openssl_csr_export_to_file", "openssl_csr_sign","openssl_csr_get_subject","openssl_csr_get_public_key", "openssl_digest","openssl_encrypt","openssl_decrypt","openssl_cipher_iv_length", "openssl_sign","openssl_verify","openssl_seal","openssl_open","openssl_pkcs7_verify", "openssl_pkcs7_decrypt","openssl_pkcs7_sign","openssl_pkcs7_encrypt", "openssl_private_encrypt","openssl_private_decrypt","openssl_public_encrypt", "openssl_public_decrypt","openssl_get_md_methods","openssl_get_cipher_methods", "openssl_dh_compute_key","openssl_random_pseudo_bytes","openssl_error_string", "preg_filter","bzopen","bzread","bzwrite","bzflush","bzclose","bzerrno", "bzerrstr","bzerror","bzcompress","bzdecompress","curl_init","curl_copy_handle", "curl_version","curl_setopt","curl_setopt_array","curl_exec","curl_getinfo", "curl_error","curl_errno","curl_close","curl_multi_init","curl_multi_add_handle", "curl_multi_remove_handle","curl_multi_select","curl_multi_exec","curl_multi_getcontent", "curl_multi_info_read","curl_multi_close","exif_read_data","read_exif_data", "exif_tagname","exif_thumbnail","exif_imagetype","ftp_ssl_connect", "imagecolorclosesthwb","imagecreatefromxpm","textdomain","gettext","dgettext", "dcgettext","bindtextdomain","ngettext","dngettext","dcngettext", "bind_textdomain_codeset","hash_copy","imap_open","imap_reopen","imap_close", "imap_num_msg","imap_num_recent","imap_headers","imap_headerinfo", "imap_rfc822_parse_headers","imap_rfc822_write_address","imap_rfc822_parse_adrlist", "imap_body","imap_bodystruct","imap_fetchbody","imap_savebody","imap_fetchheader", "imap_fetchstructure","imap_gc","imap_expunge","imap_delete","imap_undelete", "imap_check","imap_listscan","imap_mail_copy","imap_mail_move","imap_mail_compose", "imap_createmailbox","imap_renamemailbox","imap_deletemailbox","imap_subscribe", "imap_unsubscribe","imap_append","imap_ping","imap_base64","imap_qprint","imap_8bit", "imap_binary","imap_utf8","imap_status","imap_mailboxmsginfo","imap_setflag_full", "imap_clearflag_full","imap_sort","imap_uid","imap_msgno","imap_list","imap_lsub", "imap_fetch_overview","imap_alerts","imap_errors","imap_last_error","imap_search", "imap_utf7_decode","imap_utf7_encode","imap_mime_header_decode","imap_thread", "imap_timeout","imap_get_quota","imap_get_quotaroot","imap_set_quota","imap_setacl", "imap_getacl","imap_mail","imap_header","imap_listmailbox","imap_getmailboxes", "imap_scanmailbox","imap_listsubscribed","imap_getsubscribed","imap_fetchtext", "imap_scan","imap_create","imap_rename","json_last_error","mb_encoding_aliases", "mcrypt_ecb","mcrypt_cbc","mcrypt_cfb","mcrypt_ofb","mcrypt_get_key_size", "mcrypt_get_block_size","mcrypt_get_cipher_name","mcrypt_create_iv","mcrypt_list_algorithms", "mcrypt_list_modes","mcrypt_get_iv_size","mcrypt_encrypt","mcrypt_decrypt", "mcrypt_module_open","mcrypt_generic_init","mcrypt_generic","mdecrypt_generic", "mcrypt_generic_end","mcrypt_generic_deinit","mcrypt_enc_self_test", "mcrypt_enc_is_block_algorithm_mode","mcrypt_enc_is_block_algorithm", "mcrypt_enc_is_block_mode","mcrypt_enc_get_block_size","mcrypt_enc_get_key_size", "mcrypt_enc_get_supported_key_sizes","mcrypt_enc_get_iv_size", "mcrypt_enc_get_algorithms_name","mcrypt_enc_get_modes_name","mcrypt_module_self_test", "mcrypt_module_is_block_algorithm_mode","mcrypt_module_is_block_algorithm", "mcrypt_module_is_block_mode","mcrypt_module_get_algo_block_size", "mcrypt_module_get_algo_key_size","mcrypt_module_get_supported_key_sizes", "mcrypt_module_close","mysqli_refresh","posix_kill","posix_getpid","posix_getppid", "posix_getuid","posix_setuid","posix_geteuid","posix_seteuid","posix_getgid", "posix_setgid","posix_getegid","posix_setegid","posix_getgroups","posix_getlogin", "posix_getpgrp","posix_setsid","posix_setpgid","posix_getpgid","posix_getsid", "posix_uname","posix_times","posix_ctermid","posix_ttyname","posix_isatty", "posix_getcwd","posix_mkfifo","posix_mknod","posix_access","posix_getgrnam", "posix_getgrgid","posix_getpwnam","posix_getpwuid","posix_getrlimit", "posix_get_last_error","posix_errno","posix_strerror","posix_initgroups", "pspell_new","pspell_new_personal","pspell_new_config","pspell_check", "pspell_suggest","pspell_store_replacement","pspell_add_to_personal", "pspell_add_to_session","pspell_clear_session","pspell_save_wordlist", "pspell_config_create","pspell_config_runtogether","pspell_config_mode", "pspell_config_ignore","pspell_config_personal","pspell_config_dict_dir", "pspell_config_data_dir","pspell_config_repl","pspell_config_save_repl", "snmpget","snmpgetnext","snmpwalk","snmprealwalk","snmpwalkoid", "snmp_get_quick_print","snmp_set_quick_print","snmp_set_enum_print", "snmp_set_oid_output_format","snmp_set_oid_numeric_print","snmpset", "snmp2_get","snmp2_getnext","snmp2_walk","snmp2_real_walk","snmp2_set", "snmp3_get","snmp3_getnext","snmp3_walk","snmp3_real_walk","snmp3_set", "snmp_set_valueretrieval","snmp_get_valueretrieval","snmp_read_mib", "use_soap_error_handler","is_soap_fault","socket_create_pair","time_nanosleep", "time_sleep_until","strptime","php_ini_loaded_file","money_format","lcfirst", "nl_langinfo","str_getcsv","readlink","linkinfo","symlink","link","proc_nice", "atanh","asinh","acosh","expm1","log1p","inet_ntop","inet_pton","getopt", "sys_getloadavg","getrusage","quoted_printable_encode","forward_static_call", "forward_static_call_array","header_remove","parse_ini_string","gethostname", "dns_check_record","checkdnsrr","dns_get_mx","getmxrr","dns_get_record", "stream_context_get_params","stream_context_set_default","stream_socket_pair", "stream_supports_lock","stream_set_read_buffer","stream_resolve_include_path", "stream_is_local","fnmatch","chroot","lchown","lchgrp","realpath_cache_size", "realpath_cache_get","array_replace","array_replace_recursive","ftok","xmlrpc_encode", "xmlrpc_decode","xmlrpc_decode_request","xmlrpc_encode_request","xmlrpc_get_type", "xmlrpc_set_type","xmlrpc_is_fault","xmlrpc_server_create","xmlrpc_server_destroy", "xmlrpc_server_register_method","xmlrpc_server_call_method", "xmlrpc_parse_method_descriptions","xmlrpc_server_add_introspection_data", "xmlrpc_server_register_introspection_callback","zip_open","zip_close", "zip_read","zip_entry_open","zip_entry_close","zip_entry_read","zip_entry_filesize", "zip_entry_name","zip_entry_compressedsize","zip_entry_compressionmethod", "svn_checkout","svn_cat","svn_ls","svn_log","svn_auth_set_parameter", "svn_auth_get_parameter","svn_client_version","svn_config_ensure","svn_diff", "svn_cleanup","svn_revert","svn_resolved","svn_commit","svn_lock","svn_unlock", "svn_add","svn_status","svn_update","svn_import","svn_info","svn_export", "svn_copy","svn_switch","svn_blame","svn_delete","svn_mkdir","svn_move", "svn_proplist","svn_propget","svn_repos_create","svn_repos_recover", "svn_repos_hotcopy","svn_repos_open","svn_repos_fs", "svn_repos_fs_begin_txn_for_commit","svn_repos_fs_commit_txn", "svn_fs_revision_root","svn_fs_check_path","svn_fs_revision_prop", "svn_fs_dir_entries","svn_fs_node_created_rev","svn_fs_youngest_rev", "svn_fs_file_contents","svn_fs_file_length","svn_fs_txn_root","svn_fs_make_file", "svn_fs_make_dir","svn_fs_apply_text","svn_fs_copy","svn_fs_delete", "svn_fs_begin_txn2","svn_fs_is_dir","svn_fs_is_file","svn_fs_node_prop", "svn_fs_change_node_prop","svn_fs_contents_changed","svn_fs_props_changed", "svn_fs_abort_txn","sqlite_open","sqlite_popen","sqlite_close","sqlite_query", "sqlite_exec","sqlite_array_query","sqlite_single_query","sqlite_fetch_array", "sqlite_fetch_object","sqlite_fetch_single","sqlite_fetch_string", "sqlite_fetch_all","sqlite_current","sqlite_column","sqlite_libversion", "sqlite_libencoding","sqlite_changes","sqlite_last_insert_rowid", "sqlite_num_rows","sqlite_num_fields","sqlite_field_name","sqlite_seek", "sqlite_rewind","sqlite_next","sqlite_prev","sqlite_valid","sqlite_has_more", "sqlite_has_prev","sqlite_escape_string","sqlite_busy_timeout","sqlite_last_error", "sqlite_error_string","sqlite_unbuffered_query","sqlite_create_aggregate", "sqlite_create_function","sqlite_factory","sqlite_udf_encode_binary", "sqlite_udf_decode_binary","sqlite_fetch_column_types" ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-function"); }); // output of get_defined_constants(). Differs significantly from http://php.net/manual/en/reserved.constants.php [ "E_ERROR", "E_RECOVERABLE_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE", "E_STRICT", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR", "E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE", "E_ALL", "TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE", "PHP_VERSION", "PHP_OS", "PHP_SAPI", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR", "PHP_EXTENSION_DIR", "PHP_PREFIX", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR", "PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR", "PHP_CONFIG_FILE_PATH", "PHP_CONFIG_FILE_SCAN_DIR", "PHP_SHLIB_SUFFIX", "PHP_EOL", "PHP_EOL", "PHP_INT_MAX", "PHP_INT_SIZE", "PHP_OUTPUT_HANDLER_START", "PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END", "UPLOAD_ERR_OK", "UPLOAD_ERR_INI_SIZE", "UPLOAD_ERR_FORM_SIZE", "UPLOAD_ERR_PARTIAL", "UPLOAD_ERR_NO_FILE", "UPLOAD_ERR_NO_TMP_DIR", "UPLOAD_ERR_CANT_WRITE", "UPLOAD_ERR_EXTENSION", "CAL_GREGORIAN", "CAL_JULIAN", "CAL_JEWISH", "CAL_FRENCH", "CAL_NUM_CALS", "CAL_DOW_DAYNO", "CAL_DOW_SHORT", "CAL_DOW_LONG", "CAL_MONTH_GREGORIAN_SHORT", "CAL_MONTH_GREGORIAN_LONG", "CAL_MONTH_JULIAN_SHORT", "CAL_MONTH_JULIAN_LONG", "CAL_MONTH_JEWISH", "CAL_MONTH_FRENCH", "CAL_EASTER_DEFAULT", "CAL_EASTER_ROMAN", "CAL_EASTER_ALWAYS_GREGORIAN", "CAL_EASTER_ALWAYS_JULIAN", "CAL_JEWISH_ADD_ALAFIM_GERESH", "CAL_JEWISH_ADD_ALAFIM", "CAL_JEWISH_ADD_GERESHAYIM", "CLSCTX_INPROC_SERVER", "CLSCTX_INPROC_HANDLER", "CLSCTX_LOCAL_SERVER", "CLSCTX_REMOTE_SERVER", "CLSCTX_SERVER", "CLSCTX_ALL", "VT_NULL", "VT_EMPTY", "VT_UI1", "VT_I1", "VT_UI2", "VT_I2", "VT_UI4", "VT_I4", "VT_R4", "VT_R8", "VT_BOOL", "VT_ERROR", "VT_CY", "VT_DATE", "VT_BSTR", "VT_DECIMAL", "VT_UNKNOWN", "VT_DISPATCH", "VT_VARIANT", "VT_INT", "VT_UINT", "VT_ARRAY", "VT_BYREF", "CP_ACP", "CP_MACCP", "CP_OEMCP", "CP_UTF7", "CP_UTF8", "CP_SYMBOL", "CP_THREAD_ACP", "VARCMP_LT", "VARCMP_EQ", "VARCMP_GT", "VARCMP_NULL", "NORM_IGNORECASE", "NORM_IGNORENONSPACE", "NORM_IGNORESYMBOLS", "NORM_IGNOREWIDTH", "NORM_IGNOREKANATYPE", "DISP_E_DIVBYZERO", "DISP_E_OVERFLOW", "DISP_E_BADINDEX", "MK_E_UNAVAILABLE", "INPUT_POST", "INPUT_GET", "INPUT_COOKIE", "INPUT_ENV", "INPUT_SERVER", "INPUT_SESSION", "INPUT_REQUEST", "FILTER_FLAG_NONE", "FILTER_REQUIRE_SCALAR", "FILTER_REQUIRE_ARRAY", "FILTER_FORCE_ARRAY", "FILTER_NULL_ON_FAILURE", "FILTER_VALIDATE_INT", "FILTER_VALIDATE_BOOLEAN", "FILTER_VALIDATE_FLOAT", "FILTER_VALIDATE_REGEXP", "FILTER_VALIDATE_URL", "FILTER_VALIDATE_EMAIL", "FILTER_VALIDATE_IP", "FILTER_DEFAULT", "FILTER_UNSAFE_RAW", "FILTER_SANITIZE_STRING", "FILTER_SANITIZE_STRIPPED", "FILTER_SANITIZE_ENCODED", "FILTER_SANITIZE_SPECIAL_CHARS", "FILTER_SANITIZE_EMAIL", "FILTER_SANITIZE_URL", "FILTER_SANITIZE_NUMBER_INT", "FILTER_SANITIZE_NUMBER_FLOAT", "FILTER_SANITIZE_MAGIC_QUOTES", "FILTER_CALLBACK", "FILTER_FLAG_ALLOW_OCTAL", "FILTER_FLAG_ALLOW_HEX", "FILTER_FLAG_STRIP_LOW", "FILTER_FLAG_STRIP_HIGH", "FILTER_FLAG_ENCODE_LOW", "FILTER_FLAG_ENCODE_HIGH", "FILTER_FLAG_ENCODE_AMP", "FILTER_FLAG_NO_ENCODE_QUOTES", "FILTER_FLAG_EMPTY_STRING_NULL", "FILTER_FLAG_ALLOW_FRACTION", "FILTER_FLAG_ALLOW_THOUSAND", "FILTER_FLAG_ALLOW_SCIENTIFIC", "FILTER_FLAG_SCHEME_REQUIRED", "FILTER_FLAG_HOST_REQUIRED", "FILTER_FLAG_PATH_REQUIRED", "FILTER_FLAG_QUERY_REQUIRED", "FILTER_FLAG_IPV4", "FILTER_FLAG_IPV6", "FILTER_FLAG_NO_RES_RANGE", "FILTER_FLAG_NO_PRIV_RANGE", "FTP_ASCII", "FTP_TEXT", "FTP_BINARY", "FTP_IMAGE", "FTP_AUTORESUME", "FTP_TIMEOUT_SEC", "FTP_AUTOSEEK", "FTP_FAILED", "FTP_FINISHED", "FTP_MOREDATA", "HASH_HMAC", "ICONV_IMPL", "ICONV_VERSION", "ICONV_MIME_DECODE_STRICT", "ICONV_MIME_DECODE_CONTINUE_ON_ERROR", "ODBC_TYPE", "ODBC_BINMODE_PASSTHRU", "ODBC_BINMODE_RETURN", "ODBC_BINMODE_CONVERT", "SQL_ODBC_CURSORS", "SQL_CUR_USE_DRIVER", "SQL_CUR_USE_IF_NEEDED", "SQL_CUR_USE_ODBC", "SQL_CONCURRENCY", "SQL_CONCUR_READ_ONLY", "SQL_CONCUR_LOCK", "SQL_CONCUR_ROWVER", "SQL_CONCUR_VALUES", "SQL_CURSOR_TYPE", "SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC", "SQL_CURSOR_STATIC", "SQL_KEYSET_SIZE", "SQL_FETCH_FIRST", "SQL_FETCH_NEXT", "SQL_CHAR", "SQL_VARCHAR", "SQL_LONGVARCHAR", "SQL_DECIMAL", "SQL_NUMERIC", "SQL_BIT", "SQL_TINYINT", "SQL_SMALLINT", "SQL_INTEGER", "SQL_BIGINT", "SQL_REAL", "SQL_FLOAT", "SQL_DOUBLE", "SQL_BINARY", "SQL_VARBINARY", "SQL_LONGVARBINARY", "SQL_DATE", "SQL_TIME", "SQL_TIMESTAMP", "PREG_PATTERN_ORDER", "PREG_SET_ORDER", "PREG_OFFSET_CAPTURE", "PREG_SPLIT_NO_EMPTY", "PREG_SPLIT_DELIM_CAPTURE", "PREG_SPLIT_OFFSET_CAPTURE", "PREG_GREP_INVERT", "PREG_NO_ERROR", "PREG_INTERNAL_ERROR", "PREG_BACKTRACK_LIMIT_ERROR", "PREG_RECURSION_LIMIT_ERROR", "PREG_BAD_UTF8_ERROR", "DATE_ATOM", "DATE_COOKIE", "DATE_ISO8601", "DATE_RFC822", "DATE_RFC850", "DATE_RFC1036", "DATE_RFC1123", "DATE_RFC2822", "DATE_RFC3339", "DATE_RSS", "DATE_W3C", "SUNFUNCS_RET_TIMESTAMP", "SUNFUNCS_RET_STRING", "SUNFUNCS_RET_DOUBLE", "LIBXML_VERSION", "LIBXML_DOTTED_VERSION", "LIBXML_NOENT", "LIBXML_DTDLOAD", "LIBXML_DTDATTR", "LIBXML_DTDVALID", "LIBXML_NOERROR", "LIBXML_NOWARNING", "LIBXML_NOBLANKS", "LIBXML_XINCLUDE", "LIBXML_NSCLEAN", "LIBXML_NOCDATA", "LIBXML_NONET", "LIBXML_COMPACT", "LIBXML_NOXMLDECL", "LIBXML_NOEMPTYTAG", "LIBXML_ERR_NONE", "LIBXML_ERR_WARNING", "LIBXML_ERR_ERROR", "LIBXML_ERR_FATAL", "CONNECTION_ABORTED", "CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER", "INI_PERDIR", "INI_SYSTEM", "INI_ALL", "PHP_URL_SCHEME", "PHP_URL_HOST", "PHP_URL_PORT", "PHP_URL_USER", "PHP_URL_PASS", "PHP_URL_PATH", "PHP_URL_QUERY", "PHP_URL_FRAGMENT", "M_E", "M_LOG2E", "M_LOG10E", "M_LN2", "M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI", "M_SQRTPI", "M_2_SQRTPI", "M_LNPI", "M_EULER", "M_SQRT2", "M_SQRT1_2", "M_SQRT3", "INF", "NAN", "INFO_GENERAL", "INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES", "INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE", "INFO_ALL", "CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES", "CREDITS_DOCS", "CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL", "HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES", "ENT_NOQUOTES", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH", "PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION", "PATHINFO_FILENAME", "CHAR_MAX", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_ALL", "SEEK_SET", "SEEK_CUR", "SEEK_END", "LOCK_SH", "LOCK_EX", "LOCK_UN", "LOCK_NB", "STREAM_NOTIFY_CONNECT", "STREAM_NOTIFY_AUTH_REQUIRED", "STREAM_NOTIFY_AUTH_RESULT", "STREAM_NOTIFY_MIME_TYPE_IS", "STREAM_NOTIFY_FILE_SIZE_IS", "STREAM_NOTIFY_REDIRECTED", "STREAM_NOTIFY_PROGRESS", "STREAM_NOTIFY_FAILURE", "STREAM_NOTIFY_COMPLETED", "STREAM_NOTIFY_RESOLVE", "STREAM_NOTIFY_SEVERITY_INFO", "STREAM_NOTIFY_SEVERITY_WARN", "STREAM_NOTIFY_SEVERITY_ERR", "STREAM_FILTER_READ", "STREAM_FILTER_WRITE", "STREAM_FILTER_ALL", "STREAM_CLIENT_PERSISTENT", "STREAM_CLIENT_ASYNC_CONNECT", "STREAM_CLIENT_CONNECT", "STREAM_CRYPTO_METHOD_SSLv2_CLIENT", "STREAM_CRYPTO_METHOD_SSLv3_CLIENT", "STREAM_CRYPTO_METHOD_SSLv23_CLIENT", "STREAM_CRYPTO_METHOD_TLS_CLIENT", "STREAM_CRYPTO_METHOD_SSLv2_SERVER", "STREAM_CRYPTO_METHOD_SSLv3_SERVER", "STREAM_CRYPTO_METHOD_SSLv23_SERVER", "STREAM_CRYPTO_METHOD_TLS_SERVER", "STREAM_SHUT_RD", "STREAM_SHUT_WR", "STREAM_SHUT_RDWR", "STREAM_PF_INET", "STREAM_PF_INET6", "STREAM_PF_UNIX", "STREAM_IPPROTO_IP", "STREAM_IPPROTO_TCP", "STREAM_IPPROTO_UDP", "STREAM_IPPROTO_ICMP", "STREAM_IPPROTO_RAW", "STREAM_SOCK_STREAM", "STREAM_SOCK_DGRAM", "STREAM_SOCK_RAW", "STREAM_SOCK_SEQPACKET", "STREAM_SOCK_RDM", "STREAM_PEEK", "STREAM_OOB", "STREAM_SERVER_BIND", "STREAM_SERVER_LISTEN", "FILE_USE_INCLUDE_PATH", "FILE_IGNORE_NEW_LINES", "FILE_SKIP_EMPTY_LINES", "FILE_APPEND", "FILE_NO_DEFAULT_CONTEXT", "PSFS_PASS_ON", "PSFS_FEED_ME", "PSFS_ERR_FATAL", "PSFS_FLAG_NORMAL", "PSFS_FLAG_FLUSH_INC", "PSFS_FLAG_FLUSH_CLOSE", "CRYPT_SALT_LENGTH", "CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5", "CRYPT_BLOWFISH", "DIRECTORY_SEPARATOR", "PATH_SEPARATOR", "GLOB_BRACE", "GLOB_MARK", "GLOB_NOSORT", "GLOB_NOCHECK", "GLOB_NOESCAPE", "GLOB_ERR", "GLOB_ONLYDIR", "LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR", "LOG_WARNING", "LOG_NOTICE", "LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON", "LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON", "LOG_AUTHPRIV", "LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY", "LOG_NOWAIT", "LOG_PERROR", "EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME", "EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID", "EXTR_PREFIX_IF_EXISTS", "EXTR_IF_EXISTS", "EXTR_REFS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR", "SORT_NUMERIC", "SORT_STRING", "SORT_LOCALE_STRING", "CASE_LOWER", "CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE", "ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL", "STREAM_USE_PATH", "STREAM_IGNORE_URL", "STREAM_ENFORCE_SAFE_MODE", "STREAM_REPORT_ERRORS", "STREAM_MUST_SEEK", "STREAM_URL_STAT_LINK", "STREAM_URL_STAT_QUIET", "STREAM_MKDIR_RECURSIVE", "IMAGETYPE_GIF", "IMAGETYPE_JPEG", "IMAGETYPE_PNG", "IMAGETYPE_SWF", "IMAGETYPE_PSD", "IMAGETYPE_BMP", "IMAGETYPE_TIFF_II", "IMAGETYPE_TIFF_MM", "IMAGETYPE_JPC", "IMAGETYPE_JP2", "IMAGETYPE_JPX", "IMAGETYPE_JB2", "IMAGETYPE_SWC", "IMAGETYPE_IFF", "IMAGETYPE_WBMP", "IMAGETYPE_JPEG2000", "IMAGETYPE_XBM", "T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE", "T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "T_PLUS_EQUAL", "T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL", "T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL", "T_BOOLEAN_OR", "T_BOOLEAN_AND", "T_IS_EQUAL", "T_IS_NOT_EQUAL", "T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "T_IS_SMALLER_OR_EQUAL", "T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "T_INC", "T_DEC", "T_INT_CAST", "T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST", "T_BOOL_CAST", "T_UNSET_CAST", "T_NEW", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE", "T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME", "T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_CHARACTER", "T_BAD_CHARACTER", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING", "T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH", "T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH", "T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_FUNCTION", "T_CONST", "T_RETURN", "T_USE", "T_GLOBAL", "T_STATIC", "T_VAR", "T_UNSET", "T_ISSET", "T_EMPTY", "T_CLASS", "T_EXTENDS", "T_INTERFACE", "T_IMPLEMENTS", "T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CLASS_C", "T_FUNC_C", "T_METHOD_C", "T_LINE", "T_FILE", "T_COMMENT", "T_DOC_COMMENT", "T_OPEN_TAG", "T_OPEN_TAG_WITH_ECHO", "T_CLOSE_TAG", "T_WHITESPACE", "T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES", "T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_DOUBLE_COLON", "T_ABSTRACT", "T_CATCH", "T_FINAL", "T_INSTANCEOF", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC", "T_THROW", "T_TRY", "T_CLONE", "T_HALT_COMPILER", "FORCE_GZIP", "FORCE_DEFLATE", "XML_ELEMENT_NODE", "XML_ATTRIBUTE_NODE", "XML_TEXT_NODE", "XML_CDATA_SECTION_NODE", "XML_ENTITY_REF_NODE", "XML_ENTITY_NODE", "XML_PI_NODE", "XML_COMMENT_NODE", "XML_DOCUMENT_NODE", "XML_DOCUMENT_TYPE_NODE", "XML_DOCUMENT_FRAG_NODE", "XML_NOTATION_NODE", "XML_HTML_DOCUMENT_NODE", "XML_DTD_NODE", "XML_ELEMENT_DECL_NODE", "XML_ATTRIBUTE_DECL_NODE", "XML_ENTITY_DECL_NODE", "XML_NAMESPACE_DECL_NODE", "XML_LOCAL_NAMESPACE", "XML_ATTRIBUTE_CDATA", "XML_ATTRIBUTE_ID", "XML_ATTRIBUTE_IDREF", "XML_ATTRIBUTE_IDREFS", "XML_ATTRIBUTE_ENTITY", "XML_ATTRIBUTE_NMTOKEN", "XML_ATTRIBUTE_NMTOKENS", "XML_ATTRIBUTE_ENUMERATION", "XML_ATTRIBUTE_NOTATION", "DOM_PHP_ERR", "DOM_INDEX_SIZE_ERR", "DOMSTRING_SIZE_ERR", "DOM_HIERARCHY_REQUEST_ERR", "DOM_WRONG_DOCUMENT_ERR", "DOM_INVALID_CHARACTER_ERR", "DOM_NO_DATA_ALLOWED_ERR", "DOM_NO_MODIFICATION_ALLOWED_ERR", "DOM_NOT_FOUND_ERR", "DOM_NOT_SUPPORTED_ERR", "DOM_INUSE_ATTRIBUTE_ERR", "DOM_INVALID_STATE_ERR", "DOM_SYNTAX_ERR", "DOM_INVALID_MODIFICATION_ERR", "DOM_NAMESPACE_ERR", "DOM_INVALID_ACCESS_ERR", "DOM_VALIDATION_ERR", "XML_ERROR_NONE", "XML_ERROR_NO_MEMORY", "XML_ERROR_SYNTAX", "XML_ERROR_NO_ELEMENTS", "XML_ERROR_INVALID_TOKEN", "XML_ERROR_UNCLOSED_TOKEN", "XML_ERROR_PARTIAL_CHAR", "XML_ERROR_TAG_MISMATCH", "XML_ERROR_DUPLICATE_ATTRIBUTE", "XML_ERROR_JUNK_AFTER_DOC_ELEMENT", "XML_ERROR_PARAM_ENTITY_REF", "XML_ERROR_UNDEFINED_ENTITY", "XML_ERROR_RECURSIVE_ENTITY_REF", "XML_ERROR_ASYNC_ENTITY", "XML_ERROR_BAD_CHAR_REF", "XML_ERROR_BINARY_ENTITY_REF", "XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", "XML_ERROR_MISPLACED_XML_PI", "XML_ERROR_UNKNOWN_ENCODING", "XML_ERROR_INCORRECT_ENCODING", "XML_ERROR_UNCLOSED_CDATA_SECTION", "XML_ERROR_EXTERNAL_ENTITY_HANDLING", "XML_OPTION_CASE_FOLDING", "XML_OPTION_TARGET_ENCODING", "XML_OPTION_SKIP_TAGSTART", "XML_OPTION_SKIP_WHITE", "XML_SAX_IMPL", "IMG_GIF", "IMG_JPG", "IMG_JPEG", "IMG_PNG", "IMG_WBMP", "IMG_XPM", "IMG_COLOR_TILED", "IMG_COLOR_STYLED", "IMG_COLOR_BRUSHED", "IMG_COLOR_STYLEDBRUSHED", "IMG_COLOR_TRANSPARENT", "IMG_ARC_ROUNDED", "IMG_ARC_PIE", "IMG_ARC_CHORD", "IMG_ARC_NOFILL", "IMG_ARC_EDGED", "IMG_GD2_RAW", "IMG_GD2_COMPRESSED", "IMG_EFFECT_REPLACE", "IMG_EFFECT_ALPHABLEND", "IMG_EFFECT_NORMAL", "IMG_EFFECT_OVERLAY", "GD_BUNDLED", "IMG_FILTER_NEGATE", "IMG_FILTER_GRAYSCALE", "IMG_FILTER_BRIGHTNESS", "IMG_FILTER_CONTRAST", "IMG_FILTER_COLORIZE", "IMG_FILTER_EDGEDETECT", "IMG_FILTER_GAUSSIAN_BLUR", "IMG_FILTER_SELECTIVE_BLUR", "IMG_FILTER_EMBOSS", "IMG_FILTER_MEAN_REMOVAL", "IMG_FILTER_SMOOTH", "PNG_NO_FILTER", "PNG_FILTER_NONE", "PNG_FILTER_SUB", "PNG_FILTER_UP", "PNG_FILTER_AVG", "PNG_FILTER_PAETH", "PNG_ALL_FILTERS", "MB_OVERLOAD_MAIL", "MB_OVERLOAD_STRING", "MB_OVERLOAD_REGEX", "MB_CASE_UPPER", "MB_CASE_LOWER", "MB_CASE_TITLE", "MYSQL_ASSOC", "MYSQL_NUM", "MYSQL_BOTH", "MYSQL_CLIENT_COMPRESS", "MYSQL_CLIENT_SSL", "MYSQL_CLIENT_INTERACTIVE", "MYSQL_CLIENT_IGNORE_SPACE", "MYSQLI_READ_DEFAULT_GROUP", "MYSQLI_READ_DEFAULT_FILE", "MYSQLI_OPT_CONNECT_TIMEOUT", "MYSQLI_OPT_LOCAL_INFILE", "MYSQLI_INIT_COMMAND", "MYSQLI_CLIENT_SSL", "MYSQLI_CLIENT_COMPRESS", "MYSQLI_CLIENT_INTERACTIVE", "MYSQLI_CLIENT_IGNORE_SPACE", "MYSQLI_CLIENT_NO_SCHEMA", "MYSQLI_CLIENT_FOUND_ROWS", "MYSQLI_STORE_RESULT", "MYSQLI_USE_RESULT", "MYSQLI_ASSOC", "MYSQLI_NUM", "MYSQLI_BOTH", "MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH", "MYSQLI_STMT_ATTR_CURSOR_TYPE", "MYSQLI_CURSOR_TYPE_NO_CURSOR", "MYSQLI_CURSOR_TYPE_READ_ONLY", "MYSQLI_CURSOR_TYPE_FOR_UPDATE", "MYSQLI_CURSOR_TYPE_SCROLLABLE", "MYSQLI_STMT_ATTR_PREFETCH_ROWS", "MYSQLI_NOT_NULL_FLAG", "MYSQLI_PRI_KEY_FLAG", "MYSQLI_UNIQUE_KEY_FLAG", "MYSQLI_MULTIPLE_KEY_FLAG", "MYSQLI_BLOB_FLAG", "MYSQLI_UNSIGNED_FLAG", "MYSQLI_ZEROFILL_FLAG", "MYSQLI_AUTO_INCREMENT_FLAG", "MYSQLI_TIMESTAMP_FLAG", "MYSQLI_SET_FLAG", "MYSQLI_NUM_FLAG", "MYSQLI_PART_KEY_FLAG", "MYSQLI_GROUP_FLAG", "MYSQLI_TYPE_DECIMAL", "MYSQLI_TYPE_TINY", "MYSQLI_TYPE_SHORT", "MYSQLI_TYPE_LONG", "MYSQLI_TYPE_FLOAT", "MYSQLI_TYPE_DOUBLE", "MYSQLI_TYPE_NULL", "MYSQLI_TYPE_TIMESTAMP", "MYSQLI_TYPE_LONGLONG", "MYSQLI_TYPE_INT24", "MYSQLI_TYPE_DATE", "MYSQLI_TYPE_TIME", "MYSQLI_TYPE_DATETIME", "MYSQLI_TYPE_YEAR", "MYSQLI_TYPE_NEWDATE", "MYSQLI_TYPE_ENUM", "MYSQLI_TYPE_SET", "MYSQLI_TYPE_TINY_BLOB", "MYSQLI_TYPE_MEDIUM_BLOB", "MYSQLI_TYPE_LONG_BLOB", "MYSQLI_TYPE_BLOB", "MYSQLI_TYPE_VAR_STRING", "MYSQLI_TYPE_STRING", "MYSQLI_TYPE_CHAR", "MYSQLI_TYPE_INTERVAL", "MYSQLI_TYPE_GEOMETRY", "MYSQLI_TYPE_NEWDECIMAL", "MYSQLI_TYPE_BIT", "MYSQLI_RPL_MASTER", "MYSQLI_RPL_SLAVE", "MYSQLI_RPL_ADMIN", "MYSQLI_NO_DATA", "MYSQLI_DATA_TRUNCATED", "MYSQLI_REPORT_INDEX", "MYSQLI_REPORT_ERROR", "MYSQLI_REPORT_STRICT", "MYSQLI_REPORT_ALL", "MYSQLI_REPORT_OFF", "AF_UNIX", "AF_INET", "AF_INET6", "SOCK_STREAM", "SOCK_DGRAM", "SOCK_RAW", "SOCK_SEQPACKET", "SOCK_RDM", "MSG_OOB", "MSG_WAITALL", "MSG_PEEK", "MSG_DONTROUTE", "SO_DEBUG", "SO_REUSEADDR", "SO_KEEPALIVE", "SO_DONTROUTE", "SO_LINGER", "SO_BROADCAST", "SO_OOBINLINE", "SO_SNDBUF", "SO_RCVBUF", "SO_SNDLOWAT", "SO_RCVLOWAT", "SO_SNDTIMEO", "SO_RCVTIMEO", "SO_TYPE", "SO_ERROR", "SOL_SOCKET", "SOMAXCONN", "PHP_NORMAL_READ", "PHP_BINARY_READ", "SOCKET_EINTR", "SOCKET_EBADF", "SOCKET_EACCES", "SOCKET_EFAULT", "SOCKET_EINVAL", "SOCKET_EMFILE", "SOCKET_EWOULDBLOCK", "SOCKET_EINPROGRESS", "SOCKET_EALREADY", "SOCKET_ENOTSOCK", "SOCKET_EDESTADDRREQ", "SOCKET_EMSGSIZE", "SOCKET_EPROTOTYPE", "SOCKET_ENOPROTOOPT", "SOCKET_EPROTONOSUPPORT", "SOCKET_ESOCKTNOSUPPORT", "SOCKET_EOPNOTSUPP", "SOCKET_EPFNOSUPPORT", "SOCKET_EAFNOSUPPORT", "SOCKET_EADDRINUSE", "SOCKET_EADDRNOTAVAIL", "SOCKET_ENETDOWN", "SOCKET_ENETUNREACH", "SOCKET_ENETRESET", "SOCKET_ECONNABORTED", "SOCKET_ECONNRESET", "SOCKET_ENOBUFS", "SOCKET_EISCONN", "SOCKET_ENOTCONN", "SOCKET_ESHUTDOWN", "SOCKET_ETOOMANYREFS", "SOCKET_ETIMEDOUT", "SOCKET_ECONNREFUSED", "SOCKET_ELOOP", "SOCKET_ENAMETOOLONG", "SOCKET_EHOSTDOWN", "SOCKET_EHOSTUNREACH", "SOCKET_ENOTEMPTY", "SOCKET_EPROCLIM", "SOCKET_EUSERS", "SOCKET_EDQUOT", "SOCKET_ESTALE", "SOCKET_EREMOTE", "SOCKET_EDISCON", "SOCKET_SYSNOTREADY", "SOCKET_VERNOTSUPPORTED", "SOCKET_NOTINITIALISED", "SOCKET_HOST_NOT_FOUND", "SOCKET_TRY_AGAIN", "SOCKET_NO_RECOVERY", "SOCKET_NO_DATA", "SOCKET_NO_ADDRESS", "SOL_TCP", "SOL_UDP", "EACCELERATOR_VERSION", "EACCELERATOR_SHM_AND_DISK", "EACCELERATOR_SHM", "EACCELERATOR_SHM_ONLY", "EACCELERATOR_DISK_ONLY", "EACCELERATOR_NONE", "XDEBUG_TRACE_APPEND", "XDEBUG_TRACE_COMPUTERIZED", "XDEBUG_TRACE_HTML", "XDEBUG_CC_UNUSED", "XDEBUG_CC_DEAD_CODE", "STDIN", "STDOUT", "STDERR", "DNS_HINFO", "DNS_PTR", "SQLITE_EMPTY", "SVN_SHOW_UPDATES", "SVN_NO_IGNORE", "MSG_EOF", "DNS_MX", "GD_EXTRA_VERSION", "PHP_VERSION_ID", "SQLITE_OK", "LIBXML_LOADED_VERSION", "RADIXCHAR", "OPENSSL_VERSION_TEXT", "OPENSSL_VERSION_NUMBER", "PCRE_VERSION", "CURLOPT_FILE", "CURLOPT_INFILE", "CURLOPT_URL", "CURLOPT_PROXY", "CURLE_FUNCTION_NOT_FOUND", "SOCKET_ENOMSG", "CURLOPT_HTTPHEADER", "SOCKET_EIDRM", "CURLOPT_PROGRESSFUNCTION", "SOCKET_ECHRNG", "SOCKET_EL2NSYNC", "SOCKET_EL3HLT", "SOCKET_EL3RST", "SOCKET_ELNRNG", "SOCKET_ENOCSI", "SOCKET_EL2HLT", "SOCKET_EBADE", "SOCKET_EXFULL", "CURLOPT_USERPWD", "CURLOPT_PROXYUSERPWD", "CURLOPT_RANGE", "CURLOPT_TIMEOUT_MS", "CURLOPT_POSTFIELDS", "CURLOPT_REFERER", "CURLOPT_USERAGENT", "CURLOPT_FTPPORT", "SOCKET_ERESTART", "SQLITE_CONSTRAINT", "SQLITE_MISMATCH", "SQLITE_MISUSE", "CURLOPT_COOKIE", "CURLE_SSL_CERTPROBLEM", "CURLOPT_SSLCERT", "CURLOPT_KEYPASSWD", "CURLOPT_WRITEHEADER", "CURLOPT_SSL_VERIFYHOST", "CURLOPT_COOKIEFILE", "CURLE_HTTP_RANGE_ERROR", "CURLE_HTTP_POST_ERROR", "CURLOPT_CUSTOMREQUEST", "CURLOPT_STDERR", "SOCKET_EBADR", "CURLOPT_RETURNTRANSFER", "CURLOPT_QUOTE", "CURLOPT_POSTQUOTE", "CURLOPT_INTERFACE", "CURLOPT_KRB4LEVEL", "SOCKET_ENODATA", "SOCKET_ESRMNT", "CURLOPT_WRITEFUNCTION", "CURLOPT_READFUNCTION", "CURLOPT_HEADERFUNCTION", "SOCKET_EADV", "SOCKET_EPROTO", "SOCKET_EMULTIHOP", "SOCKET_EBADMSG", "CURLOPT_FORBID_REUSE", "CURLOPT_RANDOM_FILE", "CURLOPT_EGDSOCKET", "SOCKET_EREMCHG", "CURLOPT_CONNECTTIMEOUT_MS", "CURLOPT_CAINFO", "CURLOPT_CAPATH", "CURLOPT_COOKIEJAR", "CURLOPT_SSL_CIPHER_LIST", "CURLOPT_BINARYTRANSFER", "SQLITE_DONE", "CURLOPT_HTTP_VERSION", "CURLOPT_SSLKEY", "CURLOPT_SSLKEYTYPE", "CURLOPT_SSLENGINE", "CURLOPT_SSLCERTTYPE", "CURLE_OUT_OF_MEMORY", "CURLOPT_ENCODING", "CURLE_SSL_CIPHER", "SOCKET_EREMOTEIO", "CURLOPT_HTTP200ALIASES", "CURLAUTH_ANY", "CURLAUTH_ANYSAFE", "CURLOPT_PRIVATE", "CURLINFO_EFFECTIVE_URL", "CURLINFO_HTTP_CODE", "CURLINFO_HEADER_SIZE", "CURLINFO_REQUEST_SIZE", "CURLINFO_TOTAL_TIME", "CURLINFO_NAMELOOKUP_TIME", "CURLINFO_CONNECT_TIME", "CURLINFO_PRETRANSFER_TIME", "CURLINFO_SIZE_UPLOAD", "CURLINFO_SIZE_DOWNLOAD", "CURLINFO_SPEED_DOWNLOAD", "CURLINFO_SPEED_UPLOAD", "CURLINFO_FILETIME", "CURLINFO_SSL_VERIFYRESULT", "CURLINFO_CONTENT_LENGTH_DOWNLOAD", "CURLINFO_CONTENT_LENGTH_UPLOAD", "CURLINFO_STARTTRANSFER_TIME", "CURLINFO_CONTENT_TYPE", "CURLINFO_REDIRECT_TIME", "CURLINFO_REDIRECT_COUNT", "CURLINFO_PRIVATE", "CURLINFO_CERTINFO", "SQLITE_PROTOCOL", "SQLITE_SCHEMA", "SQLITE_TOOBIG", "SQLITE_NOLFS", "SQLITE_AUTH", "SQLITE_FORMAT", "SOCKET_ENOTTY", "SQLITE_NOTADB", "SOCKET_ENOSPC", "SOCKET_ESPIPE", "SOCKET_EROFS", "SOCKET_EMLINK", "GD_RELEASE_VERSION", "SOCKET_ENOLCK", "SOCKET_ENOSYS", "SOCKET_EUNATCH", "SOCKET_ENOANO", "SOCKET_EBADRQC", "SOCKET_EBADSLT", "SOCKET_ENOSTR", "SOCKET_ETIME", "SOCKET_ENOSR", "SVN_REVISION_HEAD", "XSD_ENTITY", "XSD_NOTATION", "CURLOPT_CERTINFO", "CURLOPT_POSTREDIR", "CURLOPT_SSH_AUTH_TYPES", "CURLOPT_SSH_PUBLIC_KEYFILE", "CURLOPT_SSH_PRIVATE_KEYFILE", "CURLOPT_SSH_HOST_PUBLIC_KEY_MD5", "CURLE_SSH", "CURLOPT_REDIR_PROTOCOLS", "CURLOPT_PROTOCOLS", "XSD_NONNEGATIVEINTEGER", "XSD_BYTE","DNS_SRV","DNS_A6", "DNS_NAPTR", "DNS_AAAA", "FILTER_SANITIZE_FULL_SPECIAL_CHARS", "ABDAY_1", "SVN_REVISION_UNSPECIFIED", "SVN_REVISION_BASE", "SVN_REVISION_COMMITTED", "SVN_REVISION_PREV", "GD_VERSION", "MCRYPT_TRIPLEDES", "MCRYPT_ARCFOUR_IV", "MCRYPT_ARCFOUR", "MCRYPT_BLOWFISH", "MCRYPT_BLOWFISH_COMPAT", "MCRYPT_CAST_128", "MCRYPT_CAST_256", "MCRYPT_ENIGNA", "MCRYPT_DES", "MCRYPT_GOST", "MCRYPT_LOKI97", "MCRYPT_PANAMA", "MCRYPT_RC2", "MCRYPT_RIJNDAEL_128", "MCRYPT_RIJNDAEL_192", "MCRYPT_RIJNDAEL_256", "MCRYPT_SAFER64", "MCRYPT_SAFER128","MCRYPT_SAFERPLUS", "MCRYPT_SERPENT", "MCRYPT_THREEWAY", "MCRYPT_TWOFISH", "MCRYPT_WAKE", "MCRYPT_XTEA", "MCRYPT_IDEA", "MCRYPT_MARS", "MCRYPT_RC6", "MCRYPT_SKIPJACK", "MCRYPT_MODE_CBC", "MCRYPT_MODE_CFB", "MCRYPT_MODE_ECB", "MCRYPT_MODE_NOFB", "MCRYPT_MODE_OFB", "MCRYPT_MODE_STREAM", "CL_EXPUNGE", "SQLITE_ROW", "POSIX_S_IFBLK", "POSIX_S_IFSOCK", "XSD_IDREF", "ABDAY_2", "ABDAY_3", "ABDAY_4", "ABDAY_5", "ABDAY_6", "ABDAY_7", "DAY_1", "DAY_2", "DAY_3", "DAY_4", "DAY_5", "DAY_6", "DAY_7", "ABMON_1", "ABMON_2", "ABMON_3", "ABMON_4", "ABMON_5", "ABMON_6", "ABMON_7","ABMON_8", "ABMON_9", "ABMON_10", "ABMON_11", "ABMON_12", "MON_1", "MON_2", "MON_3", "MON_4", "MON_5", "MON_6", "MON_7", "MON_8", "MON_9", "MON_10", "MON_11", "MON_12", "AM_STR", "PM_STR", "D_T_FMT", "D_FMT", "T_FMT", "T_FMT_AMPM", "ERA", "ERA_D_T_FMT", "ERA_D_FMT", "ERA_T_FMT", "ALT_DIGITS", "CRNCYSTR", "THOUSEP", "YESEXPR", "NOEXPR", "SOCKET_ENOMEDIUM", "GLOB_AVAILABLE_FLAGS", "XSD_SHORT", "XSD_NMTOKENS", "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7", "DNS_ANY", "DNS_ALL", "SOCKET_ENOLINK", "SOCKET_ECOMM", "SOAP_FUNCTIONS_ALL", "UNKNOWN_TYPE", "XSD_BASE64BINARY", "XSD_ANYURI", "XSD_QNAME", "SOCKET_EISNAM", "SOCKET_EMEDIUMTYPE", "XSD_NCNAME", "XSD_ID", "XSD_ENTITIES", "XSD_INTEGER", "XSD_NONPOSITIVEINTEGER", "XSD_NEGATIVEINTEGER", "XSD_LONG", "XSD_INT", "XSD_UNSIGNEDLONG", "XSD_UNSIGNEDINT", "XSD_UNSIGNEDSHORT", "XSD_UNSIGNEDBYTE", "XSD_POSITIVEINTEGER", "XSD_ANYTYPE", "XSD_ANYXML", "APACHE_MAP", "XSD_1999_TIMEINSTANT", "XSD_NAMESPACE", "XSD_1999_NAMESPACE", "SOCKET_ENOTUNIQ", "SOCKET_EBADFD", "SOCKET_ESTRPIPE", "T_GOTO", "T_NAMESPACE", "T_NS_C", "T_DIR", "T_NS_SEPARATOR", "LIBXSLT_VERSION","LIBEXSLT_DOTTED_VERSION", "LIBEXSLT_VERSION", "SVN_AUTH_PARAM_DEFAULT_USERNAME", "SVN_AUTH_PARAM_DEFAULT_PASSWORD", "SVN_AUTH_PARAM_NON_INTERACTIVE", "SVN_AUTH_PARAM_DONT_STORE_PASSWORDS", "SVN_AUTH_PARAM_NO_AUTH_CACHE", "SVN_AUTH_PARAM_SSL_SERVER_FAILURES", "SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO", "SVN_AUTH_PARAM_CONFIG", "SVN_AUTH_PARAM_SERVER_GROUP", "SVN_AUTH_PARAM_CONFIG_DIR", "PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS", "SVN_FS_CONFIG_FS_TYPE", "SVN_FS_TYPE_BDB", "SVN_FS_TYPE_FSFS", "SVN_PROP_REVISION_DATE", "SVN_PROP_REVISION_ORIG_DATE", "SVN_PROP_REVISION_AUTHOR", "SVN_PROP_REVISION_LOG" ].forEach(function(element, index, array) { result[element] = token("atom", "php-predefined-constant"); }); // PHP declared classes - output of get_declared_classes(). Differs from http://php.net/manual/en/reserved.classes.php [ "stdClass", "Exception", "ErrorException", "COMPersistHelper", "com_exception", "com_safearray_proxy", "variant", "com", "dotnet", "ReflectionException", "Reflection", "ReflectionFunctionAbstract", "ReflectionFunction", "ReflectionParameter", "ReflectionMethod", "ReflectionClass", "ReflectionObject", "ReflectionProperty", "ReflectionExtension", "DateTime", "DateTimeZone", "LibXMLError", "__PHP_Incomplete_Class", "php_user_filter", "Directory", "SimpleXMLElement", "DOMException", "DOMStringList", "DOMNameList", "DOMImplementationList", "DOMImplementationSource", "DOMImplementation", "DOMNode", "DOMNameSpaceNode", "DOMDocumentFragment", "DOMDocument", "DOMNodeList", "DOMNamedNodeMap", "DOMCharacterData", "DOMAttr", "DOMElement", "DOMText", "DOMComment", "DOMTypeinfo", "DOMUserDataHandler", "DOMDomError", "DOMErrorHandler", "DOMLocator", "DOMConfiguration", "DOMCdataSection", "DOMDocumentType", "DOMNotation", "DOMEntity", "DOMEntityReference", "DOMProcessingInstruction", "DOMStringExtend", "DOMXPath", "RecursiveIteratorIterator", "IteratorIterator", "FilterIterator", "RecursiveFilterIterator", "ParentIterator", "LimitIterator", "CachingIterator", "RecursiveCachingIterator", "NoRewindIterator", "AppendIterator", "InfiniteIterator", "RegexIterator", "RecursiveRegexIterator", "EmptyIterator", "ArrayObject", "ArrayIterator", "RecursiveArrayIterator", "SplFileInfo", "DirectoryIterator", "RecursiveDirectoryIterator", "SplFileObject", "SplTempFileObject", "SimpleXMLIterator", "LogicException", "BadFunctionCallException", "BadMethodCallException", "DomainException", "InvalidArgumentException", "LengthException", "OutOfRangeException", "RuntimeException", "OutOfBoundsException", "OverflowException", "RangeException", "UnderflowException", "UnexpectedValueException", "SplObjectStorage", "XMLReader", "XMLWriter", "mysqli_sql_exception", "mysqli_driver", "mysqli", "mysqli_warning", "mysqli_result", "mysqli_stmt", "PDOException", "PDO", "PDOStatement", "PDORow","Closure", "DateInterval", "DatePeriod", "FilesystemIterator", "GlobIterator", "MultipleIterator", "RecursiveTreeIterator", "SoapClient", "SoapFault", "SoapHeader", "SoapParam", "SoapServer", "SoapVar", "SplDoublyLinkedList", "SplFixedArray", "SplHeap", "SplMaxHeap", "SplMinHeap", "SplPriorityQueue", "SplQueue", "SplStack", "SQLite3", "SQLite3Result", "SQLite3Stmt", "SQLiteDatabase", "SQLiteException", "SQLiteResult", "SQLiteUnbuffered", "Svn", "SvnNode", "SvnWc", "SvnWcSchedule", "XSLTProcessor", "ZipArchive", ].forEach(function(element, index, array) { result[element] = token("t_string", "php-predefined-class"); }); return result; }(); // Helper regexps var isOperatorChar = /[+*&%\/=<>!?.|^@-]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_\\]/; // Wrapper around phpToken that helps maintain parser state (whether // we are inside of a multi-line comment) function phpTokenState(inside) { return function(source, setState) { var newInside = inside; var type = phpToken(inside, source, function(c) {newInside = c;}); if (newInside != inside) setState(phpTokenState(newInside)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through phpTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function phpToken(inside, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "php-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "php-atom"}; } // Read a word and look it up in the keywords array. If found, it's a // keyword of that type; otherwise it's a PHP T_STRING. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; // since we called get(), tokenize::take won't get() anything. Thus, we must set token.content return known ? {type: known.type, style: known.style, content: word} : {type: "t_string", style: "php-t_string", content: word}; } function readVariable() { source.nextWhileMatches(isWordChar); var word = source.get(); // in PHP, '$this' is a reserved word, but 'this' isn't. You can have function this() {...} if (word == "$this") return {type: "variable", style: "php-keyword", content: word}; else return {type: "variable", style: "php-variable", content: word}; } // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while(!source.endOfLine()){ var next = source.next(); if (next == end && !escaped) return false; escaped = next == "\\" && !escaped; } return escaped; } function readSingleLineComment() { // read until the end of the line or until ?>, which terminates single-line comments // `<?php echo 1; // comment ?> foo` will display "1 foo" while(!source.lookAhead("?>") && !source.endOfLine()) source.next(); return {type: "comment", style: "php-comment"}; } /* For multi-line comments, we want to return a comment token for every line of the comment, but we also want to return the newlines in them as regular newline tokens. We therefore need to save a state variable ("inside") to indicate whether we are inside a multi-line comment. */ function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "php-comment"}; } // similar to readMultilineComment and nextUntilUnescaped // unlike comments, strings are not stopped by ?> function readMultilineString(start){ var newInside = start; var escaped = false; while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == start && !escaped){ newInside = null; // we're outside of the string now break; } escaped = (next == "\\" && !escaped); } setInside(newInside); return { type: newInside == null? "string" : "string_not_terminated", style: (start == "'"? "php-string-single-quoted" : "php-string-double-quoted") }; } // http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc // See also 'nowdoc' on the page. Heredocs are not interrupted by the '?>' token. function readHeredoc(identifier){ var token = {}; if (identifier == "<<<") { // on our first invocation after reading the <<<, we must determine the closing identifier if (source.equals("'")) { // nowdoc source.nextWhileMatches(isWordChar); identifier = "'" + source.get() + "'"; source.next(); // consume the closing "'" } else if (source.matches(/[A-Za-z_]/)) { // heredoc source.nextWhileMatches(isWordChar); identifier = source.get(); } else { // syntax error setInside(null); return { type: "error", style: "syntax-error" }; } setInside(identifier); token.type = "string_not_terminated"; token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; token.content = identifier; } else { token.style = identifier.charAt(0) == "'"? "php-string-single-quoted" : "php-string-double-quoted"; // consume a line of heredoc and check if it equals the closing identifier plus an optional semicolon if (source.lookAhead(identifier, true) && (source.lookAhead(";\n") || source.endOfLine())) { // the closing identifier can only appear at the beginning of the line // note that even whitespace after the ";" is forbidden by the PHP heredoc syntax token.type = "string"; token.content = source.get(); // don't get the ";" if there is one setInside(null); } else { token.type = "string_not_terminated"; source.nextWhileMatches(/[^\n]/); token.content = source.get(); } } return token; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "php-operator"}; } function readStringSingleQuoted() { var endBackSlash = nextUntilUnescaped(source, "'", false); setInside(endBackSlash ? "'" : null); return {type: "string", style: "php-string-single-quoted"}; } function readStringDoubleQuoted() { var endBackSlash = nextUntilUnescaped(source, "\"", false); setInside(endBackSlash ? "\"": null); return {type: "string", style: "php-string-double-quoted"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. switch (inside) { case null: case false: break; case "'": case "\"": return readMultilineString(inside); case "/*": return readMultilineComment(source.next()); default: return readHeredoc(inside); } var ch = source.next(); if (ch == "'" || ch == "\"") return readMultilineString(ch); else if (ch == "#") return readSingleLineComment(); else if (ch == "$") return readVariable(); else if (ch == ":" && source.equals(":")) { source.next(); // the T_DOUBLE_COLON can only follow a T_STRING (class name) return {type: "t_double_colon", style: "php-operator"}; } // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;:]/.test(ch)) { return {type: ch, style: "php-punctuation"}; } else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/") { if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) return readSingleLineComment(); else return readOperator(); } else if (ch == "<") { if (source.lookAhead("<<", true)) { setInside("<<<"); return {type: "<<<", style: "php-punctuation"}; } else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || phpTokenState(false, true)); }; })();
JavaScript
/* Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed by Yahoo! Inc. under the BSD (revised) open source license @author Dan Vlad Dascalescu <dandv@yahoo-inc.com> Based on parsehtmlmixed.js by Marijn Haverbeke. */ var PHPHTMLMixedParser = Editor.Parser = (function() { var processingInstructions = ["<?php"]; if (!(PHPParser && CSSParser && JSParser && XMLParser)) throw new Error("PHP, CSS, JS, and XML parsers must be loaded for PHP+HTML mixed mode to work."); XMLParser.configure({useHTMLKludges: true}); function parseMixed(stream) { var htmlParser = XMLParser.make(stream), localParser = null, inTag = false, lastAtt = null, phpParserState = null; var iter = {next: top, copy: copy}; function top() { var token = htmlParser.next(); if (token.content == "<") inTag = true; else if (token.style == "xml-tagname" && inTag === true) inTag = token.content.toLowerCase(); else if (token.style == "xml-attname") lastAtt = token.content; else if (token.type == "xml-processing") { // see if this opens a PHP block for (var i = 0; i < processingInstructions.length; i++) if (processingInstructions[i] == token.content) { iter.next = local(PHPParser, "?>"); break; } } else if (token.style == "xml-attribute" && token.content == "\"php\"" && inTag == "script" && lastAtt == "language") inTag = "script/php"; // "xml-processing" tokens are ignored, because they should be handled by a specific local parser else if (token.content == ">") { if (inTag == "script/php") iter.next = local(PHPParser, "</script>"); else if (inTag == "script") iter.next = local(JSParser, "</script"); else if (inTag == "style") iter.next = local(CSSParser, "</style"); lastAtt = null; inTag = false; } return token; } function local(parser, tag) { var baseIndent = htmlParser.indentation(); if (parser == PHPParser && phpParserState) localParser = phpParserState(stream); else localParser = parser.make(stream, baseIndent + indentUnit); return function() { if (stream.lookAhead(tag, false, false, true)) { if (parser == PHPParser) phpParserState = localParser.copy(); localParser = null; iter.next = top; return top(); // pass the ending tag to the enclosing parser } var token = localParser.next(); var lt = token.value.lastIndexOf("<"), sz = Math.min(token.value.length - lt, tag.length); if (lt != -1 && token.value.slice(lt, lt + sz).toLowerCase() == tag.slice(0, sz) && stream.lookAhead(tag.slice(sz), false, false, true)) { stream.push(token.value.slice(lt)); token.value = token.value.slice(0, lt); } if (token.indentation) { var oldIndent = token.indentation; token.indentation = function(chars) { if (chars == "</") return baseIndent; else return oldIndent(chars); } } return token; }; } function copy() { var _html = htmlParser.copy(), _local = localParser && localParser.copy(), _next = iter.next, _inTag = inTag, _lastAtt = lastAtt, _php = phpParserState; return function(_stream) { stream = _stream; htmlParser = _html(_stream); localParser = _local && _local(_stream); phpParserState = _php; iter.next = _next; inTag = _inTag; lastAtt = _lastAtt; return iter; }; } return iter; } return { make: parseMixed, electricChars: "{}/:", configure: function(conf) { if (conf.opening != null) processingInstructions = conf.opening; } }; })();
JavaScript
/* Parse function for JavaScript. Makes use of the tokenizer from * tokenizecsharp.js. Note that your parsers do not have to be * this complicated -- if you don't want to recognize local variables, * in many languages it is enough to just look for braces, semicolons, * parentheses, etc, and know when you are inside a string or comment. * * See manual.html for more info about the parser interface. */ var JSParser = Editor.Parser = (function() { // Token types that can be considered to be atoms. var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; // Setting that can be used to have JSON data indent properly. var json = false; // Constructor for the lexical context objects. function CSharpLexical(indented, column, type, align, prev, info) { // indentation at start of this line this.indented = indented; // column at which this scope was opened this.column = column; // type of scope ('vardef', 'stat' (statement), 'form' (special form), '[', '{', or '(') this.type = type; // '[', '{', or '(' blocks that have any text after their opening // character are said to be 'aligned' -- any lines below are // indented all the way to the opening character. if (align != null) this.align = align; // Parent scope, if any. this.prev = prev; this.info = info; } // CSharp indentation rules. function indentCSharp(lexical) { return function(firstChars) { var firstChar = firstChars && firstChars.charAt(0), type = lexical.type; var closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(firstChars) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column - (closing ? 1 : 0); else return lexical.indented + (closing ? 0 : indentUnit); }; } // The parser-iterator-producing function itself. function parseCSharp(input, basecolumn) { // Wrap the input in a token stream var tokens = tokenizeCSharp(input); // The parser state. cc is a stack of actions that have to be // performed to finish the current statement. For example we might // know that we still need to find a closing parenthesis and a // semicolon. Actions at the end of the stack go first. It is // initialized with an infinitely looping action that consumes // whole statements. var cc = [statements]; // The lexical scope, used mostly for indentation. var lexical = new CSharpLexical((basecolumn || 0) - indentUnit, 0, "block", false); // Current column, and the indentation at the start of the current // line. Used to create lexical scope objects. var column = 0; var indented = 0; // Variables which are used by the mark, cont, and pass functions // below to communicate with the driver loop in the 'next' // function. var consume, marked; // The iterator object. var parser = {next: next, copy: copy}; function next(){ // Start by performing any 'lexical' actions (adjusting the // lexical variable), or the operations below will be working // with the wrong lexical state. while(cc[cc.length - 1].lex) cc.pop()(); // Fetch a token. var token = tokens.next(); // Adjust column and indented. if (token.type == "whitespace" && column == 0) indented = token.value.length; column += token.value.length; if (token.content == "\n"){ indented = column = 0; // If the lexical scope's align property is still undefined at // the end of the line, it is an un-aligned scope. if (!("align" in lexical)) lexical.align = false; // Newline tokens get an indentation function associated with // them. token.indentation = indentCSharp(lexical); } // No more processing for meaningless tokens. if (token.type == "whitespace" || token.type == "comment") return token; // When a meaningful token is found and the lexical scope's // align is undefined, it is an aligned scope. if (!("align" in lexical)) lexical.align = true; // Execute actions until one 'consumes' the token and we can // return it. while(true) { consume = marked = false; // Take and execute the topmost action. cc.pop()(token.type, token.content); if (consume){ // Marked is used to change the style of the current token. if (marked) token.style = marked; return token; } } } // This makes a copy of the parser state. It stores all the // stateful variables in a closure, and returns a function that // will restore them when called with a new input stream. Note // that the cc array has to be copied, because it is contantly // being modified. Lexical objects are not mutated, and context // objects are not mutated in a harmful way, so they can be shared // between runs of the parser. function copy(){ var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state; return function copyParser(input){ lexical = _lexical; cc = _cc.concat([]); // copies the array column = indented = 0; tokens = tokenizeCSharp(input, _tokenState); return parser; }; } // Helper function for pushing a number of actions onto the cc // stack in reverse order. function push(fs){ for (var i = fs.length - 1; i >= 0; i--) cc.push(fs[i]); } // cont and pass are used by the action functions to add other // actions to the stack. cont will cause the current token to be // consumed, pass will leave it for the next action. function cont(){ push(arguments); consume = true; } function pass(){ push(arguments); consume = false; } // Used to change the style of the current token. function mark(style){ marked = style; } // Push a new lexical context of the given type. function pushlex(type, info) { var result = function(){ lexical = new CSharpLexical(indented, column, type, null, lexical, info) }; result.lex = true; return result; } // Pop off the current lexical context. function poplex(){ lexical = lexical.prev; } poplex.lex = true; // The 'lex' flag on these actions is used by the 'next' function // to know they can (and have to) be ran before moving on to the // next token. // Creates an action that discards tokens until it finds one of // the given type. function expect(wanted){ return function expecting(type){ if (type == wanted) cont(); else cont(arguments.callee); }; } // Looks for a statement, and then calls itself. function statements(type){ return pass(statement, statements); } // Dispatches various types of statements based on the type of the // current token. function statement(type){ if (type == "var") cont(pushlex("vardef"), vardef1, expect(";"), poplex); else if (type == "keyword a") cont(pushlex("form"), expression, statement, poplex); else if (type == "keyword b") cont(pushlex("form"), statement, poplex); else if (type == "{" && json) cont(pushlex("}"), commasep(objprop, "}"), poplex); else if (type == "{") cont(pushlex("}"), block, poplex); else if (type == "function") cont(functiondef); else if (type == "for") cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); else if (type == "variable") cont(pushlex("stat"), maybelabel); else if (type == "switch") cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); else if (type == "case") cont(expression, expect(":")); else if (type == "default") cont(expect(":")); else if (type == "catch") cont(pushlex("form"), expect("("), funarg, expect(")"), statement, poplex); else if (type == "class") cont(classdef); else if (type == "keyword d") cont(statement); else pass(pushlex("stat"), expression, expect(";"), poplex); } // Dispatch expression types. function expression(type){ if (atomicTypes.hasOwnProperty(type)) cont(maybeoperator); else if (type == "function") cont(functiondef); else if (type == "keyword c") cont(expression); else if (type == "(") cont(pushlex(")"), expression, expect(")"), poplex, maybeoperator); else if (type == "operator") cont(expression); else if (type == "[") cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); else if (type == "{") cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); } // Called for places where operators, function calls, or // subscripts are valid. Will skip on to the next action if none // is found. function maybeoperator(type){ if (type == "operator") cont(expression); else if (type == "(") cont(pushlex(")"), expression, commasep(expression, ")"), poplex, maybeoperator); else if (type == ".") cont(property, maybeoperator); else if (type == "[") cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } // When a statement starts with a variable name, it might be a // label. If no colon follows, it's a regular statement. function maybelabel(type){ if (type == ":") cont(poplex, statement); else if (type == "(") cont(commasep(funarg, ")"), poplex, statement); // method definition else if (type == "{") cont(poplex, pushlex("}"), block, poplex); // property definition else pass(maybeoperator, expect(";"), poplex); } // Property names need to have their style adjusted -- the // tokenizer thinks they are variables. function property(type){ if (type == "variable") {mark("csharp-property"); cont();} } // This parses a property and its value in an object literal. function objprop(type){ if (type == "variable") mark("csharp-property"); if (atomicTypes.hasOwnProperty(type)) cont(expect(":"), expression); } // Parses a comma-separated list of the things that are recognized // by the 'what' argument. function commasep(what, end){ function proceed(type) { if (type == ",") cont(what, proceed); else if (type == end) cont(); else cont(expect(end)); }; return function commaSeparated(type) { if (type == end) cont(); else pass(what, proceed); }; } // Look for statements until a closing brace is found. function block(type){ if (type == "}") cont(); else pass(statement, block); } // Variable definitions are split into two actions -- 1 looks for // a name or the end of the definition, 2 looks for an '=' sign or // a comma. function vardef1(type, value){ if (type == "variable"){cont(vardef2);} else cont(); } function vardef2(type, value){ if (value == "=") cont(expression, vardef2); else if (type == ",") cont(vardef1); } // For loops. function forspec1(type){ if (type == "var") cont(vardef1, forspec2); else if (type == "keyword d") cont(vardef1, forspec2); else if (type == ";") pass(forspec2); else if (type == "variable") cont(formaybein); else pass(forspec2); } function formaybein(type, value){ if (value == "in") cont(expression); else cont(maybeoperator, forspec2); } function forspec2(type, value){ if (type == ";") cont(forspec3); else if (value == "in") cont(expression); else cont(expression, expect(";"), forspec3); } function forspec3(type) { if (type == ")") pass(); else cont(expression); } // A function definition creates a new context, and the variables // in its argument list have to be added to this context. function functiondef(type, value){ if (type == "variable") cont(functiondef); else if (type == "(") cont(commasep(funarg, ")"), statement); } function funarg(type, value){ if (type == "variable"){cont();} } function classdef(type) { if (type == "variable") cont(classdef, statement); else if (type == ":") cont(classdef, statement); } return parser; } return { make: parseCSharp, electricChars: "{}:", configure: function(obj) { if (obj.json != null) json = obj.json; } }; })();
JavaScript
/* Tokenizer for CSharp code */ var tokenizeCSharp = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; var next; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "csharp-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); // just a keyword with no indentation implications var keywordD = result("keyword d", "keyword"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "class": result("class", "keyword"), "namespace": result("class", "keyword"), "public": keywordD, "private": keywordD, "protected": keywordD, "internal": keywordD, "extern": keywordD, "override": keywordD, "virtual": keywordD, "abstract": keywordD, "static": keywordD, "out": keywordD, "ref": keywordD, "const": keywordD, "foreach": result("for", "keyword"), "using": keywordC, "int": keywordD, "double": keywordD, "long": keywordD, "bool": keywordD, "char": keywordD, "void": keywordD, "string": keywordD, "byte": keywordD, "sbyte": keywordD, "decimal": keywordD, "float": keywordD, "uint": keywordD, "ulong": keywordD, "object": keywordD, "short": keywordD, "ushort": keywordD, "get": keywordD, "set": keywordD, "value": keywordD }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "csharp-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "csharp-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "csharp-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gi]/); return {type: "regexp", style: "csharp-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "csharp-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "csharp-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "csharp-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "csharp-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "csharp-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (ch == "#") { // treat c# regions like comments nextUntilUnescaped(source, null); return {type: "comment", style: "csharp-comment"}; } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
JavaScript
function waitForStyles() { for (var i = 0; i < document.styleSheets.length; i++) if (/googleapis/.test(document.styleSheets[i].href)) return document.body.className += " droid"; setTimeout(waitForStyles, 100); } setTimeout(function() { if (/AppleWebKit/.test(navigator.userAgent) && /iP[oa]d|iPhone/.test(navigator.userAgent)) return; var link = document.createElement("LINK"); link.type = "text/css"; link.rel = "stylesheet"; link.href = "http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"; document.documentElement.getElementsByTagName("HEAD")[0].appendChild(link); waitForStyles(); }, 20);
JavaScript
CKFinder.addPlugin( 'fileeditor', function( api ) { var regexExt = /^(.*)\.([^\.]+)$/, regexTextExt = /^(txt|css|html|htm|js|asp|cfm|cfc|ascx|php|inc|xml|xslt|xsl)$/i, regexCodeMirrorExt = /^(css|html|htm|js|xml|xsl|php)$/i, codemirror, file, fileLoaded = false, doc; var codemirrorPath = CKFinder.getPluginPath('fileeditor') + 'codemirror/'; var codeMirrorParsers = { css : 'parsecss.js', js : [ 'tokenizejavascript.js', 'parsejavascript.js' ], xml : 'parsexml.js', php : ['parsexml.js', 'parsecss.js', 'tokenizejavascript.js', 'parsejavascript.js', '../contrib/php/js/tokenizephp.js', '../contrib/php/js/parsephp.js', '../contrib/php/js/parsephphtmlmixed.js'] }; var codeMirrorCss = { css : codemirrorPath + 'css/csscolors.css', js : codemirrorPath + 'css/jscolors.css', xml : codemirrorPath + 'css/xmlcolors.css', php : [ codemirrorPath + 'css/xmlcolors.css', codemirrorPath + 'css/jscolors.css', codemirrorPath + 'css/csscolors.css', codemirrorPath + 'contrib/php/css/phpcolors.css' ] }; codeMirrorCss.xsl = codeMirrorCss.xml; codeMirrorCss.htm = codeMirrorCss.xml; codeMirrorCss.html = codeMirrorCss.xml; codeMirrorParsers.xsl = codeMirrorParsers.xml; codeMirrorParsers.htm = codeMirrorParsers.xml; codeMirrorParsers.html = codeMirrorParsers.xml; var isTextFile = function( file ) { return regexTextExt.test( file.ext ); }; CKFinder.dialog.add( 'fileEditor', function( api ) { var height, width; var saveButton = (function() { return { id : 'save', label : api.lang.Fileeditor.save, type : 'button', onClick : function ( evt ) { if ( !fileLoaded ) return true; var dialog = evt.data.dialog; var content = codemirror ? codemirror.getCode() : doc.getById( 'fileContent' ).getValue(); api.connector.sendCommandPost( "SaveFile", null, { content : content, fileName : file.name }, function( xml ) { if ( xml.checkError() ) return false; api.openMsgDialog( '', api.lang.Fileeditor.fileSaveSuccess ); dialog.hide(); return undefined; }, file.folder.type, file.folder ); return false; } }; })(); if ( api.inPopup ) { width = api.document.documentElement.offsetWidth; height = api.document.documentElement.offsetHeight; } else { var parentWindow = ( api.document.parentWindow || api.document.defaultView ).parent; width = parentWindow.innerWidth ? parentWindow.innerWidth : parentWindow.document.documentElement.clientWidth; height = parentWindow.innerHeight ? parentWindow.innerHeight : parentWindow.document.documentElement.clientHeight; } return { title : api.getSelectedFile().name, minWidth : parseInt( width, 10 ) * 0.6, minHeight : parseInt( height, 10 ) * 0.7, onHide : function() { if ( fileLoaded ) { var fileContent = doc.getById( 'fileContent' ); if ( fileContent ) fileContent.remove(); } }, onShow : function() { var dialog = this; var cssWidth = parseInt( width, 10 ) * 0.6 - 10; var cssHeight = parseInt( height, 10 ) * 0.7 - 20; doc = dialog.getElement().getDocument(); var win = doc.getWindow(); doc.getById( 'fileArea' ).setHtml( '<div class="ckfinder_loader_32" style="margin: 100px auto 0 auto;text-align:center;"><p style="height:' + cssHeight + 'px;width:' + cssWidth + 'px;">' + api.lang.Fileeditor.loadingFile + '</p></div>' ); file = api.getSelectedFile(); var enableCodeMirror = regexCodeMirrorExt.test( file.ext ); this.setTitle( file.name ); if ( enableCodeMirror && win.$.CodeMirror === undefined ) { var head= doc.$.getElementsByTagName( 'head' )[0]; var script= doc.$.createElement( 'script' ); script.type= 'text/javascript'; script.src = CKFinder.getPluginPath( 'fileeditor' ) + 'codemirror/js/codemirror.js'; head.appendChild( script ); } // If CKFinder is runninng under a different domain than baseUrl, then the following call will fail: // CKFinder.ajax.load( file.getUrl() + '?t=' + (new Date().getTime()), function( data )... var url = api.connector.composeUrl( 'DownloadFile', { FileName : file.name, format : 'text', t : new Date().getTime() }, file.folder.type, file.folder ); CKFinder.ajax.load( url, function( data ) { if ( data === null || ( file.size > 0 && data === '' ) ) { api.openMsgDialog( '', api.lang.Fileeditor.fileOpenError ); dialog.hide(); return; } else fileLoaded = true; var fileArea = doc.getById( 'fileArea' ); fileArea.setStyle('height', '100%'); fileArea.setHtml( '<textarea id="fileContent" style="height:' + cssHeight + 'px; width:' + cssWidth + 'px"></textarea>' ); doc.getById( 'fileContent' ).setText( data ); codemirror = null; if ( enableCodeMirror && win.$.CodeMirror !== undefined ) { codemirror = win.$.CodeMirror.fromTextArea( doc.getById( 'fileContent').$, { height : cssHeight + 'px', parserfile : codeMirrorParsers[ file.ext.toLowerCase() ], stylesheet : codeMirrorCss[ file.ext.toLowerCase() ], path : codemirrorPath + "js/" } ); // TODO get rid of ugly buttons and provide something better var undoB = doc.createElement( "button", { attributes: { "label" : api.lang.common.undo } } ); undoB.on( 'click', function() { codemirror.undo(); }); undoB.setHtml( api.lang.common.undo ); undoB.appendTo( doc.getById( 'fileArea' ) ); var redoB = doc.createElement( 'button', { attributes: { "label" : api.lang.common.redo } } ); redoB.on('click', function() { codemirror.redo(); }); redoB.setHtml( api.lang.common.redo ); redoB.appendTo( doc.getById( 'fileArea' ) ); } }); }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'html', id : 'htmlLoader', html : '' + '<style type="text/css">' + '.CodeMirror-wrapping {background:white;}' + '</style>' + '<div id="fileArea"></div>' } ] } ], // TODO http://dev.fckeditor.net/ticket/4750 buttons : [ saveButton, CKFinder.dialog.cancelButton ] }; } ); api.addFileContextMenuOption( { label : api.lang.Fileeditor.contextMenuName, command : "fileEditor" } , function( api, file ) { api.openDialog( 'fileEditor' ); }, function ( file ) { var maxSize = 1024; if ( typeof (CKFinder.config.fileeditorMaxSize) != 'undefined' ) maxSize = CKFinder.config.fileeditorMaxSize; // Disable for images, binary files, large files etc. if ( isTextFile( file ) && file.size <= maxSize ) { if ( file.folder.acl.fileDelete ) return true; else return -1; } return false; }); } );
JavaScript
CKFinder.addPlugin( 'imageresize', { connectorInitialized : function( api, xml ) { var node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@smallThumb' ); if ( node ) CKFinder.config.imageresize_thumbSmall = node.value; node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@mediumThumb' ); if ( node ) CKFinder.config.imageresize_thumbMedium = node.value; node = xml.selectSingleNode( 'Connector/PluginsInfo/imageresize/@largeThumb' ); if ( node ) CKFinder.config.imageresize_thumbLarge = node.value; }, uiReady : function( api ) { var regexExt = /^(.*)\.([^\.]+)$/, regexFileName = /^(.*?)(?:_\d+x\d+)?\.([^\.]+)$/, regexGetSize = /^\s*(\d+)(px)?\s*$/i, regexGetSizeOrEmpty = /(^\s*(\d+)(px)?\s*$)|^$/i, imageDimension = { width : 0, height : 0 }, file, doc; var updateFileName = function( dialog ) { var width = dialog.getValueOf( 'tab1', 'width' ) || 0, height = dialog.getValueOf( 'tab1', 'height' ) || 0, e = dialog.getContentElement('tab1', 'createNewBox'); if ( width && height ) { var matches = file.name.match( regexFileName ); dialog.setValueOf( 'tab1', 'fileName', matches[1] + "_" + width + "x" + height + "." + matches[2]); e.getElement().show(); } else e.getElement().hide(); }; var onSizeChange = function() { var value = this.getValue(), // This = input element. dialog = this.getDialog(), maxWidth = api.config.imagesMaxWidth, maxHeight = api.config.imagesMaxHeight, aMatch = value.match( regexGetSize ), width = imageDimension.width, height = imageDimension.height, newHeight, newWidth; if ( aMatch ) value = aMatch[1]; if ( !api.config.imageresize_allowEnlarging ) { if ( width && width < maxWidth ) maxWidth = width; if ( height && height < maxHeight ) maxHeight = height; } if ( maxHeight > 0 && this.id == 'height' && value > maxHeight ) { value = maxHeight; dialog.setValueOf( 'tab1', 'height', value ); } if ( maxWidth > 0 && this.id == 'width' && value > maxWidth ) { value = maxWidth; dialog.setValueOf( 'tab1', 'width', value ); } // Only if ratio is locked if ( dialog.lockRatio && width && height ) { if ( this.id == 'height' ) { if ( value && value != '0' ) value = Math.round( width * ( value / height ) ); if ( !isNaN( value ) ) { // newWidth > maxWidth if ( maxWidth > 0 && value > maxWidth ) { value = maxWidth; newHeight = Math.round( height * ( value / width ) ); dialog.setValueOf( 'tab1', 'height', newHeight ); } dialog.setValueOf( 'tab1', 'width', value ); } } else //this.id = txtWidth. { if ( value && value != '0' ) value = Math.round( height * ( value / width ) ); if ( !isNaN( value ) ) { // newHeight > maxHeight if ( maxHeight > 0 && value > maxHeight ) { value = maxHeight; newWidth = Math.round( width * ( value / height ) ); dialog.setValueOf( 'tab1', 'width', newWidth ); } dialog.setValueOf( 'tab1', 'height', value ); } } } updateFileName( dialog ); }; var resetSize = function( dialog ) { if ( imageDimension.width && imageDimension.height ) { dialog.setValueOf( 'tab1', 'width', imageDimension.width ); dialog.setValueOf( 'tab1', 'height', imageDimension.height ); updateFileName( dialog ); } }; var switchLockRatio = function( dialog, value ) { var doc = dialog.getElement().getDocument(), ratioButton = doc.getById( 'btnLockSizes' ); if ( imageDimension.width && imageDimension.height ) { if ( value == 'check' ) // Check image ratio and original image ratio. { var width = dialog.getValueOf( 'tab1', 'width' ), height = dialog.getValueOf( 'tab1', 'height' ), originalRatio = imageDimension.width * 1000 / imageDimension.height, thisRatio = width * 1000 / height; dialog.lockRatio = false; // Default: unlock ratio if ( !width && !height ) dialog.lockRatio = true; // If someone didn't start typing, lock ratio. else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) ) { if ( Math.round( originalRatio ) == Math.round( thisRatio ) ) dialog.lockRatio = true; } } else if ( value != undefined ) dialog.lockRatio = value; else dialog.lockRatio = !dialog.lockRatio; } else if ( value != 'check' ) // I can't lock ratio if ratio is unknown. dialog.lockRatio = false; if ( dialog.lockRatio ) ratioButton.removeClass( 'ckf_btn_unlocked' ); else ratioButton.addClass( 'ckf_btn_unlocked' ); return dialog.lockRatio; }; CKFinder.dialog.add( 'resizeDialog', function( api ) { return { title : api.lang.Imageresize.dialogTitle.replace( '%s', api.getSelectedFile().name ), // TODO resizable : CKFINDER.DIALOG_RESIZE_BOTH minWidth : 390, minHeight : 230, onShow : function() { var dialog = this, thumbSmall = CKFinder.config.imageresize_thumbSmall, thumbMedium = CKFinder.config.imageresize_thumbMedium, thumbLarge = CKFinder.config.imageresize_thumbLarge; doc = dialog.getElement().getDocument(); file = api.getSelectedFile(); this.setTitle( api.lang.Imageresize.dialogTitle.replace( '%s', file.name ) ); var previewImg = doc.getById('previewImage'); var sizeSpan = doc.getById('imageSize'); previewImg.setAttribute('src', file.getThumbnailUrl( true )); var updateImgDimension = function( width, height ) { if ( !width || !height ) { sizeSpan.setText( '' ); return; } imageDimension.width = width; imageDimension.height = height; sizeSpan.setText( width + " x " + height + " px" ); CKFinder.tools.setTimeout( function(){ switchLockRatio( dialog, 'check' ); }, 0, dialog ); }; api.connector.sendCommand( "ImageResizeInfo", { fileName : file.name }, function( xml ) { if ( xml.checkError() ) return; var width = xml.selectSingleNode( 'Connector/ImageInfo/@width' ), height = xml.selectSingleNode( 'Connector/ImageInfo/@height' ), result; if ( width && height ) { width = parseInt( width.value, 10 ); height = parseInt( height.value, 10 ); updateImgDimension( width, height ); var checkThumbs = function( id, size ) { if ( !size ) return; var reThumb = /^(\d+)x(\d+)$/; result = reThumb.exec( size ); var el = dialog.getContentElement( 'tab1', id ); if ( 0 + result[1] > width && 0 + result[2] > height ) { el.disable(); el.getElement().setAttribute('title', api.lang.Imageresize.imageSmall).addClass('cke_disabled'); } else { el.enable(); el.getElement().setAttribute('title', '').removeClass('cke_disabled'); } }; checkThumbs('smallThumb', thumbSmall ); checkThumbs('mediumThumb', thumbMedium ); checkThumbs('largeThumb', thumbLarge ); } }, file.folder.type, file.folder ); if ( !thumbSmall ) dialog.getContentElement('tab1', 'smallThumb').getElement().hide(); if ( !thumbMedium ) dialog.getContentElement('tab1', 'mediumThumb').getElement().hide(); if ( !thumbLarge ) dialog.getContentElement('tab1', 'largeThumb').getElement().hide(); if ( !thumbSmall && !thumbMedium && !thumbLarge ) dialog.getContentElement('tab1', 'thumbsLabel').getElement().hide(); dialog.setValueOf( 'tab1', 'fileName', file.name ); dialog.getContentElement('tab1', 'width').focus(); dialog.getContentElement('tab1', 'fileName').setValue(''); dialog.getContentElement('tab1', 'createNewBox').getElement().hide(); updateImgDimension( 0,0 ); }, onOk : function() { var dialog = this, width = dialog.getValueOf( 'tab1', 'width' ), height = dialog.getValueOf( 'tab1', 'height' ), small = dialog.getValueOf( 'tab1', 'smallThumb' ), medium = dialog.getValueOf( 'tab1', 'mediumThumb' ), large = dialog.getValueOf( 'tab1', 'largeThumb' ), fileName = dialog.getValueOf( 'tab1', 'fileName' ), createNew = dialog.getValueOf( 'tab1', 'createNew' ); if ( width && !height ) { api.openMsgDialog( '', api.lang.Imageresize.invalidHeight ); return false; } else if ( !width && height ) { api.openMsgDialog( '', api.lang.Imageresize.invalidWidth ); return false; } if ( !api.config.imageresize_allowEnlarging && ( parseInt( width, 10 ) > imageDimension.width || parseInt( height, 10 ) > imageDimension.height ) ) { var str = api.lang.Imageresize.sizeTooBig; api.openMsgDialog( '', str.replace( "%size", imageDimension.width + "x" + imageDimension.height ) ); return false; } if ( ( width && height ) || small || medium || large ) { if ( !createNew ) fileName = file.name; api.connector.sendCommandPost( "ImageResize", null, { width : width, height : height, fileName : file.name, newFileName : fileName, overwrite : createNew ? 0 : 1, small : small ? 1 : 0, medium : medium ? 1 : 0, large : large ? 1 : 0 }, function( xml ) { if ( xml.checkError() ) return; api.openMsgDialog( '', api.lang.Imageresize.resizeSuccess ); api.refreshOpenedFolder(); }, file.folder.type, file.folder ); } return undefined; }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'hbox', widths : [ '180px', '280px' ], children: [ { type : 'vbox', children: [ { type : 'html', html : '' + '<style type="text/css">' + 'a.ckf_btn_reset' + '{' + 'float: right;' + 'background-position: 0 -32px;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' + 'width: 16px;' + 'height: 16px;' + 'background-repeat: no-repeat;' + 'border: 1px none;' + 'font-size: 1px;' + '}' + 'a.ckf_btn_locked,' + 'a.ckf_btn_unlocked' + '{' + 'float: left;' + 'background-position: 0 0;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + 'images/mini.gif");' + 'width: 16px;' + 'height: 16px;' + 'background-repeat: no-repeat;' + 'border: none 1px;' + 'font-size: 1px;' + '}' + 'a.ckf_btn_unlocked' + '{' + 'background-position: 0 -16px;' + 'background-image: url("' + CKFinder.getPluginPath('imageresize') + '/images/mini.gif");' + '}' + '.ckf_btn_over' + '{' + 'border: outset 1px;' + 'cursor: pointer;' + 'cursor: hand;' + '}' + '</style>' + '<div style="height:100px;padding:7px">' + '<img id="previewImage" src="" style="margin-bottom:4px;" /><br />' + '<span style="font-size:9px;" id="imageSize"></span>' + '</div>' }, { type : 'html', id : 'thumbsLabel', html : '<strong>' + api.lang.Imageresize.thumbnailNew + '</strong>' }, { type : 'checkbox', id : 'smallThumb', checked : false, label : api.lang.Imageresize.thumbnailSmall.replace( '%s', CKFinder.config.imageresize_thumbSmall ) }, { type : 'checkbox', id : 'mediumThumb', checked : false, label : api.lang.Imageresize.thumbnailMedium.replace( '%s', CKFinder.config.imageresize_thumbMedium ) }, { type : 'checkbox', id : 'largeThumb', checked : false, label : api.lang.Imageresize.thumbnailLarge.replace( '%s', CKFinder.config.imageresize_thumbLarge ) } ] }, { type : 'vbox', children : [ { type : 'html', html : '<strong>' + api.lang.Imageresize.newSize + '</strong>' }, { type : 'hbox', widths : [ '80%', '20%' ], children: [ { type : 'vbox', children: [ { type : 'text', labelLayout : 'horizontal', label : api.lang.Imageresize.width, onKeyUp : onSizeChange, validate: function() { var value = this.getValue(); if ( value ) { var aMatch = value.match( regexGetSize ); if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 ) { api.openMsgDialog( '', api.lang.Imageresize.invalidWidth ); return false; } } return true; }, id : 'width' }, { type : 'text', labelLayout : 'horizontal', label : api.lang.Imageresize.height, onKeyUp : onSizeChange, validate: function() { var value = this.getValue(); if ( value ) { var aMatch = value.match( regexGetSize ); if ( !aMatch || parseInt( aMatch[1], 10 ) < 1 ) { api.openMsgDialog( '', api.lang.Imageresize.invalidHeight ); return false; } } return true; }, id : 'height' } ] }, { type : 'html', onLoad : function() { var doc = this.getElement().getDocument(), dialog = this.getDialog(); // Activate Reset button var resetButton = doc.getById( 'btnResetSize' ), ratioButton = doc.getById( 'btnLockSizes' ); if ( resetButton ) { resetButton.on( 'click', function(evt) { resetSize( this ); evt.data.preventDefault(); }, dialog ); resetButton.on( 'mouseover', function() { this.addClass( 'ckf_btn_over' ); }, resetButton ); resetButton.on( 'mouseout', function() { this.removeClass( 'ckf_btn_over' ); }, resetButton ); } // Activate (Un)LockRatio button if ( ratioButton ) { ratioButton.on( 'click', function(evt) { var locked = switchLockRatio( this ), width = this.getValueOf( 'tab1', 'width' ); if ( imageDimension.width && width ) { var height = imageDimension.height / imageDimension.width * width; if ( !isNaN( height ) ) { this.setValueOf( 'tab1', 'height', Math.round( height ) ); updateFileName( dialog ); } } evt.data.preventDefault(); }, dialog ); ratioButton.on( 'mouseover', function() { this.addClass( 'ckf_btn_over' ); }, ratioButton ); ratioButton.on( 'mouseout', function() { this.removeClass( 'ckf_btn_over' ); }, ratioButton ); } }, html : '<div style="margin-top:4px">'+ '<a href="javascript:void(0)" tabindex="-1" title="' + api.lang.Imageresize.lockRatio + '" class="ckf_btn_locked ckf_btn_unlocked" id="btnLockSizes"></a>' + '<a href="javascript:void(0)" tabindex="-1" title="' + api.lang.Imageresize.resetSize + '" class="ckf_btn_reset" id="btnResetSize"></a>'+ '</div>' } ] }, { type : 'vbox', id : 'createNewBox', hidden : true, children: [ { type : 'checkbox', checked : true, id : 'createNew', label : api.lang.Imageresize.newImage, 'default' : true, onChange : function() { var dialog = this.getDialog(); var filenameInput = dialog.getContentElement('tab1', 'fileName'); if ( filenameInput ) { if (!this.getValue()) filenameInput.getElement().hide(); else filenameInput.getElement().show(); } } }, { type : 'text', label : '', validate : function() { var dialog = this.getDialog(), createNew = dialog.getContentElement('tab1', 'createNew'), value = this.getValue(), matches = value.match( regexExt ); if ( createNew && dialog.getValueOf( 'tab1', 'width' ) && dialog.getValueOf( 'tab1', 'height' ) ) { if ( !value || !matches ) { api.openMsgDialog( '', api.lang.Imageresize.invalidName ); return false; } if ( file.ext != matches[2] ) { api.openMsgDialog( '', api.lang.Imageresize.noExtensionChange ); return false; } } return true; }, id : 'fileName' } ] } ] } ] } ] } ], // TODO http://dev.fckeditor.net/ticket/4750 buttons : [ CKFinder.dialog.okButton, CKFinder.dialog.cancelButton ] }; } ); api.addFileContextMenuOption( { label : api.lang.Imageresize.contextMenuName, command : "resizeImage" } , function( api, file ) { api.openDialog( 'resizeDialog' ); }, function ( file ) { // Disable for files other than images. if ( !file.isImage() || !api.getSelectedFolder().type ) return false; if ( file.folder.acl.fileDelete && file.folder.acl.fileUpload ) return true; else return -1; }); } } );
JavaScript
/** * Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license * * CKFinder 2.x - sample "dummy" plugin. * * To enable it, add the following line to config.js: * config.extraPlugins = 'dummy'; */ /** * See http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.html#.addPlugin */ CKFinder.addPlugin( 'dummy', { lang : [ 'en', 'pl' ], appReady : function( api ) { CKFinder.dialog.add( 'dummydialog', function( api ) { // CKFinder.dialog.definition var dialogDefinition = { title : api.lang.dummy.title, minWidth : 390, minHeight : 230, onOk : function() { // "this" is now a CKFinder.dialog object. var value = this.getValueOf( 'tab1', 'textareaId' ); if ( !value ) { api.openMsgDialog( '', api.lang.dummy.typeText ); return false; } else { alert( "You have entered: " + value ); return true; } }, contents : [ { id : 'tab1', label : '', title : '', expand : true, padding : 0, elements : [ { type : 'html', html : '<h3>' + api.lang.dummy.typeText + '</h3>' }, { type : 'textarea', id : 'textareaId', rows : 10, cols : 40 } ] } ], buttons : [ CKFinder.dialog.cancelButton, CKFinder.dialog.okButton ] }; return dialogDefinition; } ); api.addFileContextMenuOption( { label : api.lang.dummy.menuItem, command : "dummycommand" } , function( api, file ) { api.openDialog('dummydialog'); }); } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKFinder.setPluginLang( 'dummy', 'pl', { dummy : { title : 'Testowe okienko', menuItem : 'Otwórz okienko dummy', typeText : 'Podaj jakiś tekst.' } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKFinder.setPluginLang( 'dummy', 'en', { dummy : { title : 'Dummy dialog', menuItem : 'Open dummy dialog', typeText : 'Please type some text.' } });
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckfinder.com/license */ CKFinder.customConfig = function( config ) { // Define changes to default configuration here. // For the list of available options, check: // http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.config.html // Sample configuration options: // config.uiColor = '#BDE31E'; // config.language = 'fr'; // config.removePlugins = 'basket'; };
JavaScript
window.onload = function() { var copyP = document.createElement( 'p' ) ; copyP.className = 'copyright' ; copyP.innerHTML = '&copy; 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 Norwegian * Nynorsk language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['no'] = { 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 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 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 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 Slovenian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['sl'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nedostopen</span>', confirmCancel : 'Nekatere opcije so bile spremenjene. Ali res želite zapreti pogovorno okno?', ok : 'Potrdi', cancel : 'Prekliči', confirmationTitle : 'Potrditev', messageTitle : 'Informacija', inputTitle : 'Vprašanje', undo : 'Razveljavi', redo : 'Obnovi', skip : 'Preskoči', skipAll : 'Preskoči vse', makeDecision : 'Katera aktivnost naj se izvede?', rememberDecision: 'Zapomni si mojo izbiro' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'sl', // 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 : 'Mape', FolderLoading : 'Nalagam...', FolderNew : 'Vnesite ime za novo mapo: ', FolderRename : 'Vnesite ime nove mape: ', FolderDelete : 'Ali ste prepričani, da želite zbrisati mapo "%1"?', FolderRenaming : ' (Preimenujem...)', FolderDeleting : ' (Brišem...)', // Files FileRename : 'Vnesite novo ime datoteke: ', FileRenameExt : 'Ali ste prepričani, da želite spremeniti končnico datoteke? Možno je, da potem datoteka ne bo uporabna.', FileRenaming : 'Preimenujem...', FileDelete : 'Ali ste prepričani, da želite izbrisati datoteko "%1"?', FilesLoading : 'Nalagam...', FilesEmpty : 'Prazna mapa', FilesMoved : 'Datoteka %1 je bila premaknjena v %2:%3.', FilesCopied : 'Datoteka %1 je bila kopirana v %2:%3.', // Basket BasketFolder : 'Koš', BasketClear : 'Izprazni koš', BasketRemove : 'Odstrani iz koša', BasketOpenFolder : 'Odpri izvorno mapo', BasketTruncateConfirm : 'Ali res želite odstraniti vse datoteke iz koša?', BasketRemoveConfirm : 'Ali res želite odstraniti datoteko "%1" iz koša?', BasketEmpty : 'V košu ni datotek. Lahko jih povlečete in spustite.', BasketCopyFilesHere : 'Kopiraj datoteke iz koša', BasketMoveFilesHere : 'Premakni datoteke iz koša', BasketPasteErrorOther : 'Napaka z datoteko %s: %e', BasketPasteMoveSuccess : 'Seznam premaknjenih datotek: %s', BasketPasteCopySuccess : 'Seznam kopiranih datotek: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Naloži na strežnik', UploadTip : 'Naloži novo datoteko na strežnik', Refresh : 'Osveži', Settings : 'Nastavitve', Help : 'Pomoč', HelpTip : 'Pomoč', // Context Menus Select : 'Izberi', SelectThumbnail : 'Izberi malo sličico (predogled)', View : 'Predogled', Download : 'Prenesi na svoj računalnik', NewSubFolder : 'Nova podmapa', Rename : 'Preimenuj', Delete : 'Zbriši', CopyDragDrop : 'Kopiraj datoteko', MoveDragDrop : 'Premakni datoteko', // Dialogs RenameDlgTitle : 'Preimenuj', NewNameDlgTitle : 'Novo ime', FileExistsDlgTitle : 'Datoteka že obstaja', SysErrorDlgTitle : 'Sistemska napaka', FileOverwrite : 'Prepiši', FileAutorename : 'Avtomatsko preimenuj', // Generic OkBtn : 'Potrdi', CancelBtn : 'Prekliči', CloseBtn : 'Zapri', // Upload Panel UploadTitle : 'Naloži novo datoteko na strežnik', UploadSelectLbl : 'Izberi datoteko za prenos na strežnik', UploadProgressLbl : '(Prenos na strežnik poteka, prosimo počakajte...)', UploadBtn : 'Prenesi izbrano datoteko na strežnik', UploadBtnCancel : 'Prekliči', UploadNoFileMsg : 'Prosimo izberite datoteko iz svojega računalnika za prenos na strežnik.', UploadNoFolder : 'Izberite mapo v katero se bo naložilo datoteko!', UploadNoPerms : 'Nalaganje datotek ni dovoljeno.', UploadUnknError : 'Napaka pri pošiljanju datoteke.', UploadExtIncorrect : 'V tej mapi ta vrsta datoteke ni dovoljena.', // 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 : 'Nastavitve', SetView : 'Pogled:', SetViewThumb : 'majhne sličice', SetViewList : 'seznam', SetDisplay : 'Prikaz:', SetDisplayName : 'ime datoteke', SetDisplayDate : 'datum', SetDisplaySize : 'velikost datoteke', SetSort : 'Razvrščanje:', SetSortName : 'po imenu datoteke', SetSortDate : 'po datumu', SetSortSize : 'po velikosti', // Status Bar FilesCountEmpty : '<Prazna mapa>', FilesCountOne : '1 datoteka', FilesCountMany : '%1 datotek(e)', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/sek', // Connector Error Messages. ErrorUnknown : 'Prišlo je do napake. (Napaka %1)', Errors : { 10 : 'Napačen ukaz.', 11 : 'V poizvedbi ni bil jasen tip (resource type).', 12 : 'Tip datoteke ni primeren.', 102 : 'Napačno ime mape ali datoteke.', 103 : 'Vašega ukaza se ne da izvesti zaradi težav z avtorizacijo.', 104 : 'Vašega ukaza se ne da izvesti zaradi težav z nastavitvami pravic v datotečnem sistemu.', 105 : 'Napačna končnica datoteke.', 109 : 'Napačna zahteva.', 110 : 'Neznana napaka.', 115 : 'Datoteka ali mapa s tem imenom že obstaja.', 116 : 'Mapa ni najdena. Prosimo osvežite okno in poskusite znova.', 117 : 'Datoteka ni najdena. Prosimo osvežite seznam datotek in poskusite znova.', 118 : 'Začetna in končna pot je ista.', 201 : 'Datoteka z istim imenom že obstaja. Naložena datoteka je bila preimenovana v "%1".', 202 : 'Neprimerna datoteka.', 203 : 'Datoteka je prevelika in zasede preveč prostora.', 204 : 'Naložena datoteka je okvarjena.', 205 : 'Na strežniku ni na voljo začasna mapa za prenos datotek.', 206 : 'Nalaganje je bilo prekinjeno zaradi varnostnih razlogov. Datoteka vsebuje podatke, ki spominjajo na HTML kodo.', 207 : 'Naložena datoteka je bila preimenovana v "%1".', 300 : 'Premikanje datotek(e) ni uspelo.', 301 : 'Kopiranje datotek(e) ni uspelo.', 500 : 'Brskalnik je onemogočen zaradi varnostnih razlogov. Prosimo kontaktirajte upravljalca spletnih strani.', 501 : 'Ni podpore za majhne sličice (predogled).' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Ime datoteke ne more biti prazno.', FileExists : 'Datoteka %s že obstaja.', FolderEmpty : 'Mapa ne more biti prazna.', FileInvChar : 'Ime datoteke ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |', FolderInvChar : 'Ime mape ne sme vsebovati naslednjih znakov: \n\\ / : * ? " < > |', PopupBlockView : 'Datoteke ni možno odpreti v novem oknu. Prosimo nastavite svoj brskalnik tako, da bo dopuščal odpiranje oken (popups) oz. izklopite filtre za blokado odpiranja oken.', 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 : 'Spremeni velikost slike %s', sizeTooBig : 'Širina ali višina slike ne moreta biti večji kot je originalna velikost (%size).', resizeSuccess : 'Velikost slike je bila uspešno spremenjena.', thumbnailNew : 'Kreiraj novo majhno sličico', thumbnailSmall : 'majhna (%s)', thumbnailMedium : 'srednja (%s)', thumbnailLarge : 'velika (%s)', newSize : 'Določite novo velikost', width : 'Širina', height : 'Višina', invalidHeight : 'Nepravilna višina.', invalidWidth : 'Nepravilna širina.', invalidName : 'Nepravilno ime datoteke.', newImage : 'Kreiraj novo sliko', noExtensionChange : 'Končnica datoteke se ne more spremeniti.', imageSmall : 'Izvorna slika je premajhna.', contextMenuName : 'Spremeni velikost', lockRatio : 'Zakleni razmerje', resetSize : 'Ponastavi velikost' }, // Fileeditor plugin Fileeditor : { save : 'Shrani', fileOpenError : 'Datoteke ni mogoče odpreti.', fileSaveSuccess : 'Datoteka je bila shranjena.', contextMenuName : 'Uredi', loadingFile : 'Nalaganje datoteke, prosimo počakajte ...' }, Maximize : { maximize : 'Maksimiraj', minimize : 'Minimiraj' } };
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 Persian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['fa'] = { 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 : 'rtl', HelpLang : 'en', LangCode : 'fa', // 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 aa', DateAmPm : ['ق.ظ', 'ب.ظ'], // 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 : 'فایل برای آپلود', 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 : 'امکان اجرای درخواست تا زمانیکه محدودیت مجوز سیستمی فایل وجود دارد،\u200bمقدور نیست.', 105 : 'پسوند فایل نامعتبر.', 109 : 'درخواست نامعتبر.', 110 : 'خطای ناشناخته.', 115 : 'یک فایل یا پوشه با همین نام از قبل وجود دارد.', 116 : 'پوشه یافت نشد. لطفا بروزرسانی کرده و مجددا تلاش کنید.', 117 : 'فایل یافت نشد. لطفا فهرست فایلها را بروزرسانی کرده و مجددا تلاش کنید.', 118 : 'منبع و مقصد مسیر یکی است.', 201 : 'یک فایل با همان نام از قبل موجود است. فایل آپلود شده به "%1" تغییر نام یافت.', 202 : 'فایل نامعتبر', 203 : 'فایل نامعتبر. اندازه فایل بیش از حد بزرگ است.', 204 : 'فایل آپلود شده خراب است.', 205 : 'هیچ پوشه موقتی برای آپلود فایل در سرور موجود نیست.', 206 : 'آپلود به دلایل امنیتی متوقف شد. فایل محتوی اطلاعات HTML است.', 207 : 'فایل آپلود شده به "%1" تغییر نام یافت.', 300 : 'جابجایی فایل(ها) ناموفق ماند.', 301 : 'کپی کردن فایل(ها) ناموفق ماند.', 500 : 'مرورگر فایل به دلایل امنیتی غیر فعال است. لطفا با مدیر سامانه تماس بگیرید تا تنظیمات این بخش را بررسی نماید.', 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 English * language. This is the base file for all translations. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['he'] = { 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 : 'rtl', HelpLang : 'en', LangCode : 'he', // 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 : 'תיקיות', 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 : 'שגיאה %e בקובץ %s', 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 : 'יצירת תמונה מוקטנת (Thumbnail)', 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 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 Latvian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['lv'] = { 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 : 'Darīts!', cancel : 'Atcelt', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Atcelt', redo : 'Atkārtot', 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 : 'lv', // 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 : 'Mapes', FolderLoading : 'Ielādē...', FolderNew : 'Lūdzu ierakstiet mapes nosaukumu: ', FolderRename : 'Lūdzu ierakstiet jauno mapes nosaukumu: ', FolderDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst mapi "%1"?', FolderRenaming : ' (Pārsauc...)', FolderDeleting : ' (Dzēš...)', // Files FileRename : 'Lūdzu ierakstiet jauno faila nosaukumu: ', FileRenameExt : 'Vai tiešām vēlaties mainīt faila paplašinājumu? Fails var palikt nelietojams.', FileRenaming : 'Pārsauc...', FileDelete : 'Vai tiešām vēlaties neatgriezeniski dzēst failu "%1"?', FilesLoading : 'Ielādē...', 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 : 'Augšupielādēt', UploadTip : 'Augšupielādēt jaunu failu', Refresh : 'Pārlādēt', Settings : 'Uzstādījumi', Help : 'Palīdzība', HelpTip : 'Palīdzība', // Context Menus Select : 'Izvēlēties', SelectThumbnail : 'Izvēlēties sīkbildi', View : 'Skatīt', Download : 'Lejupielādēt', NewSubFolder : 'Jauna apakšmape', Rename : 'Pārsaukt', Delete : 'Dzēst', 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 : 'Labi', CancelBtn : 'Atcelt', CloseBtn : 'Aizvērt', // Upload Panel UploadTitle : 'Jauna faila augšupielādēšana', UploadSelectLbl : 'Izvēlaties failu, ko augšupielādēt', UploadProgressLbl : '(Augšupielādē, lūdzu uzgaidiet...)', UploadBtn : 'Augšupielādēt izvēlēto failu', UploadBtnCancel : 'Atcelt', UploadNoFileMsg : 'Lūdzu izvēlaties failu no sava datora.', 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 : 'Uzstādījumi', SetView : 'Attēlot:', SetViewThumb : 'Sīkbildes', SetViewList : 'Failu Sarakstu', SetDisplay : 'Rādīt:', SetDisplayName : 'Faila Nosaukumu', SetDisplayDate : 'Datumu', SetDisplaySize : 'Faila Izmēru', SetSort : 'Kārtot:', SetSortName : 'pēc Faila Nosaukuma', SetSortDate : 'pēc Datuma', SetSortSize : 'pēc Izmēra', // Status Bar FilesCountEmpty : '<Tukša mape>', FilesCountOne : '1 fails', FilesCountMany : '%1 faili', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Nebija iespējams pabeigt pieprasījumu. (Kļūda %1)', Errors : { 10 : 'Nederīga komanda.', 11 : 'Resursa veids netika norādīts pieprasījumā.', 12 : 'Pieprasītais resursa veids nav derīgs.', 102 : 'Nederīgs faila vai mapes nosaukums.', 103 : 'Nav iespējams pabeigt pieprasījumu, autorizācijas aizliegumu dēļ.', 104 : 'Nav iespējams pabeigt pieprasījumu, failu sistēmas atļauju ierobežojumu dēļ.', 105 : 'Neatļauts faila paplašinājums.', 109 : 'Nederīgs pieprasījums.', 110 : 'Nezināma kļūda.', 115 : 'Fails vai mape ar šādu nosaukumu jau pastāv.', 116 : 'Mape nav atrasta. Lūdzu pārlādējiet šo logu un mēģiniet vēlreiz.', 117 : 'Fails nav atrasts. Lūdzu pārlādējiet failu sarakstu un mēģiniet vēlreiz.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Fails ar šādu nosaukumu jau eksistē. Augšupielādētais fails tika pārsaukts par "%1".', 202 : 'Nederīgs fails.', 203 : 'Nederīgs fails. Faila izmērs pārsniedz pieļaujamo.', 204 : 'Augšupielādētais fails ir bojāts.', 205 : 'Neviena pagaidu mape nav pieejama priekš augšupielādēšanas uz servera.', 206 : 'Augšupielāde atcelta drošības apsvērumu dēļ. Fails satur HTML veida datus.', 207 : 'Augšupielādētais fails tika pārsaukts par "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Failu pārlūks ir atslēgts drošības apsvērumu dēļ. Lūdzu sazinieties ar šīs sistēmas tehnisko administratoru vai pārbaudiet CKFinder konfigurācijas failu.', 501 : 'Sīkbilžu atbalsts ir atslēgts.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Faila nosaukumā nevar būt tukšums.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Mapes nosaukumā nevar būt tukšums.', FileInvChar : 'Faila nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |', FolderInvChar : 'Mapes nosaukums nedrīkst saturēt nevienu no sekojošajām zīmēm: \n\\ / : * ? " < > |', PopupBlockView : 'Nav iespējams failu atvērt jaunā logā. Lūdzu veiciet izmaiņas uzstādījumos savai interneta pārlūkprogrammai un izslēdziet visus uznirstošo logu bloķētājus šai adresei.', 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 : 'Platums', height : 'Augstums', 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 : 'Nemainīga Augstuma/Platuma attiecība', resetSize : 'Atjaunot sākotnējo izmēru' }, // Fileeditor plugin Fileeditor : { save : 'Saglabāt', 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 Norwegian * Nynorsk language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['no'] = { 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 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 Latin American Spanish * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['es-mx'] = { 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-mx', LangCode : 'es-mx', // 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 archivo: ', FileRenameExt : '¿Está seguro de querer cambiar la extensión del archivo? El archivo puede dejar de ser usable.', FileRenaming : 'Renombrando...', FileDelete : '¿Está seguro de que quiere borrar el archivo "%1".?', FilesLoading : 'Cargando...', FilesEmpty : 'Carpeta vacía', FilesMoved : 'Archivo %1 movido a %2:%3.', FilesCopied : 'Archivo %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 archivos de la cesta?', BasketRemoveConfirm : '¿Está seguro de querer quitar el archivo "%1" de la cesta?', BasketEmpty : 'No hay archivos en la cesta, arrastra y suelta algunos.', BasketCopyFilesHere : 'Copiar archivos de la cesta', BasketMoveFilesHere : 'Mover archivos 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 archivo', 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 archivo aquí', MoveDragDrop : 'Mover archivo aquí', // Dialogs RenameDlgTitle : 'Renombrar', NewNameDlgTitle : 'Nuevo nombre', FileExistsDlgTitle : 'Archivo existente', SysErrorDlgTitle : 'Error de sistema', FileOverwrite : 'Sobreescribir', FileAutorename : 'Auto-renombrar', // Generic OkBtn : 'Aceptar', CancelBtn : 'Cancelar', CloseBtn : 'Cerrar', // Upload Panel UploadTitle : 'Añadir nuevo archivo', UploadSelectLbl : 'Elija el archivo a subir', UploadProgressLbl : '(Subida en progreso, por favor espere...)', UploadBtn : 'Subir el archivo elegido', UploadBtnCancel : 'Cancelar', UploadNoFileMsg : 'Por favor, elija un archivo de su computadora.', UploadNoFolder : 'Por favor, escoja la carpeta antes de iniciar la subida.', UploadNoPerms : 'No puede subir archivos.', UploadUnknError : 'Error enviando el archivo.', UploadExtIncorrect : 'La extensión del archivo no está permitida en esta carpeta.', // Flash Uploads UploadLabel : 'Archivos a subir', UploadTotalFiles : 'Total de archivos:', UploadTotalSize : 'Tamaño total:', UploadAddFiles : 'Añadir archivos', UploadClearFiles : 'Borrar archivos', 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 archivo', SetDisplayDate : 'Fecha', SetDisplaySize : 'Tamaño del archivo', SetSort : 'Ordenar:', SetSortName : 'por Nombre', SetSortDate : 'por Fecha', SetSortSize : 'por Tamaño', // Status Bar FilesCountEmpty : '<Carpeta vacía>', FilesCountOne : '1 archivo', FilesCountMany : '%1 archivos', // 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 archivo 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 archivos.', 105 : 'La extensión del archivo no es válida.', 109 : 'Petición inválida.', 110 : 'Error desconocido.', 115 : 'Ya existe un archivo 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 archivo. Por favor, actualice la lista de archivos y pruebe de nuevo.', 118 : 'Las rutas origen y destino son iguales.', 201 : 'Ya existía un archivo con ese nombre. El archivo subido ha sido renombrado como "%1".', 202 : 'Archivo inválido.', 203 : 'Archivo inválido. El tamaño es demasiado grande.', 204 : 'El archivo 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 archivo contenía código HTML.', 207 : 'El archivo subido ha sido renombrado como "%1".', 300 : 'Ha fallado el mover el(los) archivo(s).', 301 : 'Ha fallado el copiar el(los) archivo(s).', 500 : 'El navegador de archivos está deshabilitado por razones de seguridad. Por favor, contacte con el administrador de su sistema y compruebe el archivo de configuración de CKFinder.', 501 : 'El soporte para iconos está deshabilitado.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'El nombre del archivo no puede estar vacío.', FileExists : 'El archivo %s ya existe.', FolderEmpty : 'El nombre de la carpeta no puede estar vacío.', FileInvChar : 'El nombre del archivo 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 archivo 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 archivo.', fileSaveSuccess : 'Archivo guardado correctamente.', contextMenuName : 'Editar', loadingFile : 'Cargando archivo, por favor espere...' }, Maximize : { maximize : 'Maximizar', minimize : 'Minimizar' } };
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 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 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 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 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 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
/* * 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 Estonian * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['et'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, pole saadaval</span>', confirmCancel : 'Mõned valikud on muudetud. Kas oled kindel, et tahad dialoogiakna sulgeda?', ok : 'Olgu', cancel : 'Loobu', confirmationTitle : 'Kinnitus', messageTitle : 'Andmed', inputTitle : 'Küsimus', undo : 'Võta tagasi', redo : 'Tee uuesti', skip : 'Jäta vahele', skipAll : 'Jäta kõik vahele', makeDecision : 'Mida tuleks teha?', rememberDecision: 'Jäta valik meelde' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'et', // 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 : ['EL', 'PL'], // Folders FoldersTitle : 'Kaustad', FolderLoading : 'Laadimine...', FolderNew : 'Palun sisesta uue kataloogi nimi: ', FolderRename : 'Palun sisesta uue kataloogi nimi: ', FolderDelete : 'Kas tahad kindlasti kausta "%1" kustutada?', FolderRenaming : ' (ümbernimetamine...)', FolderDeleting : ' (kustutamine...)', // Files FileRename : 'Palun sisesta faili uus nimi: ', FileRenameExt : 'Kas oled kindel, et tahad faili laiendit muuta? Fail võib muutuda kasutamatuks.', FileRenaming : 'Ümbernimetamine...', FileDelete : 'Kas oled kindel, et tahad kustutada faili "%1"?', FilesLoading : 'Laadimine...', FilesEmpty : 'See kaust on tühi.', FilesMoved : 'Fail %1 liigutati kohta %2:%3.', FilesCopied : 'Fail %1 kopeeriti kohta %2:%3.', // Basket BasketFolder : 'Korv', BasketClear : 'Tühjenda korv', BasketRemove : 'Eemalda korvist', BasketOpenFolder : 'Ava ülemine kaust', BasketTruncateConfirm : 'Kas tahad tõesti eemaldada korvist kõik failid?', BasketRemoveConfirm : 'Kas tahad tõesti eemaldada korvist faili "%1"?', BasketEmpty : 'Korvis ei ole ühtegi faili, lohista mõni siia.', BasketCopyFilesHere : 'Failide kopeerimine korvist', BasketMoveFilesHere : 'Failide liigutamine korvist', BasketPasteErrorOther : 'Faili %s viga: %e', BasketPasteMoveSuccess : 'Järgnevad failid liigutati: %s', BasketPasteCopySuccess : 'Järgnevad failid kopeeriti: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Laadi üles', UploadTip : 'Laadi üles uus fail', Refresh : 'Värskenda', Settings : 'Sätted', Help : 'Abi', HelpTip : 'Abi', // Context Menus Select : 'Vali', SelectThumbnail : 'Vali pisipilt', View : 'Kuva', Download : 'Laadi alla', NewSubFolder : 'Uus alamkaust', Rename : 'Nimeta ümber', Delete : 'Kustuta', CopyDragDrop : 'Kopeeri fail siia', MoveDragDrop : 'Liiguta fail siia', // Dialogs RenameDlgTitle : 'Ümbernimetamine', NewNameDlgTitle : 'Uue nime andmine', FileExistsDlgTitle : 'Fail on juba olemas', SysErrorDlgTitle : 'Süsteemi viga', FileOverwrite : 'Kirjuta üle', FileAutorename : 'Nimeta automaatselt ümber', // Generic OkBtn : 'Olgu', CancelBtn : 'Loobu', CloseBtn : 'Sulge', // Upload Panel UploadTitle : 'Uue faili üleslaadimine', UploadSelectLbl : 'Vali üleslaadimiseks fail', UploadProgressLbl : '(Üleslaadimine, palun oota...)', UploadBtn : 'Laadi valitud fail üles', UploadBtnCancel : 'Loobu', UploadNoFileMsg : 'Palun vali fail oma arvutist.', UploadNoFolder : 'Palun vali enne üleslaadimist kataloog.', UploadNoPerms : 'Failide üleslaadimine pole lubatud.', UploadUnknError : 'Viga faili saatmisel.', UploadExtIncorrect : 'Selline faili laiend pole selles kaustas lubatud.', // Flash Uploads UploadLabel : 'Üleslaaditavad failid', UploadTotalFiles : 'Faile kokku:', UploadTotalSize : 'Kogusuurus:', UploadAddFiles : 'Lisa faile', UploadClearFiles : 'Eemalda failid', UploadCancel : 'Katkesta üleslaadimine', UploadRemove : 'Eemalda', UploadRemoveTip : 'Eemalda !f', UploadUploaded : '!n% üles laaditud', UploadProcessing : 'Töötlemine...', // Settings Panel SetTitle : 'Sätted', SetView : 'Vaade:', SetViewThumb : 'Pisipildid', SetViewList : 'Loend', SetDisplay : 'Kuva:', SetDisplayName : 'Faili nimi', SetDisplayDate : 'Kuupäev', SetDisplaySize : 'Faili suurus', SetSort : 'Sortimine:', SetSortName : 'faili nime järgi', SetSortDate : 'kuupäeva järgi', SetSortSize : 'suuruse järgi', // Status Bar FilesCountEmpty : '<tühi kaust>', FilesCountOne : '1 fail', FilesCountMany : '%1 faili', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Päringu täitmine ei olnud võimalik. (Viga %1)', Errors : { 10 : 'Vigane käsk.', 11 : 'Allika liik ei olnud päringus määratud.', 12 : 'Päritud liik ei ole sobiv.', 102 : 'Sobimatu faili või kausta nimi.', 103 : 'Piiratud õiguste tõttu ei olnud võimalik päringut lõpetada.', 104 : 'Failisüsteemi piiratud õiguste tõttu ei olnud võimalik päringut lõpetada.', 105 : 'Sobimatu faililaiend.', 109 : 'Vigane päring.', 110 : 'Tundmatu viga.', 115 : 'Sellenimeline fail või kaust on juba olemas.', 116 : 'Kausta ei leitud. Palun värskenda lehte ja proovi uuesti.', 117 : 'Faili ei leitud. Palun värskenda lehte ja proovi uuesti.', 118 : 'Lähte- ja sihtasukoht on sama.', 201 : 'Samanimeline fail on juba olemas. Üles laaditud faili nimeks pandi "%1".', 202 : 'Vigane fail.', 203 : 'Vigane fail. Fail on liiga suur.', 204 : 'Üleslaaditud fail on rikutud.', 205 : 'Serverisse üleslaadimiseks pole ühtegi ajutiste failide kataloogi.', 206 : 'Üleslaadimine katkestati turvakaalutlustel. Fail sisaldab HTMLi sarnaseid andmeid.', 207 : 'Üleslaaditud faili nimeks pandi "%1".', 300 : 'Faili(de) liigutamine nurjus.', 301 : 'Faili(de) kopeerimine nurjus.', 500 : 'Failide sirvija on turvakaalutlustel keelatud. Palun võta ühendust oma süsteemi administraatoriga ja kontrolli CKFinderi seadistusfaili.', 501 : 'Pisipiltide tugi on keelatud.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Faili nimi ei tohi olla tühi.', FileExists : 'Fail nimega %s on juba olemas.', FolderEmpty : 'Kausta nimi ei tohi olla tühi.', FileInvChar : 'Faili nimi ei tohi sisaldada ühtegi järgnevatest märkidest: \n\\ / : * ? " < > |', FolderInvChar : 'Faili nimi ei tohi sisaldada ühtegi järgnevatest märkidest: \n\\ / : * ? " < > |', PopupBlockView : 'Faili avamine uues aknas polnud võimalik. Palun seadista oma brauserit ning keela kõik hüpikakende blokeerijad selle saidi jaoks.', XmlError : 'XML vastust veebiserverist polnud võimalik korrektselt laadida.', XmlEmpty : 'XML vastust veebiserverist polnud võimalik korrektselt laadida. Serveri vastus oli tühi.', XmlRawResponse : 'Serveri vastus toorkujul: %s' }, // Imageresize plugin Imageresize : { dialogTitle : '%s suuruse muutmine', sizeTooBig : 'Pildi kõrgust ega laiust ei saa määrata suuremaks pildi esialgsest vastavast mõõtmest (%size).', resizeSuccess : 'Pildi suuruse muutmine õnnestus.', thumbnailNew : 'Tee uus pisipilt', thumbnailSmall : 'Väike (%s)', thumbnailMedium : 'Keskmine (%s)', thumbnailLarge : 'Suur (%s)', newSize : 'Määra uus suurus', width : 'Laius', height : 'Kõrgus', invalidHeight : 'Sobimatu kõrgus.', invalidWidth : 'Sobimatu laius.', invalidName : 'Sobimatu faili nimi.', newImage : 'Loo uus pilt', noExtensionChange : 'Faili laiendit pole võimalik muuta.', imageSmall : 'Lähtepilt on liiga väike.', contextMenuName : 'Muuda suurust', lockRatio : 'Lukusta külgede suhe', resetSize : 'Lähtesta suurus' }, // Fileeditor plugin Fileeditor : { save : 'Salvesta', fileOpenError : 'Faili avamine pole võimalik.', fileSaveSuccess : 'Faili salvestamine õnnestus.', contextMenuName : 'Muuda', loadingFile : 'Faili laadimine, palun oota...' }, Maximize : { maximize : 'Maksimeeri', minimize : 'Minimeeri' } };
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 Brazilian Portuguese * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['pt-br'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, indisponível</span>', confirmCancel : 'Algumas opções foram modificadas. Deseja fechar a janela realmente?', ok : 'OK', cancel : 'Cancelar', confirmationTitle : 'Confirmação', messageTitle : 'Informação', inputTitle : 'Pergunta', undo : 'Desfazer', redo : 'Refazer', skip : 'Ignorar', skipAll : 'Ignorar todos', makeDecision : 'Que ação deve ser tomada?', rememberDecision: 'Lembra minha decisão' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'en', LangCode : 'pt-br', // 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 : 'Pastas', FolderLoading : 'Carregando...', FolderNew : 'Favor informar o nome da nova pasta: ', FolderRename : 'Favor informar o nome da nova pasta: ', FolderDelete : 'Você tem certeza que deseja apagar a pasta "%1"?', FolderRenaming : ' (Renomeando...)', FolderDeleting : ' (Apagando...)', // Files FileRename : 'Favor informar o nome do novo arquivo: ', FileRenameExt : 'Você tem certeza que deseja alterar a extensão do arquivo? O arquivo pode ser danificado.', FileRenaming : 'Renomeando...', FileDelete : 'Você tem certeza que deseja apagar o arquivo "%1"?', FilesLoading : 'Carregando...', FilesEmpty : 'Pasta vazia', FilesMoved : 'Arquivo %1 movido para %2:%3.', FilesCopied : 'Arquivo %1 copiado em %2:%3.', // Basket BasketFolder : 'Cesta', BasketClear : 'Limpa Cesta', BasketRemove : 'Remove da cesta', BasketOpenFolder : 'Abre a pasta original', BasketTruncateConfirm : 'Remover todos os arquivas da cesta?', BasketRemoveConfirm : 'Remover o arquivo "%1" da cesta?', BasketEmpty : 'Nenhum arquivo na cesta, arraste alguns antes.', BasketCopyFilesHere : 'Copia Arquivos da Cesta', BasketMoveFilesHere : 'Move os Arquivos da Cesta', BasketPasteErrorOther : 'Arquivo %s erro: %e', BasketPasteMoveSuccess : 'Os seguintes arquivos foram movidos: %s', BasketPasteCopySuccess : 'Os sequintes arquivos foram copiados: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Enviar arquivo', UploadTip : 'Enviar novo arquivo', Refresh : 'Atualizar', Settings : 'Configurações', Help : 'Ajuda', HelpTip : 'Ajuda', // Context Menus Select : 'Selecionar', SelectThumbnail : 'Selecionar miniatura', View : 'Visualizar', Download : 'Download', NewSubFolder : 'Nova sub-pasta', Rename : 'Renomear', Delete : 'Apagar', CopyDragDrop : 'Copia arquivo aqui', MoveDragDrop : 'Move arquivo aqui', // Dialogs RenameDlgTitle : 'Renomeia', NewNameDlgTitle : 'Novo nome', FileExistsDlgTitle : 'O arquivo já existe', SysErrorDlgTitle : 'Erro de Sistema', FileOverwrite : 'Sobrescrever', FileAutorename : 'Renomeia automaticamente', // Generic OkBtn : 'OK', CancelBtn : 'Cancelar', CloseBtn : 'Fechar', // Upload Panel UploadTitle : 'Enviar novo arquivo', UploadSelectLbl : 'Selecione o arquivo para enviar', UploadProgressLbl : '(Enviado arquivo, favor aguardar...)', UploadBtn : 'Enviar arquivo selecionado', UploadBtnCancel : 'Cancelar', UploadNoFileMsg : 'Favor selecionar o arquivo no seu computador.', UploadNoFolder : 'Favor selecionar a pasta antes the enviar o arquivo.', UploadNoPerms : 'Não é permitido o envio de arquivos.', UploadUnknError : 'Erro no envio do arquivo.', UploadExtIncorrect : 'A extensão deste arquivo não é permitida nesat pasta.', // Flash Uploads UploadLabel : 'Arquivos para Enviar', UploadTotalFiles : 'Arquivos:', UploadTotalSize : 'Tamanho:', UploadAddFiles : 'Adicionar Arquivos', UploadClearFiles : 'Remover Arquivos', UploadCancel : 'Cancelar Envio', UploadRemove : 'Remover', UploadRemoveTip : 'Remover !f', UploadUploaded : '!n% enviado', UploadProcessing : 'Processando...', // Settings Panel SetTitle : 'Configurações', SetView : 'Visualizar:', SetViewThumb : 'Miniaturas', SetViewList : 'Lista', SetDisplay : 'Exibir:', SetDisplayName : 'Arquivo', SetDisplayDate : 'Data', SetDisplaySize : 'Tamanho', SetSort : 'Ordenar:', SetSortName : 'por Nome do arquivo', SetSortDate : 'por Data', SetSortSize : 'por Tamanho', // Status Bar FilesCountEmpty : '<Pasta vazia>', FilesCountOne : '1 arquivo', FilesCountMany : '%1 arquivos', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Não foi possível completer o seu pedido. (Erro %1)', Errors : { 10 : 'Comando inválido.', 11 : 'O tipo de recurso não foi especificado na solicitação.', 12 : 'O recurso solicitado não é válido.', 102 : 'Nome do arquivo ou pasta inválido.', 103 : 'Não foi possível completar a solicitação por restrições de acesso.', 104 : 'Não foi possível completar a solicitação por restrições de acesso do sistema de arquivos.', 105 : 'Extensão de arquivo inválida.', 109 : 'Solicitação inválida.', 110 : 'Erro desconhecido.', 115 : 'Uma arquivo ou pasta já existe com esse nome.', 116 : 'Pasta não encontrada. Atualize e tente novamente.', 117 : 'Arquivo não encontrado. Atualize a lista de arquivos e tente novamente.', 118 : 'Origem e destino são iguais.', 201 : 'Um arquivo com o mesmo nome já está disponível. O arquivo enviado foi renomeado para "%1".', 202 : 'Arquivo inválido.', 203 : 'Arquivo inválido. O tamanho é muito grande.', 204 : 'O arquivo enviado está corrompido.', 205 : 'Nenhuma pasta temporária para envio está disponível no servidor.', 206 : 'Transmissão cancelada por razões de segurança. O arquivo contem dados HTML.', 207 : 'O arquivo enviado foi renomeado para "%1".', 300 : 'Não foi possível mover o(s) arquivo(s).', 301 : 'Não foi possível copiar o(s) arquivos(s).', 500 : 'A navegação de arquivos está desativada por razões de segurança. Contacte o administrador do sistema.', 501 : 'O suporte a miniaturas está desabilitado.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'O nome do arquivo não pode ser vazio.', FileExists : 'O nome %s já é em uso.', FolderEmpty : 'O nome da pasta não pode ser vazio.', FileInvChar : 'O nome do arquivo não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |', FolderInvChar : 'O nome da pasta não pode conter nenhum desses caracteres: \n\\ / : * ? " < > |', PopupBlockView : 'Não foi possível abrir o arquivo em outra janela. Configure seu navegador e desabilite o bloqueio a popups para esse site.', XmlError : 'Não foi possível carregar a resposta XML enviada pelo servidor.', XmlEmpty : 'Não foi possível carregar a resposta XML enviada pelo servidor. Resposta vazia..', XmlRawResponse : 'Resposta original enviada pelo servidor: %s' }, // Imageresize plugin Imageresize : { dialogTitle : 'Redimensionar %s', sizeTooBig : 'Não possível usar dimensões maiores do que as originais (%size).', resizeSuccess : 'Imagem redimensionada corretamente.', thumbnailNew : 'Cria nova anteprima', thumbnailSmall : 'Pequeno (%s)', thumbnailMedium : 'Médio (%s)', thumbnailLarge : 'Grande (%s)', newSize : 'Novas dimensões', width : 'Largura', height : 'Altura', invalidHeight : 'Altura incorreta.', invalidWidth : 'Largura incorreta.', invalidName : 'O nome do arquivo não é válido.', newImage : 'Cria nova imagem', noExtensionChange : 'A extensão do arquivo não pode ser modificada.', imageSmall : 'A imagem original é muito pequena.', contextMenuName : 'Redimensionar', lockRatio : 'Travar Proporções', resetSize : 'Redefinir para o Tamanho Original' }, // Fileeditor plugin Fileeditor : { save : 'Salva', fileOpenError : 'Não é possível abrir o arquivo.', fileSaveSuccess : 'Arquivo salvado corretamente.', contextMenuName : 'Modificar', loadingFile : 'Carregando arquivo. Por favor aguarde...' }, Maximize : { maximize : 'Maximizar', minimize : 'Minimizar' } };
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 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 Czech * language. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['cs'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nedostupné</span>', confirmCancel : 'Některá z nastavení byla změněna. Skutečně chete zavřít dialogové okno?', ok : 'OK', cancel : 'Zrušit', confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Zpět', 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 : 'cs', // 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 : 'Složky', FolderLoading : 'Načítání...', FolderNew : 'Zadejte jméno nové složky: ', FolderRename : 'Zadejte nové jméno složky: ', FolderDelete : 'Opravdu chcete smazat složku "%1"?', FolderRenaming : ' (Přejmenovávám...)', FolderDeleting : ' (Mažu...)', // Files FileRename : 'Zadejte jméno novéhho souboru: ', FileRenameExt : 'Opravdu chcete změnit příponu souboru, může se stát nečitelným.', FileRenaming : 'Přejmenovávám...', FileDelete : 'Opravdu chcete smazat soubor "%1"?', FilesLoading : 'Načítání...', FilesEmpty : 'Prázdná složka.', 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 : 'Nahrát', UploadTip : 'Nahrát nový soubor', Refresh : 'Načíst znova', Settings : 'Nastavení', Help : 'Pomoc', HelpTip : 'Pomoc', // Context Menus Select : 'Vybrat', SelectThumbnail : 'Vybrat náhled', View : 'Zobrazit', Download : 'Uložit jako', NewSubFolder : 'Nová podsložka', Rename : 'Přejmenovat', Delete : 'Smazat', 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šit', CloseBtn : 'Zavřít', // Upload Panel UploadTitle : 'Nahrát nový soubor', UploadSelectLbl : 'Zvolit soubor k nahrání', UploadProgressLbl : '(Nahrávám, čekejte...)', UploadBtn : 'Nahrát zvolený soubor', UploadBtnCancel : 'Zrušit', UploadNoFileMsg : 'Vyberte prosím soubor.', 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 : 'Nastavení', SetView : 'Zobrazení:', SetViewThumb : 'Náhledy', SetViewList : 'Seznam', SetDisplay : 'Informace:', SetDisplayName : 'Název', SetDisplayDate : 'Datum', SetDisplaySize : 'Velikost', SetSort : 'Seřazení:', SetSortName : 'Podle jména', SetSortDate : 'Podle data', SetSortSize : 'Podle velikosti', // Status Bar FilesCountEmpty : '<Prázdná složka>', FilesCountOne : '1 soubor', FilesCountMany : '%1 soubor', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Nebylo možno dokončit příkaz. (Error %1)', Errors : { 10 : 'Neplatný příkaz.', 11 : 'Požadovaný typ prostředku nebyl specifikován v dotazu.', 12 : 'Požadovaný typ prostředku není validní.', 102 : 'Šatné jméno souboru, nebo složky.', 103 : 'Nebylo možné dokončit příkaz kvůli autorizačním omezením.', 104 : 'Nebylo možné dokončit příkaz kvůli omezeným přístupovým právům k souborům.', 105 : 'Špatná přípona souboru.', 109 : 'Neplatný příkaz.', 110 : 'Neznámá chyba.', 115 : 'Již existuje soubor nebo složka se stejným jménem.', 116 : 'Složka nenalezena, prosím obnovte stránku.', 117 : 'Soubor nenalezen, prosím obnovte stránku.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Již existoval soubor se stejným jménem, nahraný soubor byl přejmenován na "%1".', 202 : 'Špatný soubor.', 203 : 'Špatný soubor. Příliš velký.', 204 : 'Nahraný soubor je poškozen.', 205 : 'Na serveru není dostupná dočasná složka.', 206 : 'Nahrávání zrušeno z bezpečnostních důvodů. Soubor obsahuje data podobná HTML.', 207 : 'Nahraný soubor byl přejmenován na "%1".', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Nahrávání zrušeno z bezpečnostních důvodů. Zdělte to prosím administrátorovi a zkontrolujte nastavení CKFinderu.', 501 : 'Podpora náhledů je vypnuta.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Název souboru nemůže být prázdný.', FileExists : 'File %s already exists.', // MISSING FolderEmpty : 'Název složky nemůže být prázdný.', FileInvChar : 'Název souboru nesmí obsahovat následující znaky: \n\\ / : * ? " < > |', FolderInvChar : 'Název složky nesmí obsahovat následující znaky: \n\\ / : * ? " < > |', PopupBlockView : 'Nebylo možné otevřít soubor do nového okna. Prosím nastavte si prohlížeč aby neblokoval vyskakovací okna.', 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 : 'Šířka', 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ámek', resetSize : 'Původní velikost' }, // Fileeditor plugin Fileeditor : { save : 'Uložit', fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING }, Maximize : { maximize : 'Maximalizovat', minimize : 'Minimalizovat' } };
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 Finnish * language. Translated into Finnish 2010-12-15 by Petteri Salmela, * updated. */ /** * Contains the dictionary of language entries. * @namespace */ CKFinder.lang['fi'] = { appTitle : 'CKFinder', // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, ei käytettävissä</span>', confirmCancel : 'Valintoja on muutettu. Suljetaanko ikkuna kuitenkin?', ok : 'OK', cancel : 'Peru', confirmationTitle : 'Varmistus', messageTitle : 'Ilmoitus', inputTitle : 'Kysymys', undo : 'Peru', redo : 'Tee uudelleen', skip : 'Ohita', skipAll : 'Ohita kaikki', makeDecision : 'Mikä toiminto suoritetaan?', rememberDecision: 'Muista valintani' }, // Language direction, 'ltr' or 'rtl'. dir : 'ltr', HelpLang : 'fi', LangCode : 'fi', // 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 : 'Kansiot', FolderLoading : 'Lataan...', FolderNew : 'Kirjoita uuden kansion nimi: ', FolderRename : 'Kirjoita uusi nimi kansiolle ', FolderDelete : 'Haluatko varmasti poistaa kansion "%1"?', FolderRenaming : ' (Uudelleennimeää...)', FolderDeleting : ' (Poistaa...)', // Files FileRename : 'Kirjoita uusi tiedostonimi: ', FileRenameExt : 'Haluatko varmasti muuttaa tiedostotarkennetta? Tiedosto voi muuttua käyttökelvottomaksi.', FileRenaming : 'Uudelleennimeää...', FileDelete : 'Haluatko varmasti poistaa tiedoston "%1"?', FilesLoading : 'Lataa...', FilesEmpty : 'Tyhjä kansio.', FilesMoved : 'Tiedosto %1 siirretty nimelle %2:%3.', FilesCopied : 'Tiedosto %1 kopioitu nimelle %2:%3.', // Basket BasketFolder : 'Kori', BasketClear : 'Tyhjennä kori', BasketRemove : 'Poista korista', BasketOpenFolder : 'Avaa ylemmän tason kansio', BasketTruncateConfirm : 'Haluatko todella poistaa kaikki tiedostot korista?', BasketRemoveConfirm : 'Haluatko todella poistaa tiedoston "%1" korista?', BasketEmpty : 'Korissa ei ole tiedostoja. Lisää raahaamalla.', BasketCopyFilesHere : 'Kopioi tiedostot korista.', BasketMoveFilesHere : 'Siirrä tiedostot korista.', BasketPasteErrorOther : 'Tiedoston %s virhe: %e.', BasketPasteMoveSuccess : 'Seuraavat tiedostot siirrettiin: %s', BasketPasteCopySuccess : 'Seuraavat tiedostot kopioitiin: %s', // Toolbar Buttons (some used elsewhere) Upload : 'Lataa palvelimelle', UploadTip : 'Lataa uusi tiedosto palvelimelle', Refresh : 'Päivitä', Settings : 'Asetukset', Help : 'Apua', HelpTip : 'Apua', // Context Menus Select : 'Valitse', SelectThumbnail : 'Valitse esikatselukuva', View : 'Näytä', Download : 'Lataa palvelimelta', NewSubFolder : 'Uusi alikansio', Rename : 'Uudelleennimeä ', Delete : 'Poista', CopyDragDrop : 'Kopioi tiedosto tähän', MoveDragDrop : 'Siirrä tiedosto tähän', // Dialogs RenameDlgTitle : 'Nimeä uudelleen', NewNameDlgTitle : 'Uusi nimi', FileExistsDlgTitle : 'Tiedostonimi on jo olemassa!', SysErrorDlgTitle : 'Järjestelmävirhe', FileOverwrite : 'Ylikirjoita', FileAutorename : 'Nimeä uudelleen automaattisesti', // Generic OkBtn : 'OK', CancelBtn : 'Peru', CloseBtn : 'Sulje', // Upload Panel UploadTitle : 'Lataa uusi tiedosto palvelimelle', UploadSelectLbl : 'Valitse ladattava tiedosto', UploadProgressLbl : '(Lataaminen palvelimelle käynnissä...)', UploadBtn : 'Lataa valittu tiedosto palvelimelle', UploadBtnCancel : 'Peru', UploadNoFileMsg : 'Valitse tiedosto tietokoneeltasi.', UploadNoFolder : 'Valitse kansio ennen palvelimelle lataamista.', UploadNoPerms : 'Tiedoston lataaminen palvelimelle evätty.', UploadUnknError : 'Tiedoston siirrossa tapahtui virhe.', UploadExtIncorrect : 'Tiedostotarkenne ei ole sallittu valitussa kansiossa.', // Flash Uploads UploadLabel : 'Ladattavat tiedostot', UploadTotalFiles : 'Tiedostoja yhteensä:', UploadTotalSize : 'Yhteenlaskettu tiedostokoko:', UploadAddFiles : 'Lisää tiedostoja', UploadClearFiles : 'Poista tiedostot', UploadCancel : 'Peru lataus', UploadRemove : 'Poista', UploadRemoveTip : 'Poista !f', UploadUploaded : 'Ladattu !n%', UploadProcessing : 'Käsittelee...', // Settings Panel SetTitle : 'Asetukset', SetView : 'Näkymä:', SetViewThumb : 'Esikatselukuvat', SetViewList : 'Luettelo', SetDisplay : 'Näytä:', SetDisplayName : 'Tiedostonimi', SetDisplayDate : 'Päivämäärä', SetDisplaySize : 'Tiedostokoko', SetSort : 'Lajittele:', SetSortName : 'aakkosjärjestykseen', SetSortDate : 'päivämäärän mukaan', SetSortSize : 'tiedostokoon mukaan', // Status Bar FilesCountEmpty : '<Tyhjä kansio>', FilesCountOne : '1 tiedosto', FilesCountMany : '%1 tiedostoa', // Size and Speed Kb : '%1 kt', KbPerSecond : '%1 kt/s', // Connector Error Messages. ErrorUnknown : 'Pyyntöä ei voitu suorittaa. (Virhe %1)', Errors : { 10 : 'Virheellinen komento.', 11 : 'Pyynnön resurssityyppi on määrittelemättä.', 12 : 'Pyynnön resurssityyppi on virheellinen.', 102 : 'Virheellinen tiedosto- tai kansionimi.', 103 : 'Oikeutesi eivät riitä pyynnön suorittamiseen.', 104 : 'Tiedosto-oikeudet eivät riitä pyynnön suorittamiseen.', 105 : 'Virheellinen tiedostotarkenne.', 109 : 'Virheellinen pyyntö.', 110 : 'Tuntematon virhe.', 115 : 'Samanniminen tiedosto tai kansio on jo olemassa.', 116 : 'Kansiota ei löydy. Yritä uudelleen kansiopäivityksen jälkeen.', 117 : 'Tiedostoa ei löydy. Yritä uudelleen kansiopäivityksen jälkeen.', 118 : 'Lähde- ja kohdekansio on sama!', 201 : 'Samanniminen tiedosto on jo olemassa. Palvelimelle ladattu tiedosto on nimetty: "%1".', 202 : 'Virheellinen tiedosto.', 203 : 'Virheellinen tiedosto. Tiedostokoko on liian suuri.', 204 : 'Palvelimelle ladattu tiedosto on vioittunut.', 205 : 'Väliaikaishakemistoa ei ole määritetty palvelimelle lataamista varten.', 206 : 'Palvelimelle lataaminen on peruttu turvallisuussyistä. Tiedosto sisältää HTML-tyylistä dataa.', 207 : 'Palvelimelle ladattu tiedosto on nimetty: "%1".', 300 : 'Tiedostosiirto epäonnistui.', 301 : 'Tiedostokopiointi epäonnistui.', 500 : 'Tiedostoselain on kytketty käytöstä turvallisuussyistä. Pyydä pääkäyttäjää tarkastamaan CKFinderin asetustiedosto.', 501 : 'Esikatselukuvien tuki on kytketty toiminnasta.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Tiedosto on nimettävä!', FileExists : 'Tiedosto %s on jo olemassa.', FolderEmpty : 'Kansio on nimettävä!', FileInvChar : 'Tiedostonimi ei voi sisältää seuraavia merkkejä: \n\\ / : * ? " < > |', FolderInvChar : 'Kansionimi ei voi sisältää seuraavia merkkejä: \n\\ / : * ? " < > |', PopupBlockView : 'Tiedostoa ei voitu avata uuteen ikkunaan. Salli selaimesi asetuksissa ponnahdusikkunat tälle sivulle.', 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 : 'Muuta kokoa %s', sizeTooBig : 'Kuvan mittoja ei voi asettaa alkuperäistä suuremmiksi(%size).', resizeSuccess : 'Kuvan koon muuttaminen onnistui.', thumbnailNew : 'Luo uusi esikatselukuva.', thumbnailSmall : 'Pieni (%s)', thumbnailMedium : 'Keskikokoinen (%s)', thumbnailLarge : 'Suuri (%s)', newSize : 'Aseta uusi koko', width : 'Leveys', height : 'Korkeus', invalidHeight : 'Viallinen korkeus.', invalidWidth : 'Viallinen leveys.', invalidName : 'Viallinen tiedostonimi.', newImage : 'Luo uusi kuva', noExtensionChange : 'Tiedostomäärettä ei voi vaihtaa.', imageSmall : 'Lähdekuva on liian pieni.', contextMenuName : 'Muuta kokoa', lockRatio : 'Lukitse suhteet', resetSize : 'Alkuperäinen koko' }, // Fileeditor plugin Fileeditor : { save : 'Tallenna', fileOpenError : 'Tiedostoa ei voi avata.', fileSaveSuccess : 'Tiedoston tallennus onnistui.', contextMenuName : 'Muokkaa', loadingFile : 'Tiedostoa ladataan ...' }, Maximize : { maximize : 'Suurenna', minimize : 'Pienennä' } };
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 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 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