code stringlengths 1 2.08M | language stringclasses 1
value |
|---|---|
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function() {
var a = (function() {
var f = {
jY : 'B8MI1HT',
_ : {},
status : 'unloaded',
basePath : (function() {
var i = window.CKFINDER_BASEPATH || '';
if (!i) {
var j = document.getElementsByTagName('script');
for ( var k = 0; k < j.length; k++) {
var l = j[k].src
.match(/(^|.*[\\\/])CKFINDER(?:_basic)?(?:_v2)?(?:_source)?.js(?:\?.*)?$/i);
if (l) {
i = l[1];
break;
}
}
}
if (i.indexOf('://') == -1)
if (i.indexOf('/') === 0)
i = location.href.match(/^.*?:\/\/[^\/]*/)[0] + i;
else
i = location.href.match(/^[^\?]*\/(?:)/)[0] + i;
return i;
})(),
getUrl : function(i) {
if (i.indexOf('://') == -1 && i.indexOf('/') !== 0)
i = this.basePath + i;
if (this.jY && i.charAt(i.length - 1) != '/')
i += (i.indexOf('?') >= 0 ? '&' : '?') + 't=' + this.jY;
return i;
}
}, g = window.CKFINDER_GETURL;
if (g) {
var h = f.getUrl;
f.getUrl = function(i) {
return g.call(f, i) || h.call(f, i);
};
}
return f;
})();
function b(f) {
return a.instances[f];
}
;
var c = {
callback : 1,
selectThumbnailActionFunction : 1,
selectActionFunction : 1
};
a.jd = function() {
var h = this;
var f = {};
for ( var g in h) {
if (!h.hasOwnProperty(g))
continue;
if (typeof h[g] == 'function' && !c[g])
continue;
f[g] = h[g];
}
if (h.callback)
f.callback = h.callback;
return f;
};
a.lj = function(f) {
var i = this;
f = f || i.basePath;
var g = '';
if (!f || f.length === 0)
f = CKFinder.DEFAULT_basePath;
if (f.substr(f.length - 1, 1) != '/')
f += '/';
f += 'ckfinder.html';
var h;
if (i.hh) {
h = i.hh;
if (typeof h == 'function')
h = h.toString().match(/function ([^(]+)/)[1];
g += '?action=js&func=' + h;
}
if (i.jx) {
g += g ? '&' : '?';
g += 'data=' + encodeURIComponent(i.jx);
}
if (i.disableThumbnailSelection) {
g += g ? '&' : '?';
g += 'dts=1';
} else if (i.lH || i.hh) {
h = i.lH || i.hh;
if (typeof h == 'function')
h = h.toString().match(/function ([^(]+)/)[1];
g += g ? '&' : '?';
g += 'thumbFunc=' + h;
if (i.nm)
g += '&tdata=' + encodeURIComponent(i.nm);
else if (!i.lH && i.jx)
g += '&tdata=' + encodeURIComponent(i.jx);
}
if (i.startupPath) {
g += g ? '&' : '?';
g += 'start=' + encodeURIComponent(i.startupPath
+ (i.startupFolderExpanded ? ':1' : ':0'));
}
if (!i.rememberLastFolder) {
g += g ? '&' : '?';
g += 'rlf=0';
}
if (i.id) {
g += g ? '&' : '?';
g += 'id=' + encodeURIComponent(i.id);
}
if (i.skin) {
g += g ? '&' : '?';
g += 'skin=' + encodeURIComponent(i.skin);
}
return f + g;
};
function d(f) {
var i = this;
i.id = f.name;
var g = f.element.getDocument().getWindow().$, h = a.oC.getWindow().$;
i.inPopup = !!(g && g.opener);
i.inIframe = !i.inPopup && g != h.top
&& g.frameElement.nodeName.toLowerCase() == 'iframe';
i.inFrame = !i.inPopup && g != h.top
&& g.frameElement.nodeName.toLowerCase() == 'frame';
i.inUrlPopup = !!(i.inPopup && h.opener);
}
;
function e(f, g, h) {
g.on('appReady', function(i) {
i.removeListener();
f.document = g.document.$;
f.folders = g.folders;
f.files = g.aG['filesview.filesview'][0].data().files;
f.basketFiles = g.basketFiles;
f.resourceTypes = g.resourceTypes;
f.connector = g.connector;
f.lang = g.lang;
f.langCode = g.langCode;
f.config = g.config;
g.aG['foldertree.foldertree'][0].on('afterAddFolder', function(j) {
j.removeListener();
if (h)
h(f);
}, f);
}, f, null, 999);
}
;
d.prototype = {
_ : {},
addFileContextMenuOption : function(f, g, h) {
var i = b(this.id), j = 'FileContextMenu_' + f.command;
i.bD(j, {
exec : function(m) {
var n = m.aG['filesview.filesview'][0].tools.dH();
g(m.cg, n);
}
});
f.command = j;
if (!f.group)
f.group = 'file1';
i.gp(j, f);
var k = i.aG['filesview.filesview'];
for ( var l = 0; l < k.length; l++)
k[l].on('beforeContextMenu', function o(m) {
if (h) {
var n = h(this.tools.dH());
if (n)
m.data.bj[j] = n == -1 ? a.aY : a.aS;
} else
m.data.bj[j] = a.aS;
});
},
disableFileContextMenuOption : function(f, g) {
var h = b(this.id), i = g ? 'FileContextMenu_' + f : f, j = h.aG['filesview.filesview'], k = [];
for ( var l = 0; l < j.length; l++) {
var m = k.push(function o(n) {
delete n.data.bj[i];
});
j[l].on('beforeContextMenu', k[m - 1]);
}
return function() {
for ( var n = 0; n < k.length; n++)
h.aG['foldertree.foldertree'][n].removeListener(
'beforeContextMenu', k[n]);
};
},
addFolderContextMenuOption : function(f, g, h) {
var i = b(this.id), j = 'FolderContextMenu_' + f.command;
i.bD(j, {
exec : function(m) {
g(m.cg, m.aV);
}
});
f.command = j;
if (!f.group)
f.group = 'folder1';
i.gp(j, f);
var k = i.aG['foldertree.foldertree'];
for ( var l = 0; l < k.length; l++)
k[l].on('beforeContextMenu', function o(m) {
if (h) {
var n = h(this.app.aV);
if (n)
m.data.bj[j] = n == -1 ? a.aY : a.aS;
} else
m.data.bj[j] = a.aS;
});
},
disableFolderContextMenuOption : function(f, g) {
var h = b(this.id), i = g ? 'FolderContextMenu_' + f : f, j = h.aG['foldertree.foldertree'], k = [];
for ( var l = 0; l < j.length; l++) {
var m = k.push(function o(n) {
delete n.data.bj[i];
});
j[l].on('beforeContextMenu', k[m - 1]);
}
return function() {
for ( var n = 0; n < k.length; n++)
h.aG['foldertree.foldertree'][n].removeListener(
'beforeContextMenu', k[n]);
};
},
getSelectedFile : function() {
return b(this.id).aG['filesview.filesview'][0].tools.dH();
},
getSelectedFolder : function() {
return b(this.id).aV;
},
setUiColor : function(f) {
return b(this.id).setUiColor(f);
},
openDialog : function(f, g) {
var j = this;
var h = new a.dom.document(window.document).eD(), i = b(j.id).document
.getWindow();
if (j.inFrame || j.inPopup || j.inIframe)
a.document = b(j.id).document;
return b(j.id).openDialog(f, g, h);
},
openMsgDialog : function(f, g) {
b(this.id).msgDialog(f, g);
},
openConfirmDialog : function(f, g, h) {
b(this.id).fe(f, g, h);
},
openInputDialog : function(f, g, h, i) {
b(this.id).hs(f, g, h, i);
},
addTool : function(f) {
return b(this.id).plugins.tools.addTool(f);
},
addToolPanel : function(f) {
return b(this.id).plugins.tools.addToolPanel(f);
},
removeTool : function(f) {
b(this.id).plugins.tools.removeTool(f);
},
showTool : function(f) {
b(this.id).plugins.tools.showTool(f);
},
hideTool : function(f) {
b(this.id).plugins.tools.hideTool(f);
},
getResourceType : function(f) {
return b(this.id).getResourceType(f);
},
log : function(f) {
a.log.apply(a.log, arguments);
},
getLog : function() {
return a.mZ();
},
emptyBasket : function() {
b(this.id).execCommand('TruncateBasket');
},
replaceUploadForm : function(f, g, h) {
var i = b(this.id);
i.aG['formpanel.formpanel'][0].on('beforeUploadFileForm', function(
j) {
if (j.data.step != 2)
return;
j.cancel(true);
var k = this.data(), l = j.data.folder;
try {
if (k.dc == 'upload')
this.oW('requestUnloadForm', function() {
this.app.cS('upload').bR(a.aS);
});
else {
if (this.data().dc)
this.oW('requestUnloadForm');
if (!h)
this.eh.removeClass('show_border');
this.oW('requestLoadForm', {
html : f,
command : 'upload'
});
g && g();
}
} catch (m) {
this.oW('failedUploadFileForm', j.data);
this.oW('afterUploadFileForm', j.data);
throw a.ba(m);
}
});
return {
hide : function() {
i.oW('requestUnloadForm', function() {
i.cS('upload').bR(a.aS);
});
}
};
},
resizeFormPanel : function(f) {
var g = b(this.id);
if (typeof f == 'undefined') {
g.document.getById('panel_view').setStyle('height', '');
g.document.getById('panel_widget').setStyle('height', '');
} else {
var h = Math.min(f, Math.max(90, g.document
.getById('main_container').$.offsetHeight - 300));
g.document.getById('panel_view').setStyle('height', h + 'px');
g.document.getById('panel_widget').setStyle('height',
h - 3 + 'px');
}
g.layout.ea(true);
},
refreshOpenedFolder : function() {
var f = b(this.id), g = f.aG['filesview.filesview'][0].tools
.currentFolder();
f.oW('requestSelectFolder', {
folder : g
});
},
selectFile : function(f) {
var g = b(this.id);
g.oW('requestSelectFile', {
file : f,
scrollTo : 1
});
},
closePopup : function() {
if (!this.inPopup)
return;
b(this.id).element.getDocument().getWindow().$.close();
},
openFolder : function(f, g) {
var h = b(this.id);
g = g.replace(/\/$/, '');
f = f.toLowerCase();
for ( var i = 0; i < h.folders.length; i++) {
var j = h.folders[i];
if (j.getPath().replace(/\/$/, '') == g
&& f == j.type.toLowerCase()) {
h.oW('requestSelectFolder', {
folder : j
});
h.oW('requestShowFolderFiles', {
folder : j
});
return;
}
}
},
setUiColor : function(f) {
b(this.id).setUiColor(f);
},
execCommand : function(f) {
b(this.id).execCommand(f);
}
};
(function() {
window.CKFinder = function(f, g) {
if (f)
for ( var h in f) {
if (!f.hasOwnProperty(h))
continue;
if (typeof f[h] == 'function' && h != 'callback')
continue;
this[h] = f[h];
}
this.callback = g;
};
CKFinder.prototype = {
create : function(f) {
var g = 'ckf' + Math.random().toString().substr(2, 4);
document.write('<span id="' + g + '"></span>');
f = a.tools.extend(a.jd.call(this), f, true);
var h = a.replace(g, f, CKFinder);
this.api = h.cg;
return h.cg;
},
appendTo : function(f, g) {
g = a.tools.extend(a.jd.call(this), g, true);
var h = a.appendTo(f, g, CKFinder);
this.api = h.cg;
return h.cg;
},
replace : function(f, g) {
g = a.tools.extend(a.jd.call(this), g, true);
var h = a.replace(f, g, CKFinder);
this.api = h.cg;
return h.cg;
},
popup : function(f, g) {
var o = this;
f = f || '80%';
g = g || '70%';
if (typeof f == 'string' && f.length > 1
&& f.substr(f.length - 1, 1) == '%')
f = parseInt(window.screen.width * parseInt(f, 10) / 100,
10);
if (typeof g == 'string' && g.length > 1
&& g.substr(g.length - 1, 1) == '%')
g = parseInt(window.screen.height * parseInt(g, 10) / 100,
10);
if (f < 200)
f = 200;
if (g < 200)
g = 200;
var h = parseInt((window.screen.height - g) / 2, 10), i = parseInt(
(window.screen.width - f) / 2, 10), j = 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width='
+ f + ',height=' + g + ',top=' + h + ',left=' + i, k = a.env.webkit ? 'about:blank'
: '', l = window.open(k, 'CKFinderpopup', j, true);
if (!l)
return false;
o.width = o.height = '100%';
var m = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>CKFinder 2</title><style type="text/css">body, html, iframe, #ckfinder { margin: 0; padding: 0; border: 0; width: 100%; height: 100%; overflow: hidden; }</style></head><body></body></html>', n = new a.dom.document(
l.document);
n.$.open();
if (a.env.isCustomDomain())
n.$.domain = window.document.domain;
n.$.write(m);
n.$.close();
try {
l.moveTo(i, h);
l.resizeTo(f, g);
l.focus();
return o.appendTo(n.bH());
} catch (p) {
return o.appendTo(n.bH());
}
return false;
}
};
CKFinder._ = {};
CKFinder.lang = {};
CKFinder.version = '2.1';
CKFinder.revision = '1937';
CKFinder.addPlugin = function(f, g, h) {
var i = {
bM : h || []
};
if (typeof g == 'function')
g = {
appReady : g
};
for ( var j in g) {
if (!g.hasOwnProperty(j))
continue;
if (j != 'connectorInitialized' && j != 'uiReady')
i[j] = g[j];
}
i.bz = function(k) {
if (g.connectorInitialized)
k.on('connectorInitialized', function(l) {
var m = g.connectorInitialized;
if (m)
m.call(m, k.cg, l.data.xml);
}, null, null, 1000);
if (g.uiReady)
k.on('uiReady', function() {
var l = g.uiReady;
l.call(l, k.cg);
}, null, null, 1000);
if (g.appReady)
k.on('appReady', function() {
var l = g.appReady;
l.call(l, k.cg);
}, null, null, 1000);
};
a.plugins.add(f, i);
};
CKFinder.getPluginPath = function(f) {
return a.plugins.getPath(f);
};
CKFinder.addExternalPlugin = function(f, g, h) {
a.plugins.tR(f, g, h);
};
CKFinder.setPluginLang = function(f, g, h) {
a.plugins.rX(f, g, h);
};
CKFinder.dialog = {
add : function(f, g) {
if (typeof g == 'function')
g = a.tools.override(g, function(h) {
return function(i) {
return h(i.cg);
};
});
a.dialog.add(f, g);
}
};
CKFinder.tools = {};
CKFinder.env = {};
CKFinder.dom = {};
CKFinder.create = function(f, g, h, i, j) {
var k;
if (f !== null && typeof f === 'object') {
k = new CKFinder();
for ( var l in f)
k[l] = f[l];
} else {
k = new CKFinder();
k.basePath = f;
if (g)
k.width = g;
if (h)
k.height = g;
if (i)
k.selectActionFunction = i;
if (j)
k.callback = j;
}
return k.create();
};
CKFinder.popup = function(f, g, h, i, j) {
var k;
if (f !== null && typeof f === 'object') {
k = new CKFinder();
for ( var l in f)
k[l] = f[l];
} else {
k = new CKFinder();
k.basePath = f;
if (i)
k.selectActionFunction = i;
if (j)
k.callback = j;
}
return k.popup(g, h);
};
CKFinder.setupFCKeditor = function(f, g, h, i) {
var j;
if (g !== null && typeof g === 'object') {
j = new CKFinder();
for ( var k in g) {
j[k] = g[k];
if (k == 'width') {
var l = j[k] || 800;
if (typeof l == 'string' && l.length > 1
&& l.substr(l.length - 1, 1) == '%')
l = parseInt(window.screen.width * parseInt(l, 10)
/ 100, 10);
f.Config.LinkBrowserWindowWidth = l;
f.Config.ImageBrowserWindowWidth = l;
f.Config.FlashBrowserWindowWidth = l;
} else if (k == 'height') {
var m = j[k] || 600;
if (typeof m == 'string' && m.length > 1
&& m.substr(m.length - 1, 1) == '%')
m = parseInt(window.screen.height * parseInt(m, 10)
/ 100, 10);
f.Config.LinkBrowserWindowHeight = m;
f.Config.ImageBrowserWindowHeight = m;
f.Config.FlashBrowserWindowHeight = m;
}
}
} else {
j = new CKFinder();
j.basePath = g;
}
var n = j.basePath;
if (n.substr(0, 1) != '/' && n.indexOf('://') == -1)
n = document.location.pathname.substring(0,
document.location.pathname.lastIndexOf('/') + 1)
+ n;
n = a.lj.call(j, n);
var o = n.indexOf('?') !== -1 ? '&' : '?';
f.Config.LinkBrowserURL = n;
f.Config.ImageBrowserURL = n + o + 'type=' + (h || 'Images');
f.Config.FlashBrowserURL = n + o + 'type=' + (i || 'Flash');
var p = n.substring(0, 1 + n.lastIndexOf('/'));
f.Config.LinkUploadURL = p + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=Files';
f.Config.ImageUploadURL = p + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (h || 'Images');
f.Config.FlashUploadURL = p + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (i || 'Flash');
};
CKFinder.setupCKEditor = function(f, g, h, i) {
if (f === null) {
for ( var j in CKEDITOR.instances)
CKFinder.setupCKEditor(CKEDITOR.instances[j], g, h, i);
CKEDITOR.on('instanceCreated', function(r) {
CKFinder.setupCKEditor(r.editor, g, h, i);
});
return;
}
var k;
if (g !== null && typeof g === 'object') {
k = new CKFinder();
for ( var l in g) {
k[l] = g[l];
if (l == 'width') {
var m = k[l] || 800;
if (typeof m == 'string' && m.length > 1
&& m.substr(m.length - 1, 1) == '%')
m = parseInt(window.screen.width * parseInt(m, 10)
/ 100, 10);
f.config.filebrowserWindowWidth = m;
} else if (l == 'height') {
var n = k[l] || 600;
if (typeof n == 'string' && n.length > 1
&& n.substr(n.length - 1, 1) == '%')
n = parseInt(window.screen.height * parseInt(n, 10)
/ 100, 10);
f.config.filebrowserWindowHeight = m;
}
}
} else {
k = new CKFinder();
k.basePath = g;
}
var o = k.basePath;
if (o.substr(0, 1) != '/' && o.indexOf('://') == -1)
o = document.location.pathname.substring(0,
document.location.pathname.lastIndexOf('/') + 1)
+ o;
o = a.lj.call(k, o);
var p = o.indexOf('?') !== -1 ? '&' : '?';
f.config.filebrowserBrowseUrl = o;
f.config.filebrowserImageBrowseUrl = o + p + 'type='
+ (h || 'Images');
f.config.filebrowserFlashBrowseUrl = o + p + 'type='
+ (i || 'Flash');
var q = o.substring(0, 1 + o.lastIndexOf('/'));
f.config.filebrowserUploadUrl = q + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=Files';
f.config.filebrowserImageUploadUrl = q + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (h || 'Images');
f.config.filebrowserFlashUploadUrl = q + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (i || 'Flash');
};
})();
if (!a.event) {
a.event = function() {
};
a.event.du = function(f, g) {
var h = a.event.prototype;
for ( var i in h) {
if (f[i] == undefined)
f[i] = h[i];
}
};
a.event.prototype = (function() {
var f = function(h) {
var i = h.kk && h.kk() || h._ || (h._ = {});
return i.cC || (i.cC = {});
}, g = function(h) {
this.name = h;
this.dF = [];
};
g.prototype = {
mi : function(h) {
for ( var i = 0, j = this.dF; i < j.length; i++) {
if (j[i].gg == h)
return i;
}
return -1;
}
};
return {
on : function(h, i, j, k, l) {
var m = f(this), n = m[h] || (m[h] = new g(h));
if (n.mi(i) < 0) {
var o = n.dF;
if (!j)
j = this;
if (isNaN(l))
l = 10;
var p = this, q = function(s, t, u, v) {
var w = {
name : h,
jN : this,
application : s,
data : t,
jO : k,
stop : u,
cancel : v,
removeListener : function() {
p.removeListener(h, i);
}
};
i.call(j, w);
return w.data;
};
q.gg = i;
q.nT = l;
for ( var r = o.length - 1; r >= 0; r--) {
if (o[r].nT <= l) {
o.splice(r + 1, 0, q);
return;
}
}
o.unshift(q);
}
},
oW : (function() {
var h = false, i = function() {
h = true;
}, j = false, k = function(l) {
j = l ? 2 : true;
};
return function w(l, m, n, o) {
if (typeof m == 'function') {
o = m;
m = null;
} else if (typeof n == 'function') {
o = n;
n = null;
}
if (l != 'mousemove')
a.log('[EVENT] ' + l, m, o);
var p = f(this)[l], q = h, r = j;
h = j = false;
if (p) {
var s = p.dF;
if (s.length) {
s = s.slice(0);
for ( var t = 0; t < s.length; t++) {
var u = s[t].call(this, n, m, i, k);
if (typeof u != 'undefined')
m = u;
if (h || j && j != 2)
break;
}
}
}
var v = j
|| (typeof m == 'undefined' ? false : !m
|| typeof m.result == 'undefined' ? m
: m.result);
if (typeof o === 'function' && j != 2)
v = o.call(this, j, m) || v;
h = q;
j = r;
return v;
};
})(),
cr : function(h, i, j) {
var k = this.oW(h, i, j);
delete f(this)[h];
return k;
},
removeListener : function(h, i) {
var j = f(this)[h];
if (j) {
var k = j.mi(i);
if (k >= 0)
j.dF.splice(k, 1);
}
},
mF : function() {
var h = f(this);
for ( var i = 0; i < h.length; i++)
h[i].dF = [];
},
rC : function(h) {
var i = f(this)[h];
return i && i.dF.length > 0;
}
};
})();
}
if (!a.application) {
a.kZ = 0;
a.fc = 1;
a.qE = 2;
a.application = function(f, g, h, i) {
var j = this;
j._ = {
kw : f,
element : g
};
j.ff = h || a.kZ;
a.event.call(j);
j.iI(i);
};
a.application.replace = function(f, g, h) {
var i = f;
if (typeof i != 'object') {
i = document.getElementById(f);
if (!i) {
var j = 0, k = document.getElementsByName(f);
while ((i = k[j++])
&& i.tagName.toLowerCase() != 'textarea') {
}
}
if (!i)
throw '[CKFINDER.application.replace] The element with id or name "' + f + '" was not found.';
}
return new a.application(g, i, a.fc, h);
};
a.application.appendTo = function(f, g, h) {
if (typeof f != 'object') {
f = document.getElementById(f);
if (!f)
throw '[CKFINDER.application.appendTo] The element with id "' + f + '" was not found.';
}
return new a.application(g, f, a.qE, h);
};
a.application.prototype = {
iI : function() {
var f = a.application.eb || (a.application.eb = []);
f.push(this);
},
oW : function(f, g, h) {
return a.event.prototype.oW.call(this, f, g, this, h);
},
cr : function(f, g, h) {
return a.event.prototype.cr.call(this, f, g, this, h);
}
};
a.event.du(a.application.prototype, true);
}
if (!a.env) {
a.env = (function() {
var f = navigator.userAgent.toLowerCase(), g = window.opera, h = {
ie :
/* @cc_on!@ */false,
opera : !!g && g.version,
webkit : f.indexOf(' applewebkit/') > -1,
air : f.indexOf(' adobeair/') > -1,
mac : f.indexOf('macintosh') > -1,
quirks : document.compatMode == 'BackCompat',
isCustomDomain : function() {
return this.ie
&& document.domain != window.location.hostname;
}
};
h.gecko = navigator.product == 'Gecko' && !h.webkit && !h.opera;
var i = 0;
if (h.ie) {
i = parseFloat(f.match(/msie (\d+)/)[1]);
h.ie8 = !!document.documentMode;
h.ie8Compat = document.documentMode == 8;
h.ie7Compat = i == 7 && !document.documentMode
|| document.documentMode == 7;
h.ie6Compat = i < 7 || h.quirks;
}
if (h.gecko) {
var j = f.match(/rv:([\d\.]+)/);
if (j) {
j = j[1].split('.');
i = j[0] * 10000 + (j[1] || 0) * 100 + +(j[2] || 0);
}
h.isMobile = f.indexOf('fennec') > -1;
}
if (h.opera) {
i = parseFloat(g.version());
h.isMobile = f.indexOf('opera mobi') > -1;
}
if (h.air)
i = parseFloat(f.match(/ adobeair\/(\d+)/)[1]);
if (h.webkit) {
i = parseFloat(f.match(/ applewebkit\/(\d+)/)[1]);
h.isMobile = f.indexOf('mobile') > -1;
}
h.version = i;
h.isCompatible = h.ie && i >= 6 || h.gecko && i >= 10801 || h.opera
&& i >= 9.5 || h.air && i >= 1 || h.webkit && i >= 522
|| false;
h.cssClass = 'browser_' + (h.ie ? 'ie' : h.gecko ? 'gecko'
: h.opera ? 'opera' : h.air ? 'air' : h.webkit ? 'webkit'
: 'unknown');
if (h.quirks)
h.cssClass += ' browser_quirks';
if (h.ie) {
h.cssClass += ' browser_ie' + (h.version < 7 ? '6'
: h.version >= 8 ? '8' : '7');
if (h.quirks)
h.cssClass += ' browser_iequirks';
}
if (h.gecko && i < 10900)
h.cssClass += ' browser_gecko18';
return h;
})();
CKFinder.env = a.env;
}
var f = a.env;
var g = f.ie;
if (a.status == 'unloaded')
(function() {
a.event.du(a);
a.dO = function() {
if (a.status != 'basic_ready') {
a.dO.qr = true;
return;
}
delete a.dO;
var i = document.createElement('script');
i.type = 'text/javascript';
i.src = a.basePath + 'ckfinder.js';
document.getElementsByTagName('head')[0].appendChild(i);
};
a.mS = 0;
a.uQ = 'ckfinder';
a.uM = true;
var h = function(i, j, k, l) {
if (f.isCompatible) {
if (a.dO)
a.dO();
var m = k(i, j, l);
a.add(m);
return m;
}
return null;
};
a.replace = function(i, j, k) {
return h(i, j, a.application.replace, k);
};
a.appendTo = function(i, j, k) {
return h(i, j, a.application.appendTo, k);
};
a.add = function(i) {
var j = this._.io || (this._.io = []);
j.push(i);
};
a.uL = function() {
var i = document.getElementsByTagName('textarea');
for ( var j = 0; j < i.length; j++) {
var k = null, l = i[j], m = l.name;
if (!l.name && !l.id)
continue;
if (typeof arguments[0] == 'string') {
var n = new RegExp('(?:^| )' + arguments[0] + '(?:$| )');
if (!n.test(l.className))
continue;
} else if (typeof arguments[0] == 'function') {
k = {};
if (arguments[0](l, k) === false)
continue;
}
this.replace(l, k);
}
};
(function() {
var i = function() {
var j = a.dO, k = a.mS;
a.status = 'basic_ready';
if (j && j.qr)
j();
else if (k)
setTimeout(function() {
if (a.dO)
a.dO();
}, k * 1000);
};
if (window.addEventListener)
window.addEventListener('load', i, false);
else if (window.attachEvent)
window.attachEvent('onload', i);
})();
a.status = 'basic_loaded';
})();
a.dom = {};
CKFinder.dom = a.dom;
var h = a.dom;
a.ajax = (function() {
var i = function() {
if (!g || location.protocol != 'file:')
try {
return new XMLHttpRequest();
} catch (n) {
}
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (o) {
}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (p) {
}
return null;
}, j = function(n) {
return n.readyState == 4
&& (n.status >= 200 && n.status < 300 || n.status == 304
|| n.status === 0 || n.status == 1223);
}, k = function(n) {
if (j(n))
return n.responseText;
return null;
}, l = function(n) {
if (j(n)) {
var o = n.responseXML, p = new a.xml(o && o.firstChild
&& o.documentElement
&& o.documentElement.nodeName != 'parsererror' ? o
: n.responseText.replace(/^[^<]+/, '').replace(
/[^>]+$/, ''));
if (p && p.mq && p.mq.documentElement
&& p.mq.documentElement.nodeName != 'parsererror'
&& p.mq.documentElement.nodeName != 'html'
&& p.mq.documentElement.nodeName != 'br')
return p;
}
var q = a.eq || a.jt, r = n.responseText, s = q.lang.ErrorMsg[!r ? 'XmlEmpty'
: 'XmlError'] + '<br>';
if (p && p.mq)
if (p.mq.parseError && p.mq.parseError.reason)
s += p.mq.parseError.reason;
else if (p.mq.documentElement
&& p.mq.documentElement.nodeName == 'parsererror')
s += p.mq.documentElement.textContent;
if (!r)
q.msgDialog(q.lang.SysErrorDlgTitle, s);
else {
if (/text\/plain/.test(n.getResponseHeader('Content-Type'))
|| /<Connector\s*/.test(r)) {
r = a.tools.htmlEncode(r);
r = r.replace(/\n/g, '<br>');
r = '<div style="width:600px; overflow:scroll"><font>' + r + '</font></div>';
}
q.msgDialog(q.lang.SysErrorDlgTitle, s
+ '<br>'
+ q.lang.ErrorMsg.XmlRawResponse.replace('%s',
'<br><br>' + r));
}
return {};
}, m = function(n, o, p, q) {
var r = !!o;
a.log('[AJAX] POST ' + n);
var s = i();
if (!s)
return null;
if (!q)
s.open('GET', n, r);
else
s.open('POST', n, r);
if (r)
s.onreadystatechange = function() {
if (s.readyState == 4) {
o(p(s));
s = null;
}
};
if (q) {
s.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
s.send(q);
} else
s.send(null);
return r ? '' : p(s);
};
return {
load : function(n, o, p) {
return m(n, o, k, p);
},
loadXml : function(n, o, p) {
return m(n, o, l, p);
}
};
})();
CKFinder.ajax = a.ajax;
(function() {
var i = [];
a.tools = {
arrayCompare : function(j, k) {
if (!j && !k)
return true;
if (!j || !k || j.length != k.length)
return false;
for ( var l = 0; l < j.length; l++) {
if (j[l] != k[l])
return false;
}
return true;
},
clone : function(j) {
var k;
if (j && j instanceof Array) {
k = [];
for ( var l = 0; l < j.length; l++)
k[l] = this.clone(j[l]);
return k;
}
if (j === null || typeof j != 'object' || j instanceof String
|| j instanceof Number || j instanceof Boolean
|| j instanceof Date)
return j;
k = new j.constructor();
for ( var m in j) {
var n = j[m];
k[m] = this.clone(n);
}
return k;
},
capitalize : function(j) {
return j.charAt(0).toUpperCase() + j.substring(1).toLowerCase();
},
extend : function(j) {
var k = arguments.length, l, m;
if (typeof (l = arguments[k - 1]) == 'boolean')
k--;
else if (typeof (l = arguments[k - 2]) == 'boolean') {
m = arguments[k - 1];
k -= 2;
}
for ( var n = 1; n < k; n++) {
var o = arguments[n];
for ( var p in o) {
if (l === true || j[p] == undefined)
if (!m || p in m)
j[p] = o[p];
}
}
return j;
},
prototypedCopy : function(j) {
var k = function() {
};
k.prototype = j;
return new k();
},
isArray : function(j) {
return !!j && j instanceof Array;
},
cssStyleToDomStyle : (function() {
var j = document.createElement('div').style, k = typeof j.cssFloat != 'undefined' ? 'cssFloat'
: typeof j.styleFloat != 'undefined' ? 'styleFloat'
: 'float';
return function(l) {
if (l == 'float')
return k;
else
return l.replace(/-./g, function(m) {
return m.substr(1).toUpperCase();
});
};
})(),
htmlEncode : function(j) {
var k = function(o) {
var p = new h.element('span');
p.setText(o);
return p.getHtml();
}, l = k('\n').toLowerCase() == '<br>' ? function(o) {
return k(o).replace(/<br>/gi, '\n');
} : k, m = k('>') == '>' ? function(o) {
return l(o).replace(/>/g, '>');
} : l, n = k(' ') == ' ' ? function(o) {
return m(o).replace(/ /g, ' ');
} : m;
this.htmlEncode = n;
return this.htmlEncode(j);
},
getNextNumber : (function() {
var j = 0;
return function() {
return ++j;
};
})(),
override : function(j, k) {
return k(j);
},
setTimeout : function(j, k, l, m, n) {
if (!n)
n = window;
if (!l)
l = n;
return n.setTimeout(function() {
if (m)
j.apply(l, [].concat(m));
else
j.apply(l);
}, k || 0);
},
trim : (function() {
var j = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;
return function(k) {
return k ? k.replace(j, '') : null;
};
})(),
ltrim : (function() {
var j = /^[ \t\n\r]+/g;
return function(k) {
return k ? k.replace(j, '') : null;
};
})(),
rtrim : (function() {
var j = /[ \t\n\r]+$/g;
return function(k) {
return k ? k.replace(j, '') : null;
};
})(),
indexOf : Array.prototype.indexOf ? function(j, k) {
return j.indexOf(k);
} : function(j, k) {
for ( var l = 0, m = j.length; l < m; l++) {
if (j[l] === k)
return l;
}
return -1;
},
bind : function(j, k) {
return function() {
return j.apply(k, arguments);
};
},
createClass : function(j) {
var k = j.$, l = j.base, m = j.vd || j._, n = j.ej, o = j.statics;
if (m) {
var p = k;
k = function() {
var t = this;
var q = t._ || (t._ = {});
for ( var r in m) {
var s = m[r];
q[r] = typeof s == 'function' ? a.tools.bind(s, t)
: s;
}
p.apply(t, arguments);
};
}
if (l) {
k.prototype = this.prototypedCopy(l.prototype);
k.prototype['constructor'] = k;
k.prototype.base = function() {
this.base = l.prototype.base;
l.apply(this, arguments);
this.base = arguments.callee;
};
}
if (n)
this.extend(k.prototype, n, true);
if (o)
this.extend(k, o, true);
return k;
},
addFunction : function(j, k) {
return i.push(function() {
j.apply(k || this, arguments);
}) - 1;
},
removeFunction : function(j) {
i[j] = null;
},
callFunction : function(j) {
var k = i[j];
return k
.apply(window, Array.prototype.slice.call(arguments, 1));
},
cssLength : (function() {
var j = /^\d+(?:\.\d+)?$/;
return function(k) {
return k + (j.test(k) ? 'px' : '');
};
})(),
repeat : function(j, k) {
return new Array(k + 1).join(j);
},
deepCopy : function(j) {
var k = {};
if (typeof j == 'object') {
if (typeof j.length != 'undefined')
k = [];
for ( var l in j) {
if (j[l] === null)
k[l] = j[l];
else if (typeof j[l] == 'object')
k[l] = a.tools.deepCopy(j[l]);
else if (typeof j[l] == 'string')
k[l] = j[l];
else if (typeof j[l] == 'number')
k[l] = j[l];
else if (typeof j[l] == 'boolean')
j[l] === true ? k[l] = true : k[l] = false;
}
}
return k;
},
getUrlParam : function(j, k) {
var l = new RegExp('(?:[?&]|&)' + j + '=([^&]+)', 'i'), m = (k || window).location.search
.match(l);
return m && m.length > 1 ? m[1] : null;
},
htmlEncode : function(j) {
if (!j)
return '';
j = typeof j != 'string' ? j.toString() : j;
j = j.replace(/&/g, '&');
j = j.replace(/</g, '<');
j = j.replace(/>/g, '>');
return j;
},
setCookie : function(j, k, l) {
document.cookie = j
+ '='
+ k
+ (!l ? '; expires=Thu, 6 Oct 2016 01:00:00 UTC; path=/'
: '');
},
getCookie : function(j) {
var k = document.cookie.match(new RegExp(
'(^|\\s|;)' + j + '=([^;]*)'));
return k && k.length > 0 ? k[2] : '';
},
mH : function(j) {
if (g) {
j.$.onfocusin = function() {
j.addClass('focus_inside');
};
j.$.onfocusout = function() {
j.removeClass('focus_inside');
};
} else {
j.$.addEventListener('focus', function() {
j.addClass('focus_inside');
}, true);
j.$.addEventListener('blur', function() {
j.removeClass('focus_inside');
}, true);
}
}
};
CKFinder._.callFunction = a.tools.callFunction;
CKFinder.tools = a.tools;
})();
var i = a.tools;
h.event = function(j) {
this.$ = j;
};
h.event.prototype = {
oV : function() {
return this.$.keyCode || this.$.which;
},
db : function() {
var k = this;
var j = k.oV();
if (k.$.ctrlKey || k.$.metaKey)
j += a.bP;
if (k.$.shiftKey)
j += a.dy;
if (k.$.altKey)
j += a.eJ;
return j;
},
preventDefault : function(j) {
var k = this.$;
if (k.preventDefault)
k.preventDefault();
else
k.returnValue = false;
if (j)
this.stopPropagation();
},
stopPropagation : function() {
var j = this.$;
if (j.stopPropagation)
j.stopPropagation();
else
j.cancelBubble = true;
},
bK : function() {
var j = this.$.target || this.$.srcElement;
return j ? new h.bi(j) : null;
}
};
a.bP = 1000;
a.dy = 2000;
a.eJ = 4000;
h.dE = function(j) {
if (j)
this.$ = j;
};
h.dE.prototype = (function() {
var j = function(k, l) {
return function(m) {
if (typeof a != 'undefined')
k.oW(l, new h.event(m));
};
};
return {
kk : function() {
var k;
if (!(k = this.dw('_')))
this.fL('_', k = {});
return k;
},
on : function(k) {
var n = this;
var l = n.dw('_cke_nativeListeners');
if (!l) {
l = {};
n.fL('_cke_nativeListeners', l);
}
if (!l[k]) {
var m = l[k] = j(n, k);
if (n.$.addEventListener && !g)
n.$.addEventListener(k, m, !!a.event.jP);
else if (n.$.attachEvent)
n.$.attachEvent('on' + k, m);
}
return a.event.prototype.on.apply(n, arguments);
},
removeListener : function(k) {
var n = this;
a.event.prototype.removeListener.apply(n, arguments);
if (!n.rC(k)) {
var l = n.dw('_cke_nativeListeners'), m = l && l[k];
if (m) {
if (n.$.removeEventListener)
n.$.removeEventListener(k, m, false);
else if (n.$.detachEvent)
n.$.detachEvent('on' + k, m);
delete l[k];
}
}
}
};
})();
(function(j) {
var k = {};
j.equals = function(l) {
return l && l.$ === this.$;
};
j.fL = function(l, m) {
var n = this.iY(), o = k[n] || (k[n] = {});
o[l] = m;
return this;
};
j.dw = function(l) {
var m = this.$.dj, n = m && k[m];
return n && n[l];
};
j.jF = function(l) {
var m = this.$.dj, n = m && k[m], o = n && n[l];
if (typeof o != 'undefined')
delete n[l];
return o || null;
};
j.iY = function() {
return this.$.dj || (this.$.dj = i.getNextNumber());
};
a.event.du(j);
})(h.dE.prototype);
h.window = function(j) {
h.dE.call(this, j);
};
h.window.prototype = new h.dE();
i.extend(h.window.prototype,
{
focus : function() {
if (f.webkit && this.$.parent)
this.$.parent.focus();
this.$.focus();
},
eR : function() {
var j = this.$.document, k = j.compatMode == 'CSS1Compat';
return {
width : (k ? j.documentElement.clientWidth
: j.body.clientWidth) || 0,
height : (k ? j.documentElement.clientHeight
: j.body.clientHeight) || 0
};
},
hV : function() {
var j = this.$;
if ('pageXOffset' in j)
return {
x : j.pageXOffset || 0,
y : j.pageYOffset || 0
};
else {
var k = j.document;
return {
x : k.documentElement.scrollLeft
|| k.body.scrollLeft || 0,
y : k.documentElement.scrollTop || k.body.scrollTop
|| 0
};
}
}
});
h.document = function(j) {
h.dE.call(this, j);
};
var j = h.document;
j.prototype = new h.dE();
i.extend(j.prototype, {
pb : function(k) {
if (this.$.createStyleSheet)
this.$.createStyleSheet(k);
else {
var l = new h.element('link');
l.setAttributes( {
rel : 'stylesheet',
type : 'text/css',
href : k
});
this.eD().append(l);
}
},
createElement : function(k, l) {
var m = new h.element(k, this);
if (l) {
if (l.attributes)
m.setAttributes(l.attributes);
if (l.gS)
m.setStyles(l.gS);
}
return m;
},
jT : function(k) {
return new h.text(k, this);
},
focus : function() {
this.getWindow().focus();
},
getById : function(k) {
var l = this.$.getElementById(k);
return l ? new h.element(l) : null;
},
vu : function(k, l) {
var m = this.$.documentElement;
for ( var n = 0; m && n < k.length; n++) {
var o = k[n];
if (!l) {
m = m.childNodes[o];
continue;
}
var p = -1;
for ( var q = 0; q < m.childNodes.length; q++) {
var r = m.childNodes[q];
if (l === true && r.nodeType == 3 && r.previousSibling
&& r.previousSibling.nodeType == 3)
continue;
p++;
if (p == o) {
m = r;
break;
}
}
}
return m ? new h.bi(m) : null;
},
eG : function(k, l) {
if (!g && l)
k = l + ':' + k;
return new h.iT(this.$.getElementsByTagName(k));
},
eD : function() {
var k = this.$.getElementsByTagName('head')[0];
k = new h.element(k);
return (this.eD = function() {
return k;
})();
},
bH : function() {
var k = new h.element(this.$.body);
return (this.bH = function() {
return k;
})();
},
gT : function() {
var k = new h.element(this.$.documentElement);
return (this.gT = function() {
return k;
})();
},
getWindow : function() {
var k = new h.window(this.$.parentWindow || this.$.defaultView);
return (this.getWindow = function() {
return k;
})();
}
});
h.bi = function(k) {
if (k) {
switch (k.nodeType) {
case a.cv:
return new h.element(k);
case a.fl:
return new h.text(k);
}
h.dE.call(this, k);
}
return this;
};
h.bi.prototype = new h.dE();
a.cv = 1;
a.fl = 3;
a.va = 8;
a.om = 11;
a.oh = 0;
a.op = 1;
a.gW = 2;
a.gX = 4;
a.mo = 8;
a.lF = 16;
i
.extend(
h.bi.prototype,
{
appendTo : function(k, l) {
k.append(this, l);
return k;
},
clone : function(k, l) {
var m = this.$.cloneNode(k);
if (!l) {
var n = function(o) {
if (o.nodeType != a.cv)
return;
o.removeAttribute('id', false);
o.removeAttribute('dj', false);
var p = o.childNodes;
for ( var q = 0; q < p.length; q++)
n(p[q]);
};
n(m);
}
return new h.bi(m);
},
gE : function() {
return !!this.$.previousSibling;
},
ge : function() {
return !!this.$.nextSibling;
},
kB : function(k) {
k.$.parentNode
.insertBefore(this.$, k.$.nextSibling);
return k;
},
insertBefore : function(k) {
k.$.parentNode.insertBefore(this.$, k.$);
return k;
},
vP : function(k) {
this.$.parentNode.insertBefore(k.$, this.$);
return k;
},
lU : function(k) {
var l = [], m = this.getDocument().$.documentElement, n = this.$;
while (n && n != m) {
var o = n.parentNode, p = -1;
for ( var q = 0; q < o.childNodes.length; q++) {
var r = o.childNodes[q];
if (k && r.nodeType == 3
&& r.previousSibling
&& r.previousSibling.nodeType == 3)
continue;
p++;
if (r == n)
break;
}
l.unshift(p);
n = n.parentNode;
}
return l;
},
getDocument : function() {
var k = new j(this.$.ownerDocument
|| this.$.parentNode.ownerDocument);
return (this.getDocument = function() {
return k;
})();
},
vA : function() {
var k = this.$, l = k.parentNode
&& k.parentNode.firstChild, m = -1;
while (l) {
m++;
if (l == k)
return m;
l = l.nextSibling;
}
return -1;
},
hL : function(k, l, m) {
if (m && !m.call) {
var n = m;
m = function(q) {
return !q.equals(n);
};
}
var o = !k && this.getFirst && this.getFirst(), p;
if (!o) {
if (this.type == a.cv && m
&& m(this, true) === false)
return null;
o = this.dG();
}
while (!o && (p = (p || this).getParent())) {
if (m && m(p, true) === false)
return null;
o = p.dG();
}
if (!o)
return null;
if (m && m(o) === false)
return null;
if (l && l != o.type)
return o.hL(false, l, m);
return o;
},
hZ : function(k, l, m) {
if (m && !m.call) {
var n = m;
m = function(q) {
return !q.equals(n);
};
}
var o = !k && this.dB && this.dB(), p;
if (!o) {
if (this.type == a.cv && m
&& m(this, true) === false)
return null;
o = this.cf();
}
while (!o && (p = (p || this).getParent())) {
if (m && m(p, true) === false)
return null;
o = p.cf();
}
if (!o)
return null;
if (m && m(o) === false)
return null;
if (l && o.type != l)
return o.hZ(false, l, m);
return o;
},
cf : function(k) {
var l = this.$, m;
do {
l = l.previousSibling;
m = l && new h.bi(l);
} while (m && k && !k(m));
return m;
},
vs : function() {
return this.cf(function(k) {
return k.$.nodeType == 1;
});
},
dG : function(k) {
var l = this.$, m;
do {
l = l.nextSibling;
m = l && new h.bi(l);
} while (m && k && !k(m));
return m;
},
vk : function() {
return this.dG(function(k) {
return k.$.nodeType == 1;
});
},
getParent : function() {
var k = this.$.parentNode;
return k && k.nodeType == 1 ? new h.bi(k) : null;
},
vn : function(k) {
var l = this, m = [];
do
m[k ? 'push' : 'unshift'](l);
while (l = l.getParent());
return m;
},
vv : function(k) {
var m = this;
if (k.equals(m))
return m;
if (k.contains && k.contains(m))
return k;
var l = m.contains ? m : m.getParent();
do {
if (l.contains(k))
return l;
} while (l = l.getParent());
return null;
},
gz : function(k) {
var l = this.$, m = k.$;
if (l.compareDocumentPosition)
return l.compareDocumentPosition(m);
if (l == m)
return a.oh;
if (this.type == a.cv && k.type == a.cv) {
if (l.contains) {
if (l.contains(m))
return a.lF + a.gX;
if (m.contains(l))
return a.mo + a.gW;
}
if ('sourceIndex' in l)
return l.sourceIndex < 0
|| m.sourceIndex < 0 ? a.op
: l.sourceIndex < m.sourceIndex ? a.gX
: a.gW;
}
var n = this.lU(), o = k.lU(), p = Math.min(
n.length, o.length);
for ( var q = 0; q <= p - 1; q++) {
if (n[q] != o[q]) {
if (q < p)
return n[q] < o[q] ? a.gX : a.gW;
break;
}
}
return n.length < o.length ? a.lF + a.gX : a.mo
+ a.gW;
},
vw : function(k, l) {
var m = this.$;
if (!l)
m = m.parentNode;
while (m) {
if (m.nodeName && m.nodeName.toLowerCase() == k)
return new h.bi(m);
m = m.parentNode;
}
return null;
},
vX : function(k, l) {
var m = this.$;
if (!l)
m = m.parentNode;
while (m) {
if (m.nodeName && m.nodeName.toLowerCase() == k)
return true;
m = m.parentNode;
}
return false;
},
move : function(k, l) {
k.append(this.remove(), l);
},
remove : function(k) {
var l = this.$, m = l.parentNode;
if (m) {
if (k)
for ( var n; n = l.firstChild;)
m.insertBefore(l.removeChild(n), l);
m.removeChild(l);
}
return this;
},
replace : function(k) {
this.insertBefore(k);
k.remove();
},
trim : function() {
this.ltrim();
this.rtrim();
},
ltrim : function() {
var n = this;
var k;
while (n.getFirst && (k = n.getFirst())) {
if (k.type == a.fl) {
var l = i.ltrim(k.getText()), m = k.hJ();
if (!l) {
k.remove();
continue;
} else if (l.length < m) {
k.split(m - l.length);
n.$.removeChild(n.$.firstChild);
}
}
break;
}
},
rtrim : function() {
var n = this;
var k;
while (n.dB && (k = n.dB())) {
if (k.type == a.fl) {
var l = i.rtrim(k.getText()), m = k.hJ();
if (!l) {
k.remove();
continue;
} else if (l.length < m) {
k.split(l.length);
n.$.lastChild.parentNode
.removeChild(n.$.lastChild);
}
}
break;
}
if (!g && !f.opera) {
k = n.$.lastChild;
if (k && k.type == 1
&& k.nodeName.toLowerCase() == 'br')
k.parentNode.removeChild(k);
}
}
});
h.iT = function(k) {
this.$ = k;
};
h.iT.prototype = {
count : function() {
return this.$.length;
},
getItem : function(k) {
var l = this.$[k];
return l ? new h.bi(l) : null;
}
};
h.element = function(k, l) {
if (typeof k == 'string')
k = (l ? l.$ : document).createElement(k);
h.dE.call(this, k);
};
var k = h.element;
k.eB = function(l) {
return l && (l.$ ? l : new k(l));
};
k.prototype = new h.bi();
k.kE = function(l, m) {
var n = new k('div', m);
n.setHtml(l);
return n.getFirst().remove();
};
k.rS = function(l, m, n, o) {
var p = m.dw('list_marker_id')
|| m.fL('list_marker_id', i.getNextNumber()).dw(
'list_marker_id'), q = m.dw('list_marker_names')
|| m.fL('list_marker_names', {}).dw('list_marker_names');
l[p] = m;
q[n] = 1;
return m.fL(n, o);
};
k.sM = function(l) {
for ( var m in l)
k.qZ(l, l[m], true);
};
k.qZ = function(l, m, n) {
var o = m.dw('list_marker_names'), p = m.dw('list_marker_id');
for ( var q in o)
m.jF(q);
m.jF('list_marker_names');
if (n) {
m.jF('list_marker_id');
delete l[p];
}
};
i
.extend(
k.prototype,
{
type : a.cv,
addClass : function(l) {
var m = this.$.className;
if (m) {
var n = new RegExp(
'(?:^|\\s)' + l + '(?:\\s|$)', '');
if (!n.test(m))
m += ' ' + l;
}
this.$.className = m || l;
},
removeClass : function(l) {
var m = this.getAttribute('class');
if (m) {
var n = new RegExp(
'(?:^|\\s+)' + l + '(?=\\s|$)', 'i');
if (n.test(m)) {
m = m.replace(n, '').replace(/^\s+/, '');
if (m)
this.setAttribute('class', m);
else
this.removeAttribute('class');
}
}
},
hasClass : function(l) {
var m = new RegExp('(?:^|\\s+)' + l + '(?=\\s|$)',
'');
return m.test(this.getAttribute('class'));
},
append : function(l, m) {
var n = this;
if (typeof l == 'string')
l = n.getDocument().createElement(l);
if (m)
n.$.insertBefore(l.$, n.$.firstChild);
else
n.$.appendChild(l.$);
a.log('[DOM] DOM flush into ' + n.getName());
return l;
},
appendHtml : function(l) {
var n = this;
if (!n.$.childNodes.length)
n.setHtml(l);
else {
var m = new k('div', n.getDocument());
m.setHtml(l);
m.jg(n);
}
},
appendText : function(l) {
if (this.$.text != undefined)
this.$.text += l;
else
this.append(new h.text(l));
},
pd : function() {
var m = this;
var l = m.dB();
while (l && l.type == a.fl && !i.rtrim(l.getText()))
l = l.cf();
if (!l || !l.is || !l.is('br'))
m.append(f.opera ? m.getDocument().jT('') : m
.getDocument().createElement('br'));
},
tV : function(l) {
var o = this;
var m = new h.mk(o.getDocument());
m.setStartAfter(o);
m.setEndAfter(l);
var n = m.extractContents();
m.insertNode(o.remove());
n.kA(o);
},
contains : g || f.webkit ? function(l) {
var m = this.$;
return l.type != a.cv ? m.contains(l.getParent().$)
: m != l.$ && m.contains(l.$);
}
: function(l) {
return !!(this.$
.compareDocumentPosition(l.$) & 16);
},
focus : function() {
try {
this.$.focus();
} catch (l) {
}
},
getHtml : function() {
return this.$.innerHTML;
},
vi : function() {
var m = this;
if (m.$.outerHTML)
return m.$.outerHTML.replace(/<\?[^>]*>/, '');
var l = m.$.ownerDocument.createElement('div');
l.appendChild(m.$.cloneNode(true));
return l.innerHTML;
},
setHtml : function(l) {
a.log('[DOM] DOM flush into ' + this.getName());
return this.$.innerHTML = l;
},
setText : function(l) {
k.prototype.setText = this.$.innerText != undefined ? function(
m) {
a.log('[DOM] Text flush');
return this.$.innerText = m;
}
: function(m) {
a.log('[DOM] Text flush');
return this.$.textContent = m;
};
return this.setText(l);
},
getAttribute : (function() {
var l = function(m) {
return this.$.getAttribute(m, 2);
};
if (g && (f.ie7Compat || f.ie6Compat))
return function(m) {
var o = this;
switch (m) {
case 'class':
m = 'className';
break;
case 'tabindex':
var n = l.call(o, m);
if (n !== 0 && o.$.tabIndex === 0)
n = null;
return n;
break;
case 'checked':
return o.$.checked;
break;
case 'style':
return o.$.style.cssText;
}
return l.call(o, m);
};
else
return l;
})(),
getChildren : function() {
return new h.iT(this.$.childNodes);
},
getComputedStyle : g ? function(l) {
return this.$.currentStyle[i.cssStyleToDomStyle(l)];
}
: function(l) {
return this.getWindow().$.getComputedStyle(
this.$, '').getPropertyValue(l);
},
pf : function() {
var l = a.ga[this.getName()];
this.pf = function() {
return l;
};
return l;
},
eG : j.prototype.eG,
vp : g ? function() {
var l = this.$.tabIndex;
if (l === 0
&& !a.ga.ug[this.getName()]
&& parseInt(this.getAttribute('tabindex'),
10) !== 0)
l = -1;
return l;
}
: f.webkit ? function() {
var l = this.$.tabIndex;
if (l == undefined) {
l = parseInt(this
.getAttribute('tabindex'), 10);
if (isNaN(l))
l = -1;
}
return l;
} : function() {
return this.$.tabIndex;
},
getText : function() {
return this.$.textContent || this.$.innerText || '';
},
getWindow : function() {
return this.getDocument().getWindow();
},
dS : function() {
return this.$.id || null;
},
data : function(l, m) {
l = 'data-' + l;
if (m === undefined)
return this.getAttribute(l);
else if (m === false)
this.removeAttribute(l);
else
this.setAttribute(l, m);
return null;
},
vm : function() {
return this.$.name || null;
},
getName : function() {
var l = this.$.nodeName.toLowerCase();
if (g) {
var m = this.$.scopeName;
if (m != 'HTML')
l = m.toLowerCase() + ':' + l;
}
return (this.getName = function() {
return l;
})();
},
getValue : function() {
return this.$.value;
},
getFirst : function() {
var l = this.$.firstChild;
return l ? new h.bi(l) : null;
},
dB : function(l) {
var m = this.$.lastChild, n = m && new h.bi(m);
if (n && l && !l(n))
n = n.cf(l);
return n;
},
rd : function(l) {
return this.$.style[i.cssStyleToDomStyle(l)];
},
is : function() {
var l = this.getName();
for ( var m = 0; m < arguments.length; m++) {
if (arguments[m] == l)
return true;
}
return false;
},
vL : function() {
var l = this.getName(), m = !a.ga.uj[l]
&& (a.ga[l] || a.ga.span);
return m && m['#'];
},
isIdentical : function(l) {
if (this.getName() != l.getName())
return false;
var m = this.$.attributes, n = l.$.attributes, o = m.length, p = n.length;
if (!g && o != p)
return false;
for ( var q = 0; q < o; q++) {
var r = m[q];
if ((!g || r.specified && r.nodeName != 'dj')
&& r.nodeValue != l
.getAttribute(r.nodeName))
return false;
}
if (g)
for (q = 0; q < p; q++) {
r = n[q];
if ((!g || r.specified
&& r.nodeName != 'dj')
&& r.nodeValue != m
.getAttribute(r.nodeName))
return false;
}
return true;
},
isVisible : function() {
return this.$.offsetWidth
&& this.$.style.visibility != 'hidden';
},
hasAttributes : g && (f.ie7Compat || f.ie6Compat) ? function() {
var l = this.$.attributes;
for ( var m = 0; m < l.length; m++) {
var n = l[m];
switch (n.nodeName) {
case 'class':
if (this.getAttribute('class'))
return true;
case 'dj':
continue;
default:
if (n.specified)
return true;
}
}
return false;
}
: function() {
var l = this.$.attributes;
return l.length > 1 || l.length == 1
&& l[0].nodeName != 'dj';
},
hasAttribute : function(l) {
var m = this.$.attributes.getNamedItem(l);
return !!(m && m.specified);
},
hide : function() {
this.setStyle('display', 'none');
},
jg : function(l, m) {
var n = this.$;
l = l.$;
if (n == l)
return;
var o;
if (m)
while (o = n.lastChild)
l.insertBefore(n.removeChild(o),
l.firstChild);
else
while (o = n.firstChild)
l.appendChild(n.removeChild(o));
},
show : function() {
this.setStyles( {
display : '',
visibility : ''
});
},
setAttribute : (function() {
var l = function(m, n) {
this.$.setAttribute(m, n);
return this;
};
if (g && (f.ie7Compat || f.ie6Compat))
return function(m, n) {
var o = this;
if (m == 'class')
o.$.className = n;
else if (m == 'style')
o.$.style.cssText = n;
else if (m == 'tabindex')
o.$.tabIndex = n;
else if (m == 'checked')
o.$.checked = n;
else
l.apply(o, arguments);
return o;
};
else
return l;
})(),
setAttributes : function(l) {
for ( var m in l)
this.setAttribute(m, l[m]);
return this;
},
setValue : function(l) {
this.$.value = l;
return this;
},
removeAttribute : (function() {
var l = function(m) {
this.$.removeAttribute(m);
};
if (g && (f.ie7Compat || f.ie6Compat))
return function(m) {
if (m == 'class')
m = 'className';
else if (m == 'tabindex')
m = 'tabIndex';
l.call(this, m);
};
else
return l;
})(),
uW : function(l) {
for ( var m = 0; m < l.length; m++)
this.removeAttribute(l[m]);
},
removeStyle : function(l) {
var m = this;
if (m.$.style.removeAttribute)
m.$.style.removeAttribute(i
.cssStyleToDomStyle(l));
else
m.setStyle(l, '');
if (!m.$.style.cssText)
m.removeAttribute('style');
},
setStyle : function(l, m) {
this.$.style[i.cssStyleToDomStyle(l)] = m;
return this;
},
setStyles : function(l) {
for ( var m in l)
this.setStyle(m, l[m]);
return this;
},
setOpacity : function(l) {
if (g) {
l = Math.round(l * 100);
this
.setStyle(
'filter',
l >= 100 ? ''
: 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + l + ')');
} else
this.setStyle('opacity', l);
},
unselectable : f.gecko ? function() {
this.$.style.MozUserSelect = 'none';
} : f.webkit ? function() {
this.$.style.uE = 'none';
} : function() {
if (g || f.opera) {
var l = this.$, m, n = 0;
l.unselectable = 'on';
while (m = l.all[n++])
switch (m.tagName.toLowerCase()) {
case 'iframe':
case 'textarea':
case 'input':
case 'select':
break;
default:
m.unselectable = 'on';
}
}
},
vr : function() {
var l = this;
while (l.getName() != 'html') {
if (l.getComputedStyle('position') != 'static')
return l;
l = l.getParent();
}
return null;
},
ir : function(l) {
var G = this;
var m = 0, n = 0, o = G.getDocument().bH(), p = G
.getDocument().$.compatMode == 'BackCompat', q = G
.getDocument();
if (document.documentElement.getBoundingClientRect) {
var r = G.$.getBoundingClientRect(), s = q.$, t = s.documentElement, u = t.clientTop
|| o.$.clientTop || 0, v = t.clientLeft
|| o.$.clientLeft || 0, w = true;
if (g) {
var x = q.gT().contains(G), y = q.bH()
.contains(G);
w = p && y || !p && x;
}
if (w) {
m = r.left
+ (!p && t.scrollLeft || o.$.scrollLeft);
m -= v;
n = r.top
+ (!p && t.scrollTop || o.$.scrollTop);
n -= u;
}
} else {
var z = G, A = null, B;
while (z
&& !(z.getName() == 'body' || z
.getName() == 'html')) {
m += z.$.offsetLeft - z.$.scrollLeft;
n += z.$.offsetTop - z.$.scrollTop;
if (!z.equals(G)) {
m += z.$.clientLeft || 0;
n += z.$.clientTop || 0;
}
var C = A;
while (C && !C.equals(z)) {
m -= C.$.scrollLeft;
n -= C.$.scrollTop;
C = C.getParent();
}
A = z;
z = (B = z.$.offsetParent) ? new k(B)
: null;
}
}
if (l) {
var D = G.getWindow(), E = l.getWindow();
if (!D.equals(E) && D.$.frameElement) {
var F = new k(D.$.frameElement).ir(l);
m += F.x;
n += F.y;
}
}
if (!document.documentElement.getBoundingClientRect)
if (f.gecko && !p) {
m += G.$.clientLeft ? 1 : 0;
n += G.$.clientTop ? 1 : 0;
}
return {
x : m,
y : n
};
},
scrollIntoView : function(l) {
var r = this;
var m = r.getWindow(), n = m.eR().height, o = n
* -1;
if (l)
o += n;
else {
o += r.$.offsetHeight || 0;
o += parseInt(r
.getComputedStyle('marginBottom') || 0,
10) || 0;
}
var p = r.ir();
o += p.y;
o = o < 0 ? 0 : o;
var q = m.hV().y;
if (o > q || o < q - n)
m.$.scrollTo(0, o);
},
bR : function(l) {
var m = this;
switch (l) {
case a.eV:
m.addClass('cke_on');
m.removeClass('cke_off');
m.removeClass('cke_disabled');
break;
case a.aY:
m.addClass('cke_disabled');
m.removeClass('cke_off');
m.removeClass('cke_on');
break;
default:
m.addClass('cke_off');
m.removeClass('cke_on');
m.removeClass('cke_disabled');
break;
}
},
getFrameDocument : function() {
var l = this.$;
try {
l.contentWindow.document;
} catch (m) {
l.src = l.src;
if (g && f.version < 7)
window
.showModalDialog('javascript:document.write("<script>window.setTimeout(function(){window.close();},50);</script>")');
}
return l && new j(l.contentWindow.document);
},
qw : function(l, m) {
var s = this;
var n = s.$.attributes;
m = m || {};
for ( var o = 0; o < n.length; o++) {
var p = n[o];
if (p.specified || g && p.nodeValue
&& p.nodeName.toLowerCase() == 'value') {
var q = p.nodeName;
if (q in m)
continue;
var r = s.getAttribute(q);
if (r === null)
r = p.nodeValue;
l.setAttribute(q, r);
}
}
if (s.$.style.cssText !== '')
l.$.style.cssText = s.$.style.cssText;
},
renameNode : function(l) {
var o = this;
if (o.getName() == l)
return;
var m = o.getDocument(), n = new k(l, m);
o.qw(n);
o.jg(n);
o.$.parentNode.replaceChild(n.$, o.$);
n.$.dj = o.$.dj;
o.$ = n.$;
},
getChild : function(l) {
var m = this.$;
if (!l.slice)
m = m.childNodes[l];
else
while (l.length > 0 && m)
m = m.childNodes[l.shift()];
return m ? new h.bi(m) : null;
},
iu : function() {
return this.$.childNodes.length;
},
hX : function() {
this.on('contextmenu', function(l) {
if (!l.data.bK().hasClass(
'cke_enable_context_menu'))
l.data.preventDefault();
});
},
'toString' : function() {
return this.getName() + '#' + this.dS() + '.'
+ this.getAttribute('class');
}
});
(function() {
var l = {
width : [ 'border-left-width', 'border-right-width',
'padding-left', 'padding-right' ],
height : [ 'border-top-width', 'border-bottom-width',
'padding-top', 'padding-bottom' ]
};
function m(n) {
var o = 0;
for ( var p = 0, q = l[n].length; p < q; p++)
o += parseInt(this.getComputedStyle(l[n][p]) || 0, 10) || 0;
return o;
}
;
k.prototype.setSize = function(n, o, p) {
if (typeof o == 'number') {
if (p && !(g && f.quirks))
o -= m.call(this, n);
this.setStyle(n, o + 'px');
}
};
k.prototype.hR = function(n, o) {
var p = Math.max(this.$['offset' + i.capitalize(n)],
this.$['client' + i.capitalize(n)]) || 0;
if (o)
p -= m.call(this, n);
return p;
};
})();
a.command = function(l, m) {
this.pW = [];
this.exec = function(n) {
if (this.bu == a.aY)
return false;
if (m.oD)
l.focus();
return m.exec.call(this, l, n) !== false;
};
i.extend(this, m, {
iH : {
qt : 1
},
oD : true,
bu : a.aS
});
a.event.call(this);
};
a.command.prototype = {
enable : function() {
var l = this;
if (l.bu == a.aY)
l.bR(!l.vf || typeof l.lJ == 'undefined' ? a.aS : l.lJ);
},
disable : function() {
this.bR(a.aY);
},
bR : function(l) {
var m = this;
if (m.bu == l)
return false;
m.lJ = m.bu;
m.bu = l;
m.oW('bu');
return true;
},
rJ : function() {
var l = this;
if (l.bu == a.aS)
l.bR(a.eV);
else if (l.bu == a.eV)
l.bR(a.aS);
}
};
a.event.du(a.command.prototype, true);
a.config = {
customConfig : a.getUrl('config.js'),
connectorLanguage : 'php',
language : '',
defaultLanguage : 'en',
defaultViewType : 'thumbnails',
defaultSortBy : 'filename',
defaultDisplayFilename : true,
defaultDisplayDate : true,
defaultDisplayFilesize : true,
pO : '',
height : 400,
plugins : 'foldertree,folder,filebrowser,container,connector,resource,toolbar,formpanel,filesview,status,contextmenu,uploadform,keystrokes,dragdrop,basket,dialog,tools,resize,help,flashupload,mobile',
extraPlugins : '',
fileIcons : 'ai|avi|bmp|cs|dll|doc|docx|exe|fla|gif|jpg|js|mdb|mp3|ogg|pdf|ppt|pptx|rdp|swf|swt|txt|vsd|xls|xlsx|xml|zip',
removePlugins : '',
tabIndex : 0,
thumbnailDelay : 50,
theme : 'default',
skin : 'kama',
width : '100%',
baseFloatZIndex : 10000,
directDownload : false,
log : false,
logStackTrace : false,
rememberLastFolder : true,
id : null,
startupPath : '',
startupFolderExpanded : true,
selectActionFunction : null,
selectActionData : null,
selectThumbnailActionFunction : null,
selectThumbnailActionData : null,
disableThumbnailSelection : false,
thumbsUrl : null,
thumbsDirectAccess : false,
imagesMaxWidth : 0,
imagesMaxHeight : 0,
selectActionType : 'js',
resourceType : null,
disableHelpButton : false,
connectorPath : '',
uiColor : null,
showContextMenuArrow : false,
useNativeIcons : false
};
CKFinder.config = a.config;
var l = a.config;
a.dU = function(m, n) {
this.rG = m;
this.message = n;
};
a.fs = function(m) {
if (m.fs)
return m.fs;
this.hasFocus = false;
this._ = {
application : m
};
return this;
};
a.fs.prototype = {
focus : function() {
var n = this;
if (n._.fW)
clearTimeout(n._.fW);
if (!n.hasFocus) {
if (a.eq)
a.eq.fs.ly();
var m = n._.application;
m.container.getFirst().addClass('cke_focus');
n.hasFocus = true;
m.oW('focus');
}
},
blur : function() {
var m = this;
if (m._.fW)
clearTimeout(m._.fW);
m._.fW = setTimeout(function() {
delete m._.fW;
m.ly();
}, 100);
},
ly : function() {
if (this.hasFocus) {
var m = this._.application;
m.container.getFirst().removeClass('cke_focus');
this.hasFocus = false;
m.oW('blur');
}
}
};
(function() {
var m = {};
a.lang = {
ko : {
cs : 1,
da : 1,
de : 1,
el : 1,
en : 1,
es : 1,
'es-mx' : 1,
et : 1,
fa : 1,
fi : 1,
fr : 1,
he : 1,
hu : 1,
it : 1,
ja : 1,
lv : 1,
lt : 1,
nb : 1,
nl : 1,
no : 1,
nn : 1,
pl : 1,
'pt-br' : 1,
ru : 1,
sk : 1,
sl : 1,
sv : 1,
tr : 1,
'zh-cn' : 1,
'zh-tw' : 1
},
load : function(n, o, p) {
if (!n || !a.lang.ko[n])
n = this.jV(o, n);
if (!this[n])
a.ec.load(a.getUrl('lang/' + n + '.js'), function() {
p(n, CKFinder.lang[n]);
}, this);
else
p(n, this[n]);
},
jV : function(n, o) {
var p = this.ko;
o = o || navigator.userLanguage || navigator.language;
var q = o.toLowerCase().match(/([a-z]+)(?:-([a-z]+))?/), r = q[1], s = q[2];
if (p[r + '-' + s])
r = r + '-' + s;
else if (!p[r])
r = null;
a.lang.jV = r ? function() {
return r;
} : function(t) {
return t;
};
return r || n;
}
};
})();
(function() {
a.log = function() {
if (!l.log && !window.CKFINDER_LOG)
return;
var m = '';
for ( var n = 0; n < arguments.length; n++) {
var o = arguments[n];
if (!o)
continue;
if (m)
m += '; ';
switch (typeof o) {
case 'function':
var p = /function (\w+?)\(/.exec(o.toString());
p = p ? p[1] : 'anonymous func';
m += p;
break;
default:
m += o ? o.toString() : '';
}
}
a._.log.push(m);
if (typeof window.console == 'object')
if (!console.log.apply)
console.log(m);
else
console.log.apply(console, arguments);
};
a.ba = function(m) {
if (l.logStackTrace)
a.log('[EXCEPTION] ' + m.toString());
return m;
};
a.mZ = function(m) {
var n = '';
for ( var o = 0; o < a._.log.length; o++)
n += o + 1 + '. ' + a._.log[o] + '\n';
return n;
};
a._.log = [];
})();
a.ec = (function() {
var m = {}, n = {};
return {
load : function(o, p, q, r, s) {
var t = typeof o == 'string';
if (t)
o = [ o ];
if (!q)
q = a;
var u = o.length, v = [], w = [], x = function(C) {
if (p)
if (t)
p.call(q, C);
else
p.call(q, v, w);
};
if (u === 0) {
x(true);
return;
}
var y = function(C, D) {
(D ? v : w).push(C);
if (--u <= 0)
x(D);
}, z = function(C, D) {
m[C] = 1;
var E = n[C];
delete n[C];
for ( var F = 0; F < E.length; F++)
E[F](C, D);
}, A = function(C) {
if (r !== true && m[C]) {
y(C, true);
return;
}
var D = n[C] || (n[C] = []);
D.push(y);
if (D.length > 1)
return;
var E = new k('script');
E.setAttributes( {
type : 'text/javascript',
src : C
});
if (p)
if (g)
E.$.onreadystatechange = function() {
if (E.$.readyState == 'loaded'
|| E.$.readyState == 'complete') {
E.$.onreadystatechange = null;
a.log('[LOADED] ' + C);
z(C, true);
}
};
else {
E.$.onload = function() {
setTimeout(function() {
a.log('[LOADED] ' + C);
z(C, true);
}, 0);
};
E.$.onerror = function() {
z(C, false);
};
}
E.appendTo(s ? s : a.document.eD());
};
for ( var B = 0; B < u; B++)
A(o[B]);
},
uq : function(o) {
var p = new k('script');
p.setAttribute('type', 'text/javascript');
p.appendText(o);
p.appendTo(a.document.eD());
}
};
})();
a.fQ = function(m, n) {
var o = this;
o.basePath = m;
o.fileName = n;
o.bX = {};
o.loaded = {};
o.jn = {};
o._ = {
rZ : {}
};
};
a.fQ.prototype = {
add : function(m, n) {
if (this.bX[m])
throw '[CKFINDER.fQ.add] The resource name "' + m + '" is already bX.';
this.bX[m] = n || {};
},
eB : function(m) {
return this.bX[m] || null;
},
getPath : function(m) {
var n = this.jn[m];
return a.getUrl(n && n.dir || this.basePath + m + '/');
},
pi : function(m) {
var n = this.jn[m];
return a.getUrl(this.getPath(m)
+ (n && n.file || this.fileName + '.js'));
},
tR : function(m, n, o) {
m = m.split(',');
for ( var p = 0; p < m.length; p++) {
var q = m[p];
this.jn[q] = {
dir : n,
file : o
};
}
},
load : function(m, n, o) {
if (!i.isArray(m))
m = m ? [ m ] : [];
var p = this.loaded, q = this.bX, r = [], s = {}, t = {};
for ( var u = 0; u < m.length; u++) {
var v = m[u];
if (!v)
continue;
if (!p[v] && !q[v]) {
var w = this.pi(v);
r.push(w);
if (!(w in s))
s[w] = [];
s[w].push(v);
} else
t[v] = this.eB(v);
}
a.ec.load(r, function(x, y) {
if (y.length)
throw '[CKFINDER.fQ.load] Resource name "'
+ s[y[0]].join(',') + '" was not found at "' + y[0]
+ '".';
for ( var z = 0; z < x.length; z++) {
var A = s[x[z]];
for ( var B = 0; B < A.length; B++) {
var C = A[B];
t[C] = this.eB(C);
p[C] = 1;
}
}
n.call(o, t);
}, this);
}
};
a.plugins = new a.fQ('plugins/', 'plugin');
var m = a.plugins;
m.load = i.override(m.load, function(n) {
return function(o, p, q) {
var r = {}, s = function(t) {
n.call(this, t, function(u) {
i.extend(r, u);
var v = [];
for ( var w in u) {
var x = u[w], y = x && x.bM;
if (y)
for ( var z = 0; z < y.length; z++) {
if (!r[y[z]])
v.push(y[z]);
}
}
if (v.length)
s.call(this, v);
else {
for (w in r) {
x = r[w];
if (x.onLoad && !x.onLoad.qK) {
x.onLoad();
x.onLoad.qK = 1;
}
}
if (p)
p.call(q || window, r);
}
}, this);
};
s.call(this, o);
};
});
m.rX = function(n, o, p) {
var q = this.eB(n);
q.lang[o] = p;
};
(function() {
var n = {}, o = function(p, q) {
var r = function() {
n[p] = 1;
q();
}, s = new k('img');
s.on('load', r);
s.on('error', r);
s.setAttribute('src', p);
};
a.rw = {
load : function(p, q) {
var r = p.length, s = function() {
if (--r === 0)
q();
};
for ( var t = 0; t < p.length; t++) {
var u = p[t];
if (n[u])
s();
else
o(u, s);
}
}
};
})();
a.skins = (function() {
var n = {}, o = {}, p = {}, q = function(r, s, t, u) {
var v = n[s];
if (!r.skin) {
r.skin = v;
if (v.bz)
v.bz(r);
}
var w = function(E) {
for ( var F = 0; F < E.length; F++)
E[F] = a.getUrl(p[s] + E[F]);
};
if (!o[s]) {
var x = v.ls;
if (x && x.length > 0) {
w(x);
a.rw.load(x, function() {
o[s] = 1;
q(r, s, t, u);
});
return;
}
o[s] = 1;
}
t = v[t];
var y = 0;
if (t) {
if (!t.iB)
t.iB = [];
else if (t.iB[r.name])
y = 1;
} else
y = 1;
if (y)
u && u();
else {
if (t.eb === undefined)
t.eb = [];
if (t.eb[r.name] === undefined)
t.eb[r.name] = [];
var z = t.eb[r.name];
z.push(u);
if (z.length > 1)
return;
var A = !t.css || !t.css.length, B = !t.js || !t.js.length, C = function() {
if (A && B) {
t.iB[r.name] = 1;
for ( var E = 0; E < z.length; E++) {
if (z[E])
z[E]();
}
}
};
if (!A) {
if (!t.rr) {
w(t.css);
t.rr = 1;
}
if (t.qx)
for ( var D = 0; D < t.css.length; D++)
a.oC.pb(t.css[D]);
else
r
.on(
'themeSpace',
function(E) {
if (E.data.space == 'head')
for ( var F = 0; F < t.css.length; F++)
E.data.html += "<link rel='stylesheet' href='"
+ t.css[F] + "'>\n";
E.removeListener();
});
A = 1;
}
if (!B) {
w(t.js);
r.ec.load(t.js, function() {
B = 1;
C();
});
}
C();
}
};
return {
add : function(r, s) {
n[r] = s;
s.fh = p[r] || (p[r] = a.getUrl('skins/' + r + '/'));
},
loaded : n,
load : function(r, s, t) {
var u = r.gd, v = r.fh;
if (n[u]) {
q(r, u, s, t);
var w = n[u];
} else {
p[u] = v;
a.ec.load(v + 'skin.js', function() {
q(r, u, s, t);
});
}
}
};
})();
a.gc = new a.fQ('gc/', 'theme');
a.bY = function(n) {
if (n.bY)
return n.bY;
this._ = {
jZ : {},
items : {},
application : n
};
return this;
};
var n = a.bY;
n.prototype = {
add : function(o, p, q) {
this._.items[o] = {
type : p,
command : q.command || null,
mp : Array.prototype.slice.call(arguments, 2)
};
},
create : function(o) {
var t = this;
var p = t._.items[o], q = p && t._.jZ[p.type], r = p && p.command
&& t._.application.cS(p.command), s = q
&& q.create.apply(t, p.mp);
if (r)
r.pW.push(s);
return s;
},
kd : function(o, p) {
this._.jZ[o] = p;
}
};
(function() {
var o = 0, p = function() {
var y = 'ckfinder' + ++o;
return a.instances && a.instances[y] ? p() : y;
}, q = {}, r = function(y) {
var z = y.config.customConfig;
if (!z)
return false;
var A = q[z] || (q[z] = {});
if (A.gg) {
A.gg.call(y, y.config);
if (y.config.customConfig == z || !r(y))
y.cr('customConfigLoaded');
} else
a.ec.load(z, function() {
if (CKFinder.customConfig)
A.gg = CKFinder.customConfig;
else
A.gg = function() {
};
r(y);
});
return true;
}, s = function(y, z) {
y.on('customConfigLoaded', function() {
if (z) {
if (z.on)
for ( var A in z.on)
y.on(A, z.on[A]);
i.extend(y.config, z, true);
delete y.config.on;
}
t(y);
});
if (z && z.customConfig != undefined)
y.config.customConfig = z.customConfig;
if (!r(y))
y.cr('customConfigLoaded');
}, t = function(y) {
var z = y.config.skin.split(','), A = z[0], B = a.getUrl(z[1]
|| 'skins/' + A + '/');
y.gd = A;
y.fh = B;
y.iy = 'cke_skin_' + A + ' skin_' + A;
y.qn = y.ox();
y.on('uiReady', function() {
y.document.getWindow().on(
'lW',
function() {
i.setCookie('CKFinder_UTime', Math.round(new Date()
.getTime() / 1000), true);
i.setCookie('CKFinder_UId',
encodeURIComponent(y.id ? y.id
: location.href), true);
});
});
y.cr('configLoaded');
u(y);
}, u = function(y) {
a.lang
.load(
y.config.language,
y.config.defaultLanguage,
function(z, A) {
y.langCode = z;
y.lang = i.prototypedCopy(A);
y.lB = (function() {
var B = "['" + y.lang.DateAmPm.join("','")
+ "']", C = y.lang.DateTime
.replace(
/dd|mm|yyyy|hh|HH|MM|aa|d|m|yy|h|H|M|a/g,
function(D) {
var E;
switch (D) {
case 'd':
E = "day.replace(/^0/,'')";
break;
case 'dd':
E = 'day';
break;
case 'm':
E = "month.replace(/^0/,'')";
break;
case 'mm':
E = 'month';
break;
case 'yy':
E = 'year.substr(2)';
break;
case 'yyyy':
E = 'year';
break;
case 'H':
E = "hour.replace(/^0/,'')";
break;
case 'HH':
E = 'hour';
break;
case 'h':
E = "( hour < 12 ? hour : ( ( hour - 12 ) + 100 ).toString().substr( 1 ) ).replace(/^0/,'')";
break;
case 'hh':
E = '( hour < 12 ? hour : ( ( hour - 12 ) + 100 ).toString().substr( 1 ) )';
break;
case 'M':
E = "minute.replace(/^0/,'')";
break;
case 'MM':
E = 'minute';
break;
case 'a':
E = B + '[ hour < 12 ? 0 : 1 ].charAt(0)';
break;
case 'aa':
E = B + '[ hour < 12 ? 0 : 1 ]';
break;
default:
E = "'" + D + "'";
}
return "'," + E + ",'";
});
C = "'" + C + "'";
C = C.replace(/('',)|,''$/g, '');
return new Function('day', 'month', 'year',
'hour', 'minute', 'return [' + C
+ "].join('');");
})();
if (f.gecko && f.version < 10900
&& y.lang.dir == 'rtl')
y.lang.dir = 'ltr';
v(y);
});
}, v = function(y) {
var z = y.config, A = z.plugins, B = z.extraPlugins, C = z.removePlugins;
if (B) {
var D = new RegExp(
'(?:^|,)(?:' + B.replace(/\s*,\s*/g, '|') + ')(?=,|$)',
'g');
A = A.replace(D, '');
A += ',' + B;
}
if (C) {
D = new RegExp(
'(?:^|,)(?:' + C.replace(/\s*,\s*/g, '|') + ')(?=,|$)',
'g');
A = A.replace(D, '');
}
m.load(A.split(','), function(E) {
var F = [], G = [], H = [];
y.plugins = E;
for ( var I in E) {
var J = E[I], K = J.lang, L = m.getPath(I), M = null;
E[I].name = I;
J.pathName = L;
if (K) {
M = i.indexOf(K, y.langCode) >= 0 ? y.langCode : K[0];
if (!J.lang[M])
H.push(a.getUrl(L + 'lang/' + M + '.js'));
else {
i.extend(y.lang, J.lang[M]);
M = null;
}
}
G.push(M);
F.push(J);
}
a.ec.load(H, function() {
var N = [ 'eK', 'bz', 'gr' ];
for ( var O = 0; O < N.length; O++)
for ( var P = 0; P < F.length; P++) {
var Q = F[P];
if (O === 0 && G[P] && Q.lang)
i.extend(y.lang, Q.lang[G[P]]);
if (Q[N[O]]) {
a.log('[PLUGIN] ' + Q.name + '.' + N[O]);
Q[N[O]](y);
}
}
y.oW('pluginsLoaded');
w(y);
});
});
}, w = function(y) {
a.skins.load(y, 'application', function() {
a.skins.load(y, 'host', function() {
x(y);
});
});
}, x = function(y) {
var z = y.config.theme;
a.gc.load(z, function() {
var A = y.theme = a.gc.eB(z);
A.pathName = a.gc.getPath(z);
y.oW('themeAvailable');
});
};
a.application.prototype.iI = function(y) {
var z = k.eB(this._.element), A = this._.kw;
delete this._.element;
delete this._.kw;
this._.ky = {};
this._.gS = [];
z.getDocument().getWindow().$.CKFinder = y;
this.element = z;
this.document = null;
this.rQ = {};
this.name = p();
if (this.name in a.instances)
throw '[CKFINDER.application] The instance "' + this.name + '" already exists.';
this.config = i.prototypedCopy(l);
this.bY = new n(this);
this.fs = new a.fs(this);
this.aL = {};
this.aG = {};
this.on('uiReady', function(B) {
this.document.getWindow().on('lW', this.fH, this);
}, this);
this.cg = new d(this);
this
.on(
'configLoaded',
function(B) {
e(this.cg, this, this.config.callback);
this.id = this.config.id;
if (this.cg.inPopup) {
var C = this, D = [ a.oC ];
if (C.cg.inUrlPopup)
D
.push(new j(
a.oC.getWindow().$.opener.document));
for ( var E = 0; E < D.length; E++)
D[E].bH().$.onbeforeunload = D[E]
.getWindow().$.onunload = D[E]
.getWindow().$.onbeforeunload = function() {
C.element.getDocument().getWindow().$
.close();
};
}
}, this);
s(this, A);
a.oW('instanceCreated', null, this);
};
})();
i.extend(a.application.prototype, {
bD : function(o, p) {
return this._.ky[o] = new a.command(this, p);
},
fH : function(o) {
var p = this;
if (!o)
p.hS();
p.theme.fH(p);
p.oW('fH');
a.remove(p);
},
execCommand : function(o, p) {
a.log('[COMMAND] ' + o);
var q = this.cS(o), r = {
name : o,
rm : p,
command : q
};
if (q && q.bu != a.aY)
if (this.oW('beforeCommandExec', r) !== true) {
r.returnValue = q.exec(r.rm);
if (!q.async && this.oW('afterCommandExec', r) !== true)
return r.returnValue;
}
return false;
},
cS : function(o) {
return this._.ky[o];
},
ox : function() {
var o = Math.round(new Date().getTime() / 1000), p = i
.getCookie('CKFinder_UTime'), q = decodeURIComponent(i
.getCookie('CKFinder_UId'));
if (q && p && q == (this.id ? this.id : location.href)
&& Math.abs(o - p) < 5)
return 1;
return 0;
},
bs : ''
});
(function() {
var o = '';
for ( var p = 49; p < 58; p++)
o += String.fromCharCode(p);
for (p = 65; p < 91; p++) {
if (p == 73 || p == 79)
continue;
o += String.fromCharCode(p);
}
a.bs = o;
a.nd = "\x6c\x6f";
a.jG = "\x68\157";
a.hf = new window["\x52\x65\147\105\x78\160"](
"\136\x77\x77\167\134\056");
a.hg = new window["\122\x65\x67\x45\x78\x70"]("\x3a\x5c\144\053\044");
a.lS = function(q) {
return q.toLowerCase().replace(a.hf, '').replace(a.hg, '');
};
})();
a.on('loaded', function() {
var o = a.application.eb;
if (o) {
delete a.application.eb;
for ( var p = 0; p < o.length; p++)
o[p].iI();
}
});
delete a.dO;
a.instances = {};
a.document = new j(document);
a.oC = a.document.getWindow().$ != a.document.getWindow().$.top ? new j(
a.document.getWindow().$.top.document) : a.document;
a.add = function(o) {
a.instances[o.name] = o;
a.jt = o;
o.on('focus', function() {
if (a.eq != o) {
a.eq = o;
a.oW('eq');
}
});
o.on('blur', function() {
if (a.eq == o) {
a.eq = null;
a.oW('eq');
}
});
};
a.remove = function(o) {
delete a.instances[o.name];
};
a.aL = {};
a.eV = 1;
a.aS = 2;
a.aY = 0;
a.bF = '';
(function() {
function o(r, s) {
return r + '.' + (s.name || s || r);
}
;
a.aG = {
bX : {},
hi : function(r, s, t) {
var u = o(r, s);
if (this.bX[u] !== undefined)
throw '[CKFINDER] Widget ' + u + ' already bX!';
a.log('[WIDGET] bX ' + u);
this.bX[u] = new q(u, t);
return this.bX[u];
},
bz : function(r, s, t, u, v) {
var w = o(s, t), x = this.bX[w], y = i.deepCopy(x.hF), z = function(
C, D, E) {
this.app = C;
this.eh = D instanceof k ? D : new k(D);
this.hF = y ? i.extend(y, E) : E || {};
this._ = {};
var F = function(I) {
this.ib = I;
};
F.prototype = this.tools;
this.tools = new F(this);
var G = x.dT;
if (G.length)
for ( var H = 0; H < G.length; H++)
G[H].call(this, C, this);
};
z.prototype = x;
var A = new z(r, u, v);
for ( var B in A.fw)
A.gA(B);
if (!r.aG[w])
r.aG[w] = [];
r.aG[w].push(A);
a.log('[WIDGET] instanced ' + w);
return A;
}
};
var p = {
click : 1,
mouseover : 1,
mouseout : 1,
focus : 1,
blur : 1,
submit : 1,
dblclick : 1,
mousedown : 1,
mouseup : 1,
mousemove : 1,
keypress : 1,
keydown : 1,
keyup : 1,
load : 1,
lW : 1,
abort : 1,
error : 1,
resize : 1,
scroll : 1,
select : 1,
change : 1,
reset : 1
}, q = function(r, s) {
var t = this;
t.id = r;
t.fw = {};
t.hF = s || {};
t.dT = [];
t.tools = new t.tools(t);
};
q.prototype = {
gA : function(r) {
var w = this;
a.log('[WIDGET] Enabling behavior ' + r);
var s = w.fw[r];
if (!s)
return;
var t = w;
for ( var u = 0; u < s.cC.length; u++) {
var v = s.cC[u];
if (p[v])
w.eh.on(v, s.fO, t);
else {
w.on(v, s.fO, t);
w.app.on(v, s.fO, t);
}
}
},
ke : function(r) {
a.log('[WIDGET] Disabling behavior ' + r);
var s = this.fw[r];
if (!s)
return;
for ( var t = 0; t < s.cC.length; t++) {
var u = s.cC[t];
if (p[u])
this.eh.removeListener(u, s.fO);
else
this.removeListener(u, s.fO);
}
},
bh : function(r, s, t) {
if (!i.isArray(s))
s = [ s ];
this.fw[r] = {
cC : s,
fO : t
};
if (this.eh)
this.gA(r);
},
removeBehavior : function(r) {
delete this.fw[r];
},
ur : function() {
return this.fw;
},
bn : function() {
return this.eh;
},
oE : function() {
return this.hF;
},
data : function() {
return this.hF;
},
tools : function() {
}
};
q.prototype.tools.prototype = {
kg : function(r) {
if (r.target == this.ib.eh)
return 1;
}
};
a.event.du(q.prototype);
})();
a.xml = function(o) {
var p = null;
if (typeof o == 'object')
p = o;
else {
var q = (o || '').replace(/ /g, '\xa0');
if (window.DOMParser)
p = new DOMParser().parseFromString(q, 'text/xml');
else if (window.ActiveXObject) {
try {
p = new ActiveXObject('MSXML2.DOMDocument');
} catch (r) {
try {
p = new ActiveXObject('Microsoft.XmlDom');
} catch (r) {
}
}
if (p) {
p.async = false;
p.resolveExternals = false;
p.validateOnParse = false;
p.loadXML(q);
}
}
}
this.mq = p;
};
a.xml.prototype = {
selectSingleNode : function(o, p) {
var q = this.mq;
if (p || (p = q))
if (g || p.selectSingleNode)
return p.selectSingleNode(o);
else if (q.evaluate) {
var r = q.evaluate(o, p, null, 9, null);
return r && r.singleNodeValue || null;
} else if (p.querySelectorAll) {
var s = this.selectNodes(o, p);
if (s.length == 1)
return s[0].getAttributeNode(o.match(/\/@(.*$)/)[1]);
} else
alert('XPath is not supported in your browser');
return null;
},
selectNodes : function(o, p) {
var q = this.mq, r = [];
if (p || (p = q))
if (g || p.selectNodes)
return p.selectNodes(o);
else if (q.evaluate) {
var s = q.evaluate(o, p, null, 5, null);
if (s) {
var t;
while (t = s.iterateNext())
r.push(t);
}
} else if (p.querySelectorAll) {
var u = o.replace(/\/@(.*$)/, '[$1]').replace(/\//gi, '>');
return p.querySelectorAll(u);
} else
alert('XPath is not supported in your browser');
return r;
},
vB : function(o, p) {
var q = this.selectSingleNode(o, p), r = [];
if (q) {
q = q.firstChild;
while (q) {
if (q.xml)
r.push(q.xml);
else if (window.XMLSerializer)
r.push(new XMLSerializer().serializeToString(q));
q = q.nextSibling;
}
}
return r.length ? r.join('') : null;
}
};
(function() {
var o = {
address : 1,
tY : 1,
dl : 1,
h1 : 1,
h2 : 1,
h3 : 1,
h4 : 1,
h5 : 1,
h6 : 1,
p : 1,
pre : 1,
li : 1,
dt : 1,
de : 1
}, p = {
body : 1,
div : 1,
table : 1,
tbody : 1,
tr : 1,
td : 1,
th : 1,
caption : 1,
form : 1
}, q = function(r) {
var s = r.getChildren();
for ( var t = 0, u = s.count(); t < u; t++) {
var v = s.getItem(t);
if (v.type == a.cv && a.ga.um[v.getName()])
return true;
}
return false;
};
h.qS = function(r) {
var x = this;
var s = null, t = null, u = [], v = r;
while (v) {
if (v.type == a.cv) {
if (!x.qH)
x.qH = v;
var w = v.getName();
if (g && v.$.scopeName != 'HTML')
w = v.$.scopeName.toLowerCase() + ':' + w;
if (!t) {
if (!s && o[w])
s = v;
if (p[w])
if (!s && w == 'div' && !q(v))
s = v;
else
t = v;
}
u.push(v);
if (w == 'body')
break;
}
v = v.getParent();
}
x.block = s;
x.tX = t;
x.elements = u;
};
})();
h.qS.prototype = {
sJ : function(o) {
var p = this.elements, q = o && o.elements;
if (!q || p.length != q.length)
return false;
for ( var r = 0; r < p.length; r++) {
if (!p[r].equals(q[r]))
return false;
}
return true;
}
};
h.text = function(o, p) {
if (typeof o == 'string')
o = (p ? p.$ : document).createTextNode(o);
this.$ = o;
};
h.text.prototype = new h.bi();
i.extend(h.text.prototype, {
type : a.fl,
hJ : function() {
return this.$.nodeValue.length;
},
getText : function() {
return this.$.nodeValue;
},
split : function(o) {
var t = this;
if (g && o == t.hJ()) {
var p = t.getDocument().jT('');
p.kB(t);
return p;
}
var q = t.getDocument(), r = new h.text(t.$.splitText(o), q);
if (f.ie8) {
var s = new h.text('', q);
s.kB(r);
s.remove();
}
return r;
},
substring : function(o, p) {
if (typeof p != 'number')
return this.$.nodeValue.substr(o);
else
return this.$.nodeValue.substring(o, p);
}
});
h.pa = function(o) {
o = o || a.document;
this.$ = o.$.createDocumentFragment();
};
i.extend(h.pa.prototype, k.prototype, {
type : a.om,
kA : function(o) {
o = o.$;
o.parentNode.insertBefore(this.$, o.nextSibling);
}
}, true, {
append : 1,
pd : 1,
getFirst : 1,
dB : 1,
appendTo : 1,
jg : 1,
insertBefore : 1,
kA : 1,
replace : 1,
trim : 1,
type : 1,
ltrim : 1,
rtrim : 1,
getDocument : 1,
iu : 1,
getChild : 1,
getChildren : 1
});
(function() {
function o(s, t) {
if (this._.end)
return null;
var u, v = this.mk, w, x = this.vR, y = this.type, z = s ? 'getPreviousSourceNode'
: 'getNextSourceNode';
if (!this._.start) {
this._.start = 1;
v.trim();
if (v.collapsed) {
this.end();
return null;
}
}
if (!s && !this._.kp) {
var A = v.endContainer, B = A.getChild(v.endOffset);
this._.kp = function(F, G) {
return (!G || !A.equals(F)) && (!B || !F.equals(B))
&& (F.type != a.cv || F.getName() != 'body');
};
}
if (s && !this._.ka) {
var C = v.startContainer, D = v.startOffset > 0
&& C.getChild(v.startOffset - 1);
this._.ka = function(F, G) {
return (!G || !C.equals(F)) && (!D || !F.equals(D))
&& (F.type != a.cv || F.getName() != 'body');
};
}
var E = s ? this._.ka : this._.kp;
if (x)
w = function(F, G) {
if (E(F, G) === false)
return false;
return x(F);
};
else
w = E;
if (this.current)
u = this.current[z](false, y, w);
else if (s) {
u = v.endContainer;
if (v.endOffset > 0) {
u = u.getChild(v.endOffset - 1);
if (w(u) === false)
u = null;
} else
u = w(u) === false ? null : u.hZ(true, y, w);
} else {
u = v.startContainer;
u = u.getChild(v.startOffset);
if (u) {
if (w(u) === false)
u = null;
} else
u = w(v.startContainer) === false ? null : v.startContainer
.hL(true, y, w);
}
while (u && !this._.end) {
this.current = u;
if (!this.lf || this.lf(u) !== false) {
if (!t)
return u;
} else if (t && this.lf)
return false;
u = u[z](false, y, w);
}
this.end();
return this.current = null;
}
;
function p(s) {
var t, u = null;
while (t = o.call(this, s))
u = t;
return u;
}
;
h.gm = i.createClass( {
$ : function(s) {
this.mk = s;
this._ = {};
},
ej : {
end : function() {
this._.end = 1;
},
next : function() {
return o.call(this);
},
previous : function() {
return o.call(this, true);
},
sC : function() {
return o.call(this, false, true) !== false;
},
sD : function() {
return o.call(this, true, true) !== false;
},
uF : function() {
return p.call(this);
},
uB : function() {
return p.call(this, true);
},
reset : function() {
delete this.current;
this._ = {};
}
}
});
var q = {
block : 1,
'list-item' : 1,
table : 1,
'table-row-group' : 1,
'table-header-group' : 1,
'table-footer-group' : 1,
'table-row' : 1,
'table-column-group' : 1,
'table-column' : 1,
'table-cell' : 1,
'table-caption' : 1
}, r = {
hr : 1
};
k.prototype.qy = function(s) {
var t = i.extend( {}, r, s || {});
return q[this.getComputedStyle('display')] || t[this.getName()];
};
h.gm.pQ = function(s) {
return function(t, u) {
return !(t.type == a.cv && t.qy(s));
};
};
h.gm.us = function() {
return this.pQ( {
br : 1
});
};
h.gm.tU = function(s) {
}, h.gm.tW = function(s, t) {
function u(v) {
return v && v.getName && v.getName() == 'span'
&& v.hasAttribute('_fck_bookmark');
}
;
return function(v) {
var w, x;
w = v && !v.getName && (x = v.getParent()) && u(x);
w = s ? w : w || u(v);
return t ^ w;
};
};
h.gm.sf = function(s) {
return function(t) {
var u = t && t.type == a.fl && !i.trim(t.getText());
return s ^ u;
};
};
})();
(function() {
if (f.webkit) {
f.hc = false;
return;
}
var o = g && f.version < 7, p = g && f.version == 7, q = o ? a.basePath + 'images/spacer.gif'
: p ? 'about:blank' : 'data:image/png;base64,', r = k
.kE(
'<div style="width:0px;height:0px;position:absolute;left:-10000px;background-image:url(' + q + ')"></div>',
a.document);
r.appendTo(a.document.eD());
try {
f.hc = r.getComputedStyle('background-image') == 'none';
} catch (s) {
f.hc = false;
}
if (f.hc)
f.cssClass += ' cke_hc';
r.remove();
})();
m.load(l.pO.split(','), function() {
a.status = 'loaded';
a.oW('loaded');
var o = a._.io;
if (o) {
delete a._.io;
for ( var p = 0; p < o.length; p++)
a.add(o[p]);
}
});
if (g)
try {
document.execCommand('BackgroundImageCache', false, true);
} catch (o) {
}
CKFinder.lang.en = {
appTitle : 'CKFinder',
common : {
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'
},
dir : 'ltr',
HelpLang : 'en',
LangCode : 'en',
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : [ 'AM', 'PM' ],
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...)',
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.',
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',
Upload : 'Upload',
UploadTip : 'Upload New File',
Refresh : 'Refresh',
Settings : 'Settings',
Help : 'Help',
HelpTip : 'Help',
Select : 'Select',
SelectThumbnail : 'Select Thumbnail',
View : 'View',
Download : 'Download',
NewSubFolder : 'New Subfolder',
Rename : 'Rename',
Delete : 'Delete',
CopyDragDrop : 'Copy File Here',
MoveDragDrop : 'Move File Here',
RenameDlgTitle : 'Rename',
NewNameDlgTitle : 'New Name',
FileExistsDlgTitle : 'File Already Exists',
SysErrorDlgTitle : 'System Error',
FileOverwrite : 'Overwrite',
FileAutorename : 'Auto-rename',
OkBtn : 'OK',
CancelBtn : 'Cancel',
CloseBtn : 'Close',
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.',
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...',
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',
FilesCountEmpty : '<Empty Folder>',
FilesCountOne : '1 file',
FilesCountMany : '%1 files',
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
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.'
},
ErrorMsg : {
pg : 'The file name cannot be empty.',
FileExists : 'File %s already exists.',
FolderEmpty : 'The folder name cannot be empty.',
oP : 'The file name cannot contain any of the following characters: \n\\ / : * ? " < > |',
FolderInvChar : 'The folder name cannot contain any of the following characters: \n\\ / : * ? " < > |',
oo : '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 : {
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 : {
save : 'Save',
fileOpenError : 'Unable to open file.',
fileSaveSuccess : 'File saved successfully.',
contextMenuName : 'Edit',
loadingFile : 'Loading file, please wait...'
},
Maximize : {
maximize : 'Maximize',
minimize : 'Minimize'
}
};
(function() {
var p = 1, q = 2, r = 4, s = 8, t = 16, u = 32, v = 64, w = 128;
a.aL.Acl = function(x) {
var y = this;
if (!x)
x = 0;
y.folderView = (x & p) == p;
y.folderCreate = (x & q) == q;
y.folderRename = (x & r) == r;
y.folderDelete = (x & s) == s;
y.fileView = (x & t) == t;
y.fileUpload = (x & u) == u;
y.fileRename = (x & v) == v;
y.fileDelete = (x & w) == w;
};
m.add('acl');
})();
(function() {
m
.add(
'connector',
{
bM : [],
bz : function(q) {
q
.on(
'appReady',
function() {
q.connector = new a.aL.Connector(
q);
var r = q.config.resourceType, s = r ? {
type : r
}
: null;
q.connector
.sendCommand(
'Init',
s,
function(t) {
var u;
if (t
.checkError())
return;
var v = "\103\157\156\156\x65\x63\164\x6f\x72\x2f\x43\157\156\x6e\145\143\x74\x6f\x72\111\156\x66\x6f\057";
a.ed = t
.selectSingleNode(v
+ "\x40\163").value;
a.bF = t
.selectSingleNode(v
+ "\100\143").value + '----';
q.config.thumbsEnabled = t
.selectSingleNode(v
+ "\100\x74\x68\x75\155\142\163\x45\156\x61\142\154\x65\144").value == 'true';
q.config.thumbsDirectAccess = false;
if (q.config.thumbsEnabled) {
u = t
.selectSingleNode(v
+ "\x40\164\150\x75\x6d\142\163\x55\x72\154");
if (u)
q.config.thumbsUrl = u.value;
u = t
.selectSingleNode(v
+ "\x40\x74\150\x75\155\142\x73\x44\151\162\x65\x63\164\x41\x63\143\x65\x73\x73");
if (u)
q.config.thumbsDirectAccess = u.value == 'true';
}
q.config.imagesMaxWidth = parseInt(
t
.selectSingleNode(v
+ "\x40\x69\155\147\x57\151\x64\164\x68").value,
10);
q.config.imagesMaxHeight = parseInt(
t
.selectSingleNode(v
+ "\100\151\x6d\x67\110\145\x69\x67\x68\x74").value,
10);
u = t
.selectSingleNode(v
+ "\100\165\x70\154\x6f\141\144\x4d\141\x78\x53\x69\172\145");
q.config.uploadMaxSize = u ? parseInt(
u.value,
10)
: 0;
u = t
.selectSingleNode(v
+ "\x40\x75\x70\x6c\157\141\144\x43\150\145\143\x6b\111\x6d\141\147\145\x73");
q.config.uploadCheckImages = u ? u.value == 'true'
: false;
var w = t
.selectSingleNode(v
+ "\100\x70\154\165\x67\x69\156\163"), x = w
&& w.value;
if (x
&& x.length)
m
.load(
x
.split(','),
function(
y) {
var z = [], A = [], B = [];
for ( var C in y) {
var D = y[C], E = D.lang, F = m
.getPath(C), G = null;
if (!q.plugins[C])
q.plugins[C] = y[C];
else
continue;
y[C].name = C;
D.pathName = F;
if (E) {
G = i
.indexOf(
E,
q.langCode) >= 0 ? q.langCode
: E[0];
if (!D.lang[G])
B
.push(a
.getUrl(F
+ 'lang/'
+ G
+ '.js'));
else {
i
.extend(
q.lang,
D.lang[G]);
G = null;
}
}
A
.push(G);
z
.push(D);
}
a.ec
.load(
B,
function() {
var H = [
'eK',
'bz',
'gr' ];
for ( var I = 0; I < H.length; I++)
for ( var J = 0; J < z.length; J++) {
var K = z[J];
if (I === 0
&& A[J]
&& K.lang)
i
.extend(
q.lang,
K.lang[A[J]]);
if (K[H[I]]) {
a
.log('[PLUGIN] '
+ K.name
+ '.'
+ H[I]);
K[H[I]]
(q);
}
}
q
.cr('uiReady');
q
.cr('appReady');
q
.oW(
'pluginsLoaded',
{
step : 2,
jN : q.connector
});
q
.cr(
'connectorInitialized',
{
xml : t
});
});
});
else {
q
.oW(
'pluginsLoaded',
{
step : 2,
jN : q.connector
});
q
.cr(
'connectorInitialized',
{
xml : t
});
}
});
});
}
});
a.aL.Connector = function(q) {
this.app = q;
var r = q.config.connectorLanguage || 'php';
if (q.config.connectorPath)
this.oN = q.config.connectorPath;
else
this.oN = a.basePath + 'core/connector/' + r + '/connector.'
+ r;
};
a.aL.Connector.prototype = {
ERROR_NONE : 0,
ERROR_CUSTOMERROR : 1,
ERROR_INVALIDCOMMAND : 10,
ERROR_TYPENOTSPECIFIED : 11,
ERROR_INVALIDTYPE : 12,
ERROR_INVALIDNAME : 102,
ERROR_UNAUTHORIZED : 103,
ERROR_ACCESSDENIED : 104,
ERROR_INVALIDEXTENSION : 105,
ERROR_INVALIDREQUEST : 109,
ERROR_UNKNOWN : 110,
ERROR_ALREADYEXIST : 115,
ERROR_FOLDERNOTFOUND : 116,
ERROR_FILENOTFOUND : 117,
ERROR_SOURCE_AND_TARGET_PATH_EQUAL : 118,
ERROR_UPLOADEDFILERENAMED : 201,
ERROR_UPLOADEDINVALID : 202,
ERROR_UPLOADEDTOOBIG : 203,
ERROR_UPLOADEDCORRUPT : 204,
ERROR_UPLOADEDNOTMPDIR : 205,
ERROR_UPLOADEDWRONGHTMLFILE : 206,
ERROR_UPLOADEDINVALIDNAMERENAMED : 207,
ERROR_MOVE_FAILED : 300,
ERROR_COPY_FAILED : 301,
ERROR_CONNECTORDISABLED : 500,
ERROR_THUMBNAILSDISABLED : 501,
currentFolderUrl : function() {
if (this.app.aV)
return this.app.aV.getUrl();
},
currentType : function() {
if (this.app.aV)
return this.app.aV.type;
},
currentTypeHash : function() {
if (this.app.aV)
return a.getResourceType(this.app.aV.type).hash;
},
currentResourceType : function() {
return a.getResourceType(this.currentType());
},
sendCommand : function(q, r, s, t, u) {
var v = this.composeUrl(q, r, t, u), w = this;
if (s)
return a.ajax.loadXml(v, function(x) {
x.hy = w.app;
s(i.extend(x, p));
});
else
return a.ajax.loadXml(v);
},
sendCommandPost : function(q, r, s, t, u, v) {
var w = this.composeUrl(q, r, u, v), x = this;
if (!s)
s = {};
s.CKFinderCommand = true;
if (t)
return a.ajax.loadXml(w, function(y) {
y.hy = x.app;
t(i.extend(y, p));
}, this.composeUrlParams(s));
else
return a.ajax.loadXml(w, null, this.composeUrlParams(s));
},
composeUrl : function(q, r, s, t) {
var w = this;
var u = w.oN + '?command=' + encodeURIComponent(q);
if (q != 'Init') {
var v = '';
if (!t)
t = w.app.aV;
if (s)
v = w.app.getResourceType(s).hash;
else
v = w.app.getResourceType(t.type).hash;
u += '&type=' + encodeURIComponent(s || w.app.aV.type)
+ '¤tFolder='
+ encodeURIComponent(t.getPath() || '')
+ '&langCode=' + w.app.langCode + '&hash=' + v;
}
if (r)
u += '&' + w.composeUrlParams(r);
if (w.app.id)
u += '&id=' + encodeURIComponent(w.app.id);
return u;
},
composeUrlParams : function(q) {
if (!q)
return '';
var r = '';
for ( var s in q) {
if (r.length)
r += '&';
r += encodeURIComponent(s) + '=' + encodeURIComponent(q[s]);
}
return r;
}
};
var p = {
checkError : function() {
var w = this;
var q = w.getErrorNumber(), r = w.hy.connector;
if (q == r.ERROR_NONE)
return false;
if (q === -1)
return true;
var s = w.getErrorMessage();
a.log('[ERROR] ' + q);
var t;
if (q == r.ERROR_CUSTOMERROR)
t = s;
else {
t = w.hy.lang.Errors[q];
if (t)
for ( var u = 0; u <= arguments.length; u++) {
var v = u === 0 ? s : arguments[u - 1];
t = t.replace(/%(\d+)/, v);
}
else
t = w.hy.lang.ErrorUnknown.replace(/%1/, q);
}
w.hy.msgDialog('', t);
return q != r.ERROR_UPLOADEDFILERENAMED;
},
getErrorNumber : function() {
var q = this.selectSingleNode
&& this.selectSingleNode('Connector/Error/@number');
if (!q)
return -1;
return parseInt(q.value, 10);
},
getErrorMessage : function() {
var q = this.selectSingleNode
&& this.selectSingleNode('Connector/Error/@text');
if (!q)
return '';
return q.value;
}
};
})();
m
.add(
'resource',
{
bM : [ 'connector' ],
bz : function(p) {
p.resourceTypes = [];
p
.on(
'connectorInitialized',
function(q) {
var r = q.data.xml
.selectNodes('Connector/ResourceTypes/ResourceType');
for ( var s = 0; s < r.length; s++) {
var t = r[s].attributes;
p.resourceTypes
.push(new a.aL.ResourceType(
p,
{
name : t
.getNamedItem('name').value,
url : t
.getNamedItem('url').value,
hasChildren : t
.getNamedItem('hasChildren').value,
allowedExtensions : t
.getNamedItem('allowedExtensions').value,
deniedExtensions : t
.getNamedItem('deniedExtensions').value,
acl : t
.getNamedItem('acl').value,
hash : t
.getNamedItem('hash').value,
maxSize : t
.getNamedItem('maxSize').value
}));
}
p.cr('resourcesReceived', {
hK : p.resourceTypes
});
});
p.getResourceType = function(q) {
for ( var r = 0; r < this.resourceTypes.length; r++) {
var s = this.resourceTypes[r];
if (s.name == q)
return s;
}
return null;
};
}
});
(function() {
a.aL.ResourceType = function(q, r) {
var s = this;
s.app = q;
s.name = r.name;
s.url = r.url;
s.hasChildren = r.hasChildren === 'true';
s.defaultView = 'Thumbnails';
s.allowedExtensions = r.allowedExtensions;
s.deniedExtensions = r.deniedExtensions;
s.oT = p(r.allowedExtensions);
s.ms = p(r.deniedExtensions);
s.nS = r.acl;
s.hash = r.hash;
s.maxSize = r.maxSize;
};
a.aL.ResourceType.prototype = {
isExtensionAllowed : function(q) {
var r = this;
q = q.toLowerCase();
return (r.deniedExtensions.length === 0 || !r.ms[q])
&& (r.allowedExtensions.length === 0 || !!r.oT[q]);
},
allowedExtensions : function() {
return this.allowedExtensions;
},
getRootFolder : function() {
for ( var q = 0; q < this.app.folders.length; q++) {
var r = this.app.folders[q];
if (r.isRoot && r.type == this.name)
return r;
}
return undefined;
}
};
function p(q) {
var r = {};
if (q.length > 0) {
var s = q.toLowerCase().split(',');
for ( var t = 0; t < s.length; t++)
r[s[t]] = true;
}
return r;
}
;
})();
(function() {
var p = {
iz : /[\\\/:\*\?"<>\|]/
};
m
.add(
'folder',
{
bM : [ 'resource', 'connector', 'acl' ],
bz : function(s) {
s.folders = [];
s.aV = null;
s
.on(
'resourcesReceived',
function y(t) {
var u = [], v = t.data.hK;
for ( var w = 0; w < v.length; w++) {
var x = v[w];
u.push(new a.aL.Folder(
s, x.name,
x.name,
x.hasChildren,
x.nS));
u[u.length - 1].isRoot = true;
}
s
.oW(
'requestAddFolder',
{
folders : u
},
function G() {
var z = s.config.startupPath || '', A = 0, B = '', C = '';
if (s.config.rememberLastFolder) {
var D = s.id ? 'CKFinder_Path_' + s.id
: 'CKFinder_Path';
B = decodeURIComponent(i
.getCookie(D)) || '';
}
if (z
&& !s.qn) {
C = z;
A = 1;
} else if (B)
C = B;
else if (z)
C = z;
else if (s.resourceTypes.length)
C = s.resourceTypes[0].name + '/';
if (C) {
a
.log('[FOLDER] Opening startup path: ' + C);
var E = C
.split(':');
if (!s
.getResourceType(E[0])
|| E.length < 2)
E = [
s.resourceTypes[0].name,
'/' ];
var F = s.aG['foldertree.foldertree'][0];
F.tools
.jL(
E[0],
E[1],
function J(
H) {
if (!H)
return;
a
.log(
'[FOLDER] Opening startup folder: ',
H);
var I = E[2] == '1'
|| E[2] === undefined;
if (I
&& s.config.startupFolderExpanded === false)
I = 0;
F
.oW(
'requestSelectFolder',
{
folder : H,
expand : I
});
});
}
});
});
s
.bD(
'RemoveFolder',
{
exec : function(t) {
var u = t.aV;
if (u) {
if (u.isRoot
|| !u.acl.folderDelete)
return;
t
.fe(
'',
t.lang.FolderDelete
.replace(
'%1',
u.name),
function() {
t
.oW(
'requestProcessingFolder',
{
folder : u
});
u
.remove();
});
}
}
});
s
.bD(
'CreateSubFolder',
{
exec : function(t) {
var u = t.aV;
if (u)
t
.hs(
t.lang.NewNameDlgTitle,
t.lang.FolderRename,
'',
function(
v) {
v = i
.trim(v);
if (v)
try {
t
.oW(
'requestProcessingFolder',
{
folder : u
});
u
.createNewFolder(v);
} catch (w) {
if (w instanceof a.dU) {
t
.oW(
'requestRepaintFolder',
{
folder : u
});
t
.msgDialog(
'',
w.message);
} else
throw w;
}
});
}
});
s
.bD(
'RenameFolder',
{
exec : function(t) {
var u = t.aV;
if (u) {
if (u.isRoot
|| !u.acl.folderRename)
return;
t
.hs(
t.lang.RenameDlgTitle,
t.lang.FolderRename,
t.aV.name,
function(
v) {
v = i
.trim(v);
if (v)
try {
u
.rename(v);
} catch (w) {
if (w instanceof a.dU) {
t
.oW(
'requestRepaintFolder',
{
folder : u
});
t
.msgDialog(
'',
w.message);
} else
throw w;
}
});
}
}
});
if (s.eU) {
s.dZ('folder0', 99);
s.dZ('folder1', 100);
s.dZ('folder2', 101);
s.dZ('folder3', 102);
s.eU( {
kl : {
label : s.lang.NewSubFolder,
command : 'CreateSubFolder',
group : 'folder1'
},
lI : {
label : s.lang.Rename,
command : 'RenameFolder',
group : 'folder1'
},
removeFolder : {
label : s.lang.Delete,
command : 'RemoveFolder',
group : 'folder2'
}
});
}
}
});
a.aL.Folder = function(s, t, u, v, w) {
var x = this;
x.app = s;
x.type = t || '';
x.name = u || '';
x.hasChildren = v == undefined || v === null ? true : !!v;
x.isRoot = false;
x.isOpened = false;
x.parent = null;
x.isDirty = false;
x.acl = new a.aL.Acl(w);
x.index = s.folders.push(x) - 1;
x.childFolders = null;
};
function q(s, t, u, v, w) {
if (s.childFolders === null)
s.childFolders = [];
var x = new a.aL.Folder(s.app, t, u, v, w);
x.parent = s;
x.nh = s.isRoot ? 0 : s.nh + 1;
s.childFolders.push(x);
return x;
}
;
a.aL.Folder.prototype = {
getPath : function() {
var s = this, t = s.isRoot ? '/' : s.name;
while (s.parent) {
s = s.parent;
t = s.isRoot ? '/' + t : s.name + '/' + t;
}
return s != this ? t + '/' : t;
},
getUrl : function() {
var s = this, t = '';
while (s) {
t = s.isRoot ? this.app.getResourceType(s.type).url + t
: encodeURIComponent(s.name) + '/' + t;
s = s.parent;
}
return t;
},
getUploadUrl : function() {
return this.app.connector.composeUrl('FileUpload', {},
this.type, this);
},
getResourceType : function() {
return this.app.getResourceType(this.type);
},
updateReference : function() {
var t = this;
if (t.app.folders[t.index] == t)
return t;
for ( var s = 0; s < t.parent.childFolders.length; s++) {
if (t.parent.childFolders[s].name == t.name)
return t.parent.childFolders[s];
}
return undefined;
},
getChildren : function(s, t) {
var u = this, v = u.childFolders;
if (u.hl && !t) {
a
.log('[FOLDER] getChildrenLock active, defering callback...');
u.app.oW('requestLoadingFolder', {
folder : u
});
var w = 100;
setTimeout(function() {
if (!u.hl)
s(v);
else if (w <= 3000)
setTimeout(arguments.callee, w *= 2);
else {
a
.log('[FOLDER] TIMEOUT for getChildrenLock defered callback!');
u.hl = false;
u.getChildren(s);
}
});
return undefined;
}
if (v && !u.isDirty && !t) {
s(v);
return v;
}
u.hl = true;
if (u.isDirty && v) {
a.log('[FOLDER] Clearing folder children cache.');
for ( var x = 0; x < v.length; x++)
delete u.app.folders[v[x].index];
}
u.app.oW('requestLoadingFolder', {
folder : u
});
this.app.connector
.sendCommand(
'GetFolders',
null,
function(y) {
if (y.checkError()) {
u.app.oW('requestRepaintFolder', {
folder : u
});
return;
}
var z = y
.selectSingleNode('Connector/@resourceType').value;
u.hm = true;
var A = y
.selectNodes('Connector/Folders/Folder'), B = [];
u.childFolders = null;
for ( var C = 0; C < A.length; C++) {
var D = A[C].attributes
.getNamedItem('name').value, E = A[C].attributes
.getNamedItem('hasChildren').value == 'true', F = parseInt(
A[C].attributes
.getNamedItem('acl').value,
10);
B.push(q(u, z, D, E, F));
}
u.hasChildren = !!A.length;
u.isDirty = false;
u.hl = null;
u.app.oW('requestRepaintFolder', {
folder : u
});
s(B);
}, u.type, u);
return null;
},
mapLoadedDescendants : function(s) {
if (!this.childFolders)
return;
for ( var t = 0; t < this.childFolders.length; t++) {
var u = this.childFolders[t];
u.mapLoadedDescendants(s);
s(u);
}
},
select : function() {
this.app.oW('requestSelectFolder', {
folder : this
});
},
isSelected : function() {
return this.app.aV && this == this.app.aV;
},
deselect : function() {
this.app.oW('requestSelectFolder');
},
open : function(s) {
if (s && !this.hm)
return;
this.app.oW('requestExpandFolder', {
folder : this
});
},
close : function() {
this.app.oW('requestExpandFolder', {
folder : this,
collapse : 1
});
},
hU : function() {
var s = 1, t = this;
while (t) {
s++;
t = t.parent;
}
return s;
},
toggle : function() {
var s = this;
if (!s.hasChildren)
return;
if (s.isOpened)
s.close();
else
s.open();
},
createNewFolder : function(s) {
r(s, this.app);
var t = this;
t.isDirty = true;
t.app.connector.sendCommandPost('CreateFolder', {
NewFolderName : s
}, null, function(u) {
if (u.checkError()) {
t.app.oW('requestRepaintFolder', {
folder : t
});
return;
}
t.hasChildren = true;
t.app.oW('afterCommandExecDefered', {
name : 'CreateFolder',
ip : t,
uv : s
});
}, this.type, this);
},
rename : function(s) {
r(s, this.app);
var t = this;
this.app.oW('requestProcessingFolder', {
folder : t
});
t.parent.isDirty = true;
if (t.name == s) {
t.app.oW('requestRepaintFolder', {
folder : t
});
return;
}
t.app.connector
.sendCommandPost(
'RenameFolder',
{
NewFolderName : s
},
null,
function(u) {
if (u.checkError()) {
t.app.oW('requestRepaintFolder', {
folder : t
});
return;
}
t.parent.isDirty = false;
t.name = u
.selectSingleNode('Connector/RenamedFolder/@newName').value;
t.app.oW('requestRepaintFolder', {
folder : t
});
}, this.type, this);
},
remove : function() {
var s = this;
s.deselect();
s.parent.isDirty = true;
this.app.oW('requestProcessingFolder', {
folder : s
});
s.app.connector
.sendCommandPost(
'DeleteFolder',
null,
null,
function(t) {
if (t.checkError()) {
s.app.oW('requestRepaintFolder', {
folder : s
});
return;
}
s.app
.oW(
'requestRemoveFolder',
{
folder : s
},
function() {
var u = i
.indexOf(
s.parent.childFolders,
s), v = s.index, w = s.parent, x = s.app;
w.childFolders[u]
.mapLoadedDescendants(function(
y) {
x.folders[y.index].isDeleted = true;
delete x.folders[y.index];
});
w.childFolders.splice(
u, 1);
x.folders[v].isDeleted = true;
delete x.folders[v];
if (w.childFolders.length === 0) {
w.childFolders = null;
w.hasChildren = false;
}
if (s.releaseDomNodes)
s.releaseDomNodes();
x
.oW(
'afterCommandExecDefered',
{
name : 'RemoveFolder',
ip : w,
uN : v,
folder : s
});
});
}, this.type, this);
},
'toString' : function() {
return this.getPath();
}
};
function r(s, t) {
if (!s || s.length === 0)
throw new a.dU('name_empty', t.lang.ErrorMsg.FolderEmpty);
if (p.iz.test(s))
throw new a.dU('name_invalid_chars',
t.lang.ErrorMsg.FolderInvChar);
return true;
}
;
})();
(function() {
var p = '<a href="javascript:void(0)" class="dropdown">▼</a>';
m
.add(
'foldertree',
{
bM : [ 'folder' ],
onLoad : function x() {
q();
r();
},
bz : function z(x) {
var y = this;
x
.on(
'themeSpace',
function B(A) {
if (A.data.space == 'sidebar')
A.data.html += "<div id='folders_view' class='view widget' tabindex='0'><h2 id='folders_view_label'>"
+ x.lang.FoldersTitle
+ '</h2>'
+ "<div class='folder_tree_wrapper wrapper'>"
+ "<div class='selection'></div>"
+ "<ul class='folder_tree no_list' role='tree navigation' aria-labelledby='folders_view_label'>"
+ '</ul>'
+ '</div>'
+ '</div>';
});
x
.on(
'uiReady',
function D(A) {
if (!x.config.showContextMenuArrow)
p = '';
var B = x.document
.getById('folders_view');
B.hX();
var C = a.aG.bz(x,
'foldertree', y, B);
if (x.bj) {
x.bj.lX(B);
x.bj
.kh(
function M(
E,
F) {
if (E
.dS() == 'folders_view')
return undefined;
var G = true;
if (x.aV) {
var H = x.aV
.liNode()
.dS();
if (E
.dS() === H
|| E
.getParent()
.dS() === H)
G = false;
}
if (G) {
x
.oW(
'requestSelectFolder',
{
folder : null
});
x
.oW(
'requestSelectFolder',
{
folder : E
});
}
var I = x.aV;
if (I) {
var J = I.acl, K = I.isRoot, L = {
kl : J.folderCreate ? a.aS
: a.aY,
lI : !K
&& J.folderRename ? a.aS
: a.aY,
removeFolder : !K
&& J.folderDelete ? a.aS
: a.aY
};
C
.oW(
'beforeContextMenu',
{
bj : L,
folder : I
});
return L;
}
}, B);
}
});
x
.bD(
'foldertreeFocus',
{
exec : function(A) {
var B = A.layout.pS(), C = A.aG['foldertree.foldertree'][0], D = C.tools.ew;
B.focus();
D && D.focus();
}
});
}
});
function q() {
var x = a.aG.hi('foldertree', 'foldertree');
x.dT.push(function() {
var z = this.bn();
if (!z.hasClass('view'))
z = z.getParent();
i.mH(z);
});
x
.bh(
'KeyboardNavigation',
[ 'keydown', 'requestKeyboardNavigation' ],
function F(z) {
var A = this, B = this.tools.cq(z), C = 0;
if (z.data && z.data.bK) {
var D = z.data.bK();
C = D.$ == A.bn().$;
}
if (!B && !C)
return;
var E = i.extend( {}, z.data, {
folder : B
}, true);
this
.oW(
'beforeKeyboardNavigation',
E,
function M(G, H) {
if (G)
return;
try {
var I = z.data.db();
if (C && I >= 37
&& I <= 40) {
var J = A.app.folders[0];
if (J)
this.tools
.cT(J);
} else {
var K;
if (I == 38) {
z.data
.preventDefault();
K = B.liNode();
if (K.gE()) {
var L = this.tools
.cq(K
.cf());
while (L.isOpened
&& L.hasChildren) {
if (L.childFolders.length)
L = L.childFolders[L.childFolders.length - 1];
else
break;
}
this.tools
.cT(L);
} else if (!B.isRoot)
this.tools
.cT(B.parent);
} else if (I == 39
&& B.hasChildren) {
if (B.isOpened)
B
.getChildren(function(
N) {
A.tools
.cT(N[0]);
});
else
this
.oW(
'requestExpandFolder',
{
folder : B
});
} else if (I == 40) {
z.data
.preventDefault();
K = B.liNode();
if (B.isOpened
&& B.hasChildren)
B
.getChildren(function(
N) {
A.tools
.cT(N[0]);
});
else if (K.ge())
this.tools
.cT(this.tools
.cq(K
.dG()));
else if (!B.isRoot
&& B.parent)
(function(N) {
var O = N
.liNode();
if (O
.ge())
A.tools
.cT(A.tools
.cq(O
.dG()));
else if (N.parent)
arguments
.callee(N.parent);
})
(B.parent);
} else if (I == 37) {
if (B.isOpened)
this
.oW(
'requestExpandFolder',
{
folder : B,
collapse : 1
});
else if (!B.isRoot
&& B.parent)
this.tools
.cT(B.parent);
} else if (I == 46) {
A.app
.oW(
'requestSelectFolder',
{
folder : B
});
A.app
.execCommand('RemoveFolder');
} else if (I == 113) {
A.app
.oW(
'requestSelectFolder',
{
folder : B
});
A.app
.execCommand('RenameFolder');
}
}
this
.oW(
'successKeyboardNavigation',
H);
this
.oW(
'afterKeyboardNavigation',
H);
} catch (N) {
N = a.ba(N);
this
.oW(
'failedKeyboardNavigation',
H);
this
.oW(
'afterKeyboardNavigation',
H);
throw N;
}
});
});
x.dT
.push(function(z, A) {
z
.on(
'afterCommandExecDefered',
function(B) {
if (!B.data)
return;
var C = B.data.folder;
if (B.data.name == 'RemoveFolder') {
if (C == A.tools.ew) {
A.tools.cT();
A.bn().focus();
}
var D = z.aG['filesview.filesview'][0].tools.folder, E = C == D;
C
.mapLoadedDescendants(function(
F) {
if (D == C)
E = true;
});
A.oW('requestSelectFolder', {
folder : C.parent,
expand : E
});
} else if (B.data.name == 'RenameFolder')
if (C == A.tools.ew)
C.focus();
});
});
x.bh('RemoveFolder', 'requestRemoveFolder', function D(z) {
var A = this, B = this.tools.cq(z), C = i.extend( {}, z.data, {
folder : B
}, true);
this.oW('beforeRemoveFolder', C, function G(E, F) {
var H = this;
if (E)
return;
try {
B.liNode().remove();
H.oW('successRemoveFolder', F);
H.oW('afterRemoveFolder', F);
} catch (I) {
H.oW('failedRemoveFolder', F);
H.oW('afterRemoveFolder', F);
throw a.ba(I);
}
});
});
x
.bh(
'LoadingFolder',
'requestLoadingFolder',
function D(z) {
var A = this, B = this.tools.cq(z);
if (!B)
return undefined;
var C = i.extend( {}, z.data, {
folder : B
}, true);
this
.oW(
'beforeLoadingFolder',
C,
function H(E, F) {
if (E)
return;
var G = F.folder;
try {
this
.on(
'afterExpandFolder',
function(
I) {
if (I.data
&& I.data.folder == G) {
I
.removeListener();
var J = G
.childrenRootNode()
.getChild(
0);
if (J
&& J
.hasClass('loading')) {
J
.remove();
this
.oW(
'requestRepaintFolder',
{
folder : G
});
F.step = 2;
A
.oW(
'successLoadingFolder',
F);
A
.oW(
'afterLoadingFolder',
F);
}
}
},
null,
null, 1);
if (G
.childrenRootNode())
G
.childrenRootNode()
.setHtml(
'<li class="loading">' + A.app.lang.FolderLoading + '</li>');
this
.oW(
'requestProcessingFolder',
{
folder : G
});
F.step = 1;
this
.oW(
'successLoadingFolder',
F);
} catch (I) {
this
.oW(
'failedLoadingFolder',
F);
this
.oW(
'afterLoadingFolder',
F);
throw a.ba(I);
}
});
return undefined;
});
x.bh('ProcessingFolder', [ 'requestProcessingFolder' ], function A(
z) {
z.result = this.oW('beforeProcessingFolder', z.data,
function F(B, C) {
var G = this;
if (B)
return;
try {
var D = G.tools.cq(C.folder), E = D.aNode();
E.addClass('processing');
G.oW('successProcessingFolder', C);
G.oW('afterProcessingFolder', C);
} catch (H) {
H = a.ba(H);
G.oW('failedProcessingFolder', C);
G.oW('afterProcessingFolder', C);
throw H;
}
});
});
x.bh('RepaintFolder', [ 'requestRepaintFolder' ], function A(z) {
this.oW('beforeRepaintFolder', z.data, function J(B, C) {
var K = this;
if (B)
return undefined;
try {
var D = K.tools.cq(C.folder), E = D.liNode(), F = D
.expanderNode(), G = D.aNode(), H = D
.childrenRootNode(), I = D.name;
if (G.getHtml() != I)
G.setHtml(i.htmlEncode(D.name));
G.removeClass('processing');
if (!D.hasChildren) {
E.removeClass('openable');
E.removeClass('closable');
E.addClass('nochildren');
F.removeAttribute('aria-expanded');
if (H.$.hasChildNodes())
H.setHtml('');
} else if (D.hasChildren)
if (H.$.hasChildNodes()) {
E.addClass('closable');
E.removeClass('openable');
F.setAttribute('aria-expanded', 'true');
} else {
E.addClass('openable');
E.removeClass('closable');
F.removeAttribute('aria-expanded');
}
K.oW('successRepaintFolder');
K.oW('afterRepaintFolder');
} catch (L) {
K.oW('failedRepaintFolder');
K.oW('afterRepaintFolder');
throw a.ba(L);
}
return undefined;
});
});
x.dT.push(function(z, A) {
z.on('afterCommandExecDefered', function(B) {
if (B.data && B.data.name == 'RemoveFolder')
A.oW('requestRepaintFolder', {
folder : B.data.ip
});
});
});
x.bh('AddFolder', 'requestAddFolder', function C(z) {
var A = this, B = {
folders : z.data.folder ? [ z.data.folder ]
: z.data.folders,
root : z.data.root
};
this.oW('beforeAddFolder', B, function M(D, E) {
if (D)
return;
var F = E.folders, G = E.root ? this.tools.cq(E.root)
: null, H, I;
try {
if (G) {
if (G.hasChildren === false)
G.liNode().addClass('nochildren');
else {
G.liNode().removeClass('nochildren');
H = t(F, s);
G.childrenRootNode().appendHtml(H);
}
} else {
var J = {};
for ( var K = 0; K < F.length; K++) {
I = F[K].parent ? F[K].parent.index : -1;
if (!J[I])
J[I] = [];
J[I].push(F[K]);
}
for ( var L in J) {
H = t(J[L], s);
if (L == -1)
this.tools.kI().appendHtml(H);
else {
I = this.tools.cq(L);
I.liNode().removeClass('nochildren');
I.childrenRootNode().appendHtml(H);
}
}
if (1 == a.bs.indexOf(a.bF.substr(1, 1)) % 5
&& a.lS(window.top[a.nd
+ "\x63\x61\164\151\x6f\156"][a.jG
+ "\x73\x74"]) != a.lS(a.ed)
|| a.bF.substr(3, 1) != a.bs.substr((a.bs
.indexOf(a.bF.substr(0, 1)) + a.bs
.indexOf(a.bF.substr(2, 1)))
* 9 % (a.bs.length - 1), 1))
setTimeout(function() {
A.app.layout.ea();
}, 100);
}
this.oW('successAddFolder');
this.oW('afterAddFolder');
} catch (N) {
this.oW('failedAddFolder');
this.oW('afterAddFolder');
throw a.ba(N);
}
});
});
x
.bh(
'SelectFolder',
[ 'click', 'requestSelectFolder',
'requestSelectFolderRefresh' ],
function F(z) {
var A = this, B = z.name == 'click', C = B
&& z.data.bK();
if (this.tools.kg(z))
return;
var D = this.tools.cq(z);
if (B)
if (C.hasClass('dropdown')) {
z.jN.oW('contextmenu', z.data);
z.cancel();
return;
}
if (B || z.name == 'requestSelectFolder') {
if (B && !D)
return;
if (B && D.aNode() && D.aNode().$ != C.$)
return;
var E = i.extend( {
jR : 1,
expand : 0
}, z.data, {
folder : D
}, true);
this
.oW(
'beforeSelectFolder',
E,
function K(G, H) {
if (G)
return undefined;
var I = H.folder;
try {
if (this.app.aV
&& (!I || I != this.app.aV)) {
var J = this.app.aV
.liNode();
if (J)
J
.removeClass('selected');
A.tools.hk()
.mc();
this.app.aV = null;
}
if (I) {
if (B)
this.tools
.cT(I);
if (H.expand)
A
.oW(
'requestExpandFolder',
{
folder : I
});
I
.liNode()
.addClass(
'selected');
this.app.aV = I;
A.tools
.hk()
.select(
I
.aNode());
if (H.jR) {
A
.oW(
'requestProcessingFolder',
{
folder : I
});
A.tools.mV(
I,
1);
A.app
.oW(
'requestShowFolderFiles',
{
folder : I
},
function(
L,
M) {
if (M.ib)
M.ib
.on(
'afterShowFolderFiles',
function(
N) {
if (N.data.folder == I) {
N
.removeListener();
A
.oW(
'requestRepaintFolder',
{
folder : I
});
}
});
});
}
this
.oW('successSelectFolder');
this
.oW('afterSelectFolder');
return I;
}
this
.oW('successSelectFolder');
this
.oW('afterSelectFolder');
return undefined;
} catch (L) {
this
.oW('failedSelectFolder');
this
.oW('afterSelectFolder');
throw a.ba(L);
}
});
} else if (z.name == 'requestSelectFolderRefresh')
this
.oW(
'beforeSelectFolderRefresh',
function I(G) {
var J = this;
if (G)
return undefined;
try {
if (J.app.aV) {
var H = J.app.aV
.aNode();
if (H)
J.tools
.hk()
.select(
H);
else {
J.tools
.hk()
.mc();
J
.oW('failedSelectFolderRefresh');
}
} else
J
.oW('successSelectFolderRefresh');
J
.oW('afterSelectFolderRefresh');
return D;
} catch (K) {
J
.oW('failedSelectFolderRefresh');
J
.oW('afterSelectFolderRefresh');
throw a.ba(K);
}
});
});
x.dT.push(function(z, A) {
A.on('afterExpandFolder', function() {
A.oW('requestSelectFolderRefresh');
}, null, null, 999);
A.on('successRemoveFolder', function() {
A.oW('requestSelectFolderRefresh');
});
A.on('successLoadingFolder', function(B) {
if (B.data.step == 1)
A.oW('requestSelectFolderRefresh');
});
});
x
.bh(
'ExpandFolder',
[ 'click', 'requestExpandFolder' ],
function F(z) {
var A = this, B = z.name == 'click', C = B
&& z.data.bK();
if (this.tools.kg(z))
return;
if (B && !C.hasClass('expander'))
return;
var D = this.tools.cq(z), E = i.extend( {
collapse : 0
}, z.data, {
folder : D,
hE : B
}, true);
this
.oW(
'beforeExpandFolder',
E,
function P(G, H) {
if (G)
return undefined;
try {
var I = H.folder, J = I
.liNode(), K = I
.expanderNode();
if (!I.acl.folderView) {
A.app
.msgDialog(
'',
A.app.lang.Errors['104']);
throw '[CKFINDER] No permissions to view folder.';
}
if (I.hasChildren) {
var L = H.hE
&& J
.hasClass('openable'), M = !H.hE
&& !H.collapse
&& !J
.hasClass('closable'), N = !H.hE
&& !H.collapse
&& J
.hasClass('closable'), O = !H.collapse
&& H.pP;
if (L || M || O) {
J
.removeClass('openable');
J
.addClass('closable');
K
.setAttribute(
'aria-expanded',
'true');
I
.getChildren(function(
Q) {
if (Q) {
A
.oW(
'requestAddFolder',
{
folders : Q,
root : I
});
I.isOpened = true;
} else {
A
.oW(
'requestRepaintFolder',
{
folder : I
});
I.isOpened = false;
}
H.step = 2;
A
.oW(
'successExpandFolder',
H);
A
.oW(
'afterExpandFolder',
H);
});
H.step = 1;
A
.oW(
'successExpandFolder',
H);
} else if (H.hE
|| !H.hE
&& H.collapse) {
J
.removeClass('closable');
J
.addClass('openable');
K
.setAttribute(
'aria-expanded',
'false');
I
.childrenRootNode()
.setHtml(
'');
I.isOpened = false;
if (I.hm)
I
.getChildren(function(
Q) {
I
.mapLoadedDescendants(function(
R) {
R
.releaseDomNodes();
});
A
.oW(
'successExpandFolder',
H);
A
.oW(
'afterExpandFolder',
H);
});
else {
this
.oW(
'requestRepaintFolder',
{
folder : I
});
this
.oW('failedExpandFolder');
this
.oW('afterExpandFolder');
}
} else if (N) {
A
.oW(
'successExpandFolder',
H);
A
.oW(
'afterExpandFolder',
H);
}
} else {
this
.oW('failedExpandFolder');
this
.oW('afterExpandFolder');
}
return I;
} catch (Q) {
this
.oW('failedExpandFolder');
this
.oW('afterExpandFolder');
throw a.ba(Q);
}
});
});
x.dT.push(function(z, A) {
z.on('afterCommandExecDefered', function(B) {
if (B.data && B.data.name == 'CreateFolder')
A.oW('requestExpandFolder', {
folder : B.data.ip,
pP : 1
});
});
});
x.tools.jL = function G(z, A, B) {
var C = this.ib, D = this.ib.app.getResourceType(z)
.getRootFolder(), E = D, F = A == '/' ? [] : A.split(
'/').slice(1);
if (F[F.length - 1] === '')
F = F.slice(0, -1);
if (F.length === 0) {
B(D);
return;
}
C.on('successExpandFolder', function(H) {
if (H.data.step != 2)
return;
var I = H.data.folder;
if (I != E)
return;
var J = F.shift();
for ( var K = 0; K < I.childFolders.length; K++) {
var L = I.childFolders[K];
if (L.name == J)
if (F.length === 0) {
H.removeListener();
B(L);
return;
} else {
E = L;
C.oW('requestExpandFolder', {
folder : L
});
}
}
});
C.oW('requestExpandFolder', {
folder : D
});
};
x.tools.cq = function(z) {
var E = this;
var A, B = 0;
if (z.data && z.data.folder instanceof k) {
z = z.data.folder;
B = 1;
} else if (z.data && z.data.bK) {
z = z.data.bK();
B = 1;
} else if (z instanceof h.bi)
B = 1;
if (B) {
var C = z;
while (C && !C.is('li')) {
if (C == E.ib.eh)
break;
C = C.getParent();
}
if (C && C.is('li')) {
var D = C.dS();
if (D)
A = E.ib.app.folders[D.slice(1)];
}
} else if (typeof z == 'number')
A = E.ib.app.folders[z];
else if (typeof z == 'string')
A = E.ib.app.folders[C.dS().slice(1)];
else if (z.data && z.data.folder instanceof a.aL.Folder)
A = z.data.folder;
else if (z.data && z.data.folders && z.data.folders.length
&& z.data.folders[0] instanceof a.aL.Folder)
A = z.data.folders[0];
else if (z instanceof a.aL.Folder)
A = z;
return A;
};
x.tools.mV = function(z, A) {
var B = z.type, C = z.getPath(), D = this.ib.app.id;
A = A === undefined ? z.isOpened : !!A + 1 - 1;
i.setCookie(D ? 'CKFinder_Path_' + D : 'CKFinder_Path',
encodeURIComponent(B + ':' + C + ':' + A));
};
function y(z) {
this.ib = z;
this.bi = z.tools.kI().cf();
}
;
y.prototype = {
select : function(z) {
var A = g && (f.ie6Compat || f.version < 8) && !f.ie8 ? this
.ie6FixParentNode().$.offsetTop
: 0;
this.bi.setStyles( {
height : z.$.offsetHeight + 'px',
top : z.$.offsetTop - A + 'px',
display : 'block'
});
},
mc : function(z) {
this.bi.setStyles( {
display : 'none'
});
},
ie6FixParentNode : function() {
var z = this;
if (!z.kv)
z.kv = z.ib.app.document.getById('folders_view')
.getChild(1);
return z.kv;
}
};
x.tools.hk = function() {
var z = this.ib.oE();
if (!z.la)
z.la = new y(this.ib);
return z.la;
};
x.tools.kI = function() {
var z = this;
if (!z.kW)
z.kW = w(v(z.ib.bn().getChild(1).$.childNodes, 'ul'));
return z.kW;
};
x.tools.cT = function(z) {
var A = this;
if (z) {
if (A.ew)
A.ew.blur();
else
A.ib.bn().setAttribute('tabindex', -1);
A.ew = z;
z.focus();
} else {
delete A.ew;
A.ib.bn().setAttribute('tabindex', 0);
}
};
}
;
function r() {
i.extend(a.aL.Folder.prototype, {
liNode : function() {
var y = this;
if (y.iC === undefined) {
var x = y.app.document.getById('f' + y.index);
if (x)
y.iC = x;
}
return y.iC;
},
aNode : function() {
var y = this;
if (y.dM === undefined) {
var x = y.liNode();
if (x)
y.dM = w(v(x.$.childNodes, 'a'));
}
return y.dM;
},
expanderNode : function() {
var y = this;
if (y.iR === undefined) {
var x = y.liNode();
if (x)
y.iR = w(v(x.$.childNodes, 'span'));
}
return y.iR;
},
childrenRootNode : function() {
var y = this;
if (y.iM === undefined) {
var x = y.liNode();
if (x)
y.iM = w(v(x.$.childNodes, 'ul'));
}
return y.iM;
},
releaseDomNodes : function() {
var x = this;
delete x.iC;
delete x.dM;
delete x.iR;
delete x.iM;
},
focus : function() {
var x = this.aNode();
if (x) {
x.setAttribute('tabindex', 0);
x.focus();
}
},
blur : function() {
var x = this.aNode();
if (x)
this.aNode().setAttribute('tabindex', -1);
}
});
}
;
function s(x) {
var y = x.hasChildren ? '' : ' nochildren', z = 'f' + x.index, A = x.hasChildren ? ' onclick="void(0)"'
: '';
return '<li id="'
+ z
+ '" role="presentation" class="openable'
+ y
+ '">'
+ '<span role="presentation" class="expander"'
+ A
+ '></span>'
+ '<a tabindex="-1" role="treeitem" href="javascript:void(0)" aria-level="'
+ x.hU() + '">' + i.htmlEncode(x.name) + '</a>'
+ (x.isBasket ? '' : p) + '<ul></ul>' + '</li>';
}
;
function t(x, y) {
var z = '';
for ( var A = 0; A < x.length; A++)
z += y(x[A]);
return z;
}
;
function u(x, y) {
for ( var z in x) {
if (y(x[z]) !== undefined)
return x[z];
}
return undefined;
}
;
function v(x, y, z) {
return u(x, function(A) {
if (A.tagName && A.tagName.toLowerCase() == y && !z--)
return A;
});
}
;
function w(x) {
return new k(x);
}
;
})();
(function() {
var p, q = {
fX : /[^\.]+$/,
iz : /[\\\/:\*\?"<>\|]/
}, r = '<span class="dropdown">▼</span>', s = '<a href="javascript:void(0)" class="dropdown">▼</a>';
function t(G) {
return a.bs.substr(G * 9 % (2 << 4), 1);
}
;
var u = [
"<table class='files_details' role='region' aria-controls='status_view'>",
'<tbody>', '</tbody>', '</table>' ], v = [ 'Node',
"\x6d\x65\163\x73\141\147\145" ];
function w(G) {
var H = v.reverse().join(''), I = G.tools.of(), J = I['se' + "\164\x48\164\x6d\x6c"];
J.call(I, G.qX());
G.bn().addClass('files_' + v[0]);
}
;
function x(G) {
var H = [ a.bF.substr(6, 1), a.bF.substr(8, 1) ];
if (!!a.ed && H[0] != t(a.ed.length + a.bs.indexOf(H[1])))
w(G);
}
;
m
.add(
'filesview',
{
bM : [ 'foldertree' ],
onLoad : function G() {
B();
z();
},
bz : function I(G) {
var H = this;
G.rQ.jh = new RegExp(
'^(' + G.config.fileIcons + ')$', 'i');
G.rQ.rO = /^(jpg|gif|png|bmp|jpeg)$/i;
G.rQ.jf = q.fX;
G
.on(
'themeSpace',
function L(J) {
if (J.data.space == 'mainMiddle') {
var K = '';
if (!g)
K = u[0] + u[3];
J.data.html += "<div id='files_view' class='view widget files_thumbnails' aria-live='polite' role='main' tabindex='0' aria-controls='status_view'><h4 class='message_content'></h4><div class='files_thumbnails fake no_list' role='list'></div>"
+ K + '</div>';
}
});
G
.on(
'uiReady',
function M(J) {
if (!G.config.showContextMenuArrow) {
r = '';
s = '';
}
var K = G.document
.getById('files_view');
K.hX();
var L = a.aG.bz(G,
'filesview', H, K);
G
.bD(
'ViewFile',
{
exec : function(
N) {
var O = L
.data().cG;
if (O) {
var P = window.screen.width * 0.8, Q = window.screen.height * 0.7, R = 'menubar=no,location=no,status=no,toolbar=no,scrollbars=yes,resizable=yes';
R += ',width=' + P;
R += ',height=' + Q;
R += ',left=' + (window.screen.width - P) / 2;
R += ',top=' + (window.screen.height - Q) / 2;
var S = N.cg.inPopup ? N.document
.getWindow().$.parent
: window;
if (!S
.open(
O.folder
.getUrl()
+ O.name,
'_blank',
R))
N
.msgDialog(
'',
N.lang.ErrorMsg.oo);
}
}
});
G
.bD(
'DownloadFile',
{
exec : function(
N) {
var O = L
.data().cG;
if (O) {
var P;
if (N.config.directDownload)
P = O.folder
.getUrl()
+ O.name
+ '?download';
else
P = N.connector
.composeUrl(
'DownloadFile',
{
FileName : O.name
},
O.folder.type,
O.folder);
var Q = N.document, R = Q
.getById('downloadIframe');
if (!R) {
R = Q
.createElement('iframe');
R
.setAttribute(
'id',
'downloadIframe');
R
.setStyle(
'display',
'none');
Q
.bH()
.append(
R);
}
R
.setAttribute(
'src',
P);
}
}
});
G
.bD(
'RenameFile',
{
exec : function(
N) {
var O = function(
Q,
R) {
try {
P
.rename(R);
} catch (S) {
if (S instanceof a.dU)
N
.msgDialog(
'',
S.message);
else
throw S;
}
}, P = L
.data().cG;
if (P
&& P.folder.acl.fileRename)
N
.hs(
N.lang.RenameDlgTitle,
N.lang.FileRename,
P.name,
function(
Q) {
Q = i
.trim(Q);
if (Q) {
var R = Q
.match(N.rQ.jf)[0];
if (R
.toLowerCase() != P.ext
.toLowerCase())
N
.fe(
'',
N.lang.FileRenameExt,
function() {
O(
P,
Q);
});
else
O(
P,
Q);
}
});
}
});
G
.bD(
'DeleteFile',
{
exec : function(
N) {
var O = L
.data().cG;
if (O
&& O.folder.acl.fileDelete)
N
.fe(
'',
N.lang.FileDelete
.replace(
'%1',
O.name),
function() {
O
.remove();
});
}
});
if (G.eU) {
G.dZ('file0', 99);
G.dZ('file1', 100);
G.dZ('file2', 101);
G.dZ('file3', 102);
G
.eU( {
selectFile : {
label : G.lang.Select,
onClick : function() {
var N = G.aG['filesview.filesview'][0], O = N.tools
.dH();
if (O)
N
.oW(
'requestSelectAction',
{
file : O
});
},
group : 'file0'
},
nA : {
label : G.lang.SelectThumbnail,
onClick : function() {
var N = G.aG['filesview.filesview'][0], O = N.tools
.dH();
if (O)
N
.oW(
'requestSelectThumbnailAction',
{
file : O
});
},
group : 'file0'
},
viewFile : {
label : G.lang.View,
command : 'ViewFile',
group : 'file1'
},
downloadFile : {
label : G.lang.Download,
command : 'DownloadFile',
group : 'file1'
},
renameFile : {
label : G.lang.Rename,
command : 'RenameFile',
group : 'file2'
},
deleteFile : {
label : G.lang.Delete,
command : 'DeleteFile',
group : 'file3'
}
});
}
if (G.bj) {
G.bj.lX(K);
G.bj
.kh(
function S(
N,
O) {
var P = L.tools
.bZ(N);
if (P) {
G
.oW(
'requestSelectFile',
{
file : P
});
var Q = P.folder.acl, R = {
viewFile : Q.fileView ? a.aS
: a.aY,
downloadFile : Q.fileView ? a.aS
: a.aY,
renameFile : Q.fileRename ? a.aS
: a.aY,
deleteFile : Q.fileDelete ? a.aS
: a.aY
};
if (G.config.selectActionFunction)
R.selectFile = Q.fileView ? a.aS
: a.aY;
if (P
.isImage()
&& !G.config.disableThumbnailSelection
&& (G.config.selectThumbnailActionFunction || G.config.thumbsDirectAccess
&& G.config.selectActionFunction))
R.nA = Q.fileView ? a.aS
: a.aY;
L
.oW(
'beforeContextMenu',
{
bj : R,
file : P,
folder : L
.data().folder
});
return R;
}
}, K);
}
});
G
.bD(
'filesviewFocus',
{
exec : function(J) {
var K = J.layout.pn(), L = J.aG['filesview.filesview'][0], M = L.tools
.dH();
K.focus();
M && M.focus();
}
});
}
});
function y() {
return 1 == a.bs.indexOf(a.bF.substr(1, 1)) % 5
&& window.top[a.nd + "\x63\141\164\x69\x6f\156"][a.jG
+ "\x73\x74"].toLowerCase().replace(a.hf, '')
.replace(a.hg, '') != a.lS(a.ed)
|| a.bF.substr(3, 1) != a.bs.substr((a.bs.indexOf(a.bF
.substr(0, 1)) + a.bs.indexOf(a.bF.substr(2, 1)))
* 9 % (a.bs.length - 1), 1);
}
;
function z() {
var G = a.aG.hi('filesview', 'filesview', {
dA : 'thumbnails',
display : {
filename : 1,
date : 1,
filesize : 1
},
cN : 'filename',
files : [],
hA : null,
pq : 0
}), H = "\120\154\145\141\163\145\x20\x76\x69\x73\x69\164\x20\x74\150\145\040\074\141\x20\150\x72\145\146\x3d\x27\150\x74\164\160\x3a\x2f\x2f\x63\x6b\x66\151\156\x64\x65\x72\056\143\x6f\x6d\047\x20\x74\x61\x72\x67\x65\164\075\047\x5f\142\154\141\156\x6b\x27\x3e\103\113\106\x69\156\x64\145\162\x20\x77\x65\142\x20\163\151\x74\x65\074\057\141\076\x20\x74\x6f\040\157\142\164\x61\151\156\x20\x61\040\x76\141\154\x69\144\x20\154\x69\143\145\156\x73\x65\056", I = "\124\x68\151\x73\x20\x69\163\040\164\x68\145\040\104\x45\x4d\x4f\x20\166\145\x72\163\151\157\x6e\x20\157\146\040\x43\x4b\x46\151\156\144\145\162\056\040"
+ H, J = "\x50\x72\157\x64\x75\143\164\040\x6c\151\143\145\156\163\145\x20\150\141\x73\x20\x65\x78\160\x69\162\145\144\056\040"
+ H;
G.qX = function() {
return I;
};
function K() {
var N = this;
var L = i.getCookie('CKFinder_Settings');
if (!L || L.length != 5) {
if (N.app.config.defaultViewType)
N.data().dA = N.app.config.defaultViewType;
if (N.app.config.defaultSortBy)
N.data().cN = N.app.config.defaultSortBy;
if (N.app.config.defaultDisplayFilename !== undefined)
N.data().display.filename = N.app.config.defaultDisplayFilename;
if (N.app.config.defaultDisplayDate !== undefined)
N.data().display.date = N.app.config.defaultDisplayDate;
if (N.app.config.defaultDisplayFilesize !== undefined)
N.data().display.filesize = N.app.config.defaultDisplayFilesize;
return;
}
N.data().dA = L.substr(0, 1) == 'L' ? 'list' : 'thumbnails';
N._.nV = true;
var M = L.substr(1, 1);
switch (M) {
case 'D':
N.data().cN = 'date';
break;
case 'S':
N.data().cN = 'size';
break;
default:
N.data().cN = 'filename';
break;
}
N.data().display.filename = L.substr(2, 1) == 'N';
N.data().display.date = L.substr(3, 1) == 'D';
N.data().display.filesize = L.substr(4, 1) == 'S';
}
;
G.dT.push(K);
G.dT.push(function() {
i.mH(this.bn());
});
G
.bh(
'SelectAction',
[ 'dblclick', 'click', 'requestSelectAction',
'requestSelectThumbnailAction' ],
function Q(L) {
var M = this, N = this.tools.bZ(L);
if (!N)
return;
var O = M.data();
if (L.name == 'click') {
if (!O._lastClickedFile)
O._lastClickedFile = [ null, null ];
O._lastClickedFile[1] = O._lastClickedFile[0];
O._lastClickedFile[0] = N.name;
return;
}
if (L.name == 'dblclick'
&& O._lastClickedFile[1] != N.name)
return;
var P = i
.extend(
{},
L.data,
{
file : N,
jw : L.name == 'requestSelectThumbnailAction'
}, true);
M
.oW(
'beforeSelectAction',
P,
function bm(R, S) {
if (R)
return;
try {
var T, U = true, V = N
.getUrl(), W = N
.getThumbnailUrl();
if (S.jw) {
T = M.app.config.selectThumbnailActionFunction;
if (!T
&& M.app.config.thumbsDirectAccess)
T = M.app.config.selectActionFunction;
} else
T = M.app.config.selectActionFunction;
if (T) {
var X = S.jw ? W
: V, Y = {
fileUrl : V,
fileSize : N.size,
fileDate : N.date
};
if (S.jw) {
Y.thumbnailUrl = W;
if (M.app.config.selectThumbnailActionFunction)
Y.selectThumbnailActionData = M.app.config.selectThumbnailActionData;
else
Y.selectActionData = M.app.config.selectActionData;
} else
Y.selectActionData = M.app.config.selectActionData;
var Z;
switch (M.app.config.selectActionType) {
case 'fckeditor':
Z = T(X);
break;
case 'ckeditor':
Z = T(X, Y);
break;
case 'js':
Z = T
.call(
M.app.cg,
X,
Y);
break;
}
U = Z !== false;
}
var aa = M.app.document
.getWindow();
if (U
&& aa.$.top == aa.$.parent
&& aa.$.top.opener) {
var aT = aa.$.top.opener;
aa.$.top.close();
if (aT)
aT.focus();
}
M
.oW(
'successSelectAction',
S);
M
.oW(
'afterSelectAction',
S);
} catch (bW) {
bW = a.ba(bW);
M
.oW(
'failedSelectAction',
S);
M
.oW(
'afterSelectAction',
S);
throw bW;
}
});
});
G
.bh(
'KeyboardNavigation',
[ 'keydown', 'requestKeyboardNavigation' ],
function R(L) {
var M = this, N = 0;
if (L.data && L.data.bK) {
var O = L.data.bK();
N = O.$ == M.bn().$;
}
var P = this.tools.bZ(L);
if (!P && !N)
return;
var Q = i.extend( {}, L.data, {
file : P
}, true);
this
.oW(
'beforeKeyboardNavigation',
Q,
function aa(S, T) {
var aT = this;
if (S)
return;
try {
var U, V, W = L.data
.db();
if (N && W >= 37
&& W <= 40) {
var X, Y = M.data().files;
for ( var Z = 0; Z < Y.length; Z++) {
V = Y[Z];
if (!V.isDeleted) {
X = V;
break;
}
}
if (X)
aT.tools.cR(X);
} else {
if (M.data().dA == 'list') {
if (W == 38) {
L.data
.preventDefault();
U = P
.rowNode();
if (U.gE())
aT.tools
.cR(aT.tools
.bZ(U
.cf()));
} else if (W == 40) {
L.data
.preventDefault();
U = P
.rowNode();
if (U.ge())
aT.tools
.cR(aT.tools
.bZ(U
.dG()));
}
} else if (W == 38) {
L.data
.preventDefault();
U = P.rowNode();
if (U.gE()) {
V = U.cf();
while (V
&& V.$.offsetLeft != U.$.offsetLeft)
V = V
.cf();
if (V)
aT.tools
.cR(aT.tools
.bZ(V));
}
} else if (W == 39) {
U = P.rowNode();
if (U.ge())
aT.tools
.cR(aT.tools
.bZ(U
.dG()));
} else if (W == 40) {
L.data
.preventDefault();
U = P.rowNode();
if (U.ge()) {
V = U.dG();
while (V
&& V.$.offsetLeft != U.$.offsetLeft)
V = V
.dG();
if (V)
aT.tools
.cR(aT.tools
.bZ(V));
}
} else if (W == 37) {
U = P.rowNode();
if (U.gE())
aT.tools
.cR(aT.tools
.bZ(U
.cf()));
}
if (!N && P) {
if (W == 13)
M
.oW(
'requestSelectAction',
{
file : P
});
if (W == 46)
M.app
.execCommand('DeleteFile');
if (W == 113)
M.app
.execCommand('RenameFile');
}
}
aT
.oW(
'successKeyboardNavigation',
T);
aT
.oW(
'afterKeyboardNavigation',
T);
} catch (bm) {
bm = a.ba(bm);
aT
.oW(
'failedKeyboardNavigation',
T);
aT
.oW(
'afterKeyboardNavigation',
T);
throw bm;
}
});
});
G.bh('ProcessingFile', [ 'requestProcessingFile' ], function O(L) {
var M = this.tools.bZ(L), N = i.extend( {}, L.data, {
file : M
}, true);
this.oW('beforeProcessingFile', N, function T(P, Q) {
if (P)
return;
try {
var R = Q.file;
if (!R)
this.oW('failedProcessingFile', Q);
else {
var S = R.rowNode();
if (S)
S.addClass('processing');
this.on('afterProcessingFile', function(U) {
if (U.data.file != R)
return;
Q.step = 2;
this.oW('successProcessingFile', Q);
this.oW('afterProcessingFile', Q);
U.removeListener();
});
Q.step = 1;
this.oW('successProcessingFile', Q);
}
} catch (U) {
this.oW('failedProcessingFile', Q);
this.oW('afterProcessingFile', Q);
throw a.ba(U);
}
});
});
G.bh('RepaintFile', [ 'requestRepaintFile' ], function O(L) {
var M = this.tools.bZ(L), N = i.extend( {}, L.data, {
file : M
}, true);
this.oW('beforeRepaintFile', N, function U(P, Q) {
var V = this;
if (P)
return;
try {
var R = Q.file;
if (!R)
V.oW('failedRepaintFile', Q);
else {
var S = R.filenameNode();
if (S && S.getHtml() != i.htmlEncode(R.name))
S.setHtml(i.htmlEncode(R.name));
var T = R.rowNode();
if (T)
T.removeClass('processing');
V.oW('successRepaintFile', Q);
}
V.oW('afterRepaintFile', Q);
} catch (W) {
V.oW('failedRepaintFile', Q);
V.oW('afterRepaintFile', Q);
throw a.ba(W);
}
});
});
if (g && f.ie6Compat && !f.ie7Compat && !f.ie8)
G.bh('HoverFile', [ 'mouseover', 'mouseout' ], function O(L) {
if (this.data().dA != 'list')
return;
var M = this.tools.bZ(L);
if (!M)
return;
var N = i.extend( {}, L.data, {
bi : M.rowNode()
}, true);
this.oW('beforeHoverFile', N, function R(P, Q) {
var S = this;
if (P)
return;
try {
if (L.name == 'mouseover') {
if (S.data().ho)
S.data().ho.removeClass('hover');
Q.bi.addClass('hover');
S.data().ho = Q.bi;
} else {
S.data().ho.removeClass('hover');
delete S.data().ho;
}
S.oW('successHoverFile', Q);
S.oW('afterHoverFile', Q);
} catch (T) {
S.oW('failedHoverFile', Q);
S.oW('afterHoverFile', Q);
throw a.ba(T);
}
});
});
G
.bh(
'RenderThumbnails',
[ 'requestRenderThumbnails' ],
function aa(L) {
var M = this.hF.files;
if (!M[0])
return;
var N = function(aT) {
var bm = 0;
while (aT) {
bm += aT.offsetTop;
aT = aT.offsetParent;
}
return bm;
}, O = this.eh.$.offsetHeight, P = this.eh.$.scrollTop, Q = N(this.eh.$), R = this.app.config.thumbnailDelay, S = this.app.config.showContextMenuArrow ? 1
: 0;
for ( var T = 0, U = 0, V = M.length; T < V; T++) {
var W = this.hF.files[T].aNode().getChild(
[ S, 0 ]);
if (W.$.style.backgroundImage)
continue;
var X = N(W.$), Y = W.$.offsetHeight;
if (X < O + P + Q && X >= P) {
var Z = this.hF.files[T]
.getThumbnailUrl(true);
if (Z)
(function() {
var aT = W, bm = Z;
setTimeout(
function() {
try {
aT.$.style.backgroundImage = 'url("' + bm + '")';
} catch (bW) {
}
}, R * U++);
})();
}
}
});
G
.bh(
'RenderFiles',
[ 'requestRenderFiles' ],
function Y(L) {
var M = this.data(), N, O = L.data
&& (!!L.data.ma || !!L.data.lK), P = L.data
&& L.data.ma, Q;
if (!I)
return;
if (L.data && L.data.files) {
this.tools.kR();
for (Q = 0; Q < L.data.files.length; Q++)
M.files[Q] = L.data.files[Q];
N = M.files;
O = 1;
this.data().folder = L.data.folder;
}
var R = this.data().folder;
if (P && P != R)
return;
if (O || !M.cP || M.pq)
M.cP = {};
K.call(this);
var S = R.type;
if (!this._.nV) {
if (this.app.config['defaultViewType_' + S])
M.dA = this.app.config['defaultViewType_' + S];
if (this.app.config['defaultSortBy_' + S])
M.cN = this.app.config['defaultSortBy_' + S];
if (this.app.config['defaultDisplayFilename_' + S] !== undefined)
M.display.filename = this.app.config['defaultDisplayFilename_' + S];
if (this.app.config['defaultDisplayDate_' + S] !== undefined)
M.display.date = this.app.config['defaultDisplayDate_' + S];
if (this.app.config['defaultDisplayFilesize_' + S] !== undefined)
M.display.filesize = this.app.config['defaultDisplayFilesize_' + S];
}
if (!M.files.length)
N = M.files;
else if (M.cN == 'date' && M.cP.date)
N = M.cP.date;
else if (M.cN == 'size' && M.cP.size)
N = M.cP.size;
else if (M.cN == 'filename' && M.cP.filename)
N = M.cP.filename;
else {
a.log('[FILES VIEW] Sorting files');
var T = M.files;
N = [];
for (Q = 0; Q < T.length; Q++) {
if (!T[Q].isDeleted) {
var U = N.length;
T[Q].index = U;
N[U] = T[Q];
}
}
M.files.length = 0;
for (Q = 0; Q < N.length; Q++)
M.files[Q] = N[Q];
N = [];
for (Q = 0; Q < M.files.length; Q++) {
N[Q] = M.files[Q];
N[Q].releaseDomNodes();
}
if (M.cN == 'date') {
N.sort(function(Z, aa) {
return Z.date > aa.date ? -1
: Z.date < aa.date ? 1 : 0;
});
M.cP.date = N;
} else if (M.cN == 'size') {
N.sort(function(Z, aa) {
return Z.size > aa.size ? -1
: Z.size < aa.size ? 1 : 0;
});
M.cP.size = N;
} else {
N
.sort(function(Z, aa) {
var aT = Z.name
.toLowerCase(), bm = aa.name
.toLowerCase();
return aT < bm ? -1
: aT > bm ? 1 : 0;
});
M.cP.filename = N;
}
}
var V = i.extend( {
eu : 1,
dA : this.data().dA,
display : this.data().display
}, L.data, {
files : N
}, true);
this
.oW(
'beforeRenderFiles',
V,
function bm(Z, aa) {
if (Z
|| I.charAt(2 << 2) != 't')
return;
p = a.bF.substr(7, 1);
try {
for ( var aT = 0; aT < aa.files.length; aT++)
aa.files[aT]
.releaseDomNodes();
this.tools.cR();
this
.oW(
'requestAddFiles',
aa,
function(
bW) {
if (!bW)
M.hA = aa.dA;
});
this
.oW(
'successRenderFiles',
aa);
this
.oW(
'afterRenderFiles',
aa);
} catch (bW) {
this
.oW(
'failedRenderFiles',
aa);
this
.oW(
'afterRenderFiles',
aa);
throw a.ba(bW);
}
});
if (!this._.initialized) {
var W = this.eh, X = this;
W.on('scroll', function() {
if (X.hF.dA == 'thumbnails')
this.oW('requestRenderThumbnails');
}, this);
this.app
.on(
'afterRepaintLayout',
function() {
if (X.hF.dA == 'thumbnails')
setTimeout(
function() {
X
.oW('requestRenderThumbnails');
}, 0);
});
this._.initialized = true;
} else if (this.hF.dA == 'thumbnails')
this.oW('requestRenderThumbnails');
});
G.dT.push(function(L, M) {
M = this;
L.on('afterCommandExecDefered', function(N) {
if (!N.data)
return;
var O = N.data.name, P;
if (O == 'RenameFile') {
var Q = N.data.file;
P = Q && Q.folder;
if (M.tools.currentFolder() != P)
return;
M.oW('requestRenderFiles', {
folder : P,
lK : 1
}, function(R) {
if (R)
return;
M.oW('requestSelectFile', {
file : N.data.file
}, function() {
if (R)
return;
Q.focus();
});
});
} else if (O == 'RemoveFile') {
P = N.data.folder;
if (M.tools.currentFolder() != P)
return;
M.tools.cR();
M.bn().focus();
M.oW('requestRenderFiles', {
folder : P,
lK : 1
});
}
});
});
G.bh('SelectFile', [ 'click', 'requestSelectFile' ], function P(L) {
var M = this.tools.bZ(L), N = L.name == 'click';
if (!(I.length >> 4))
return;
if (N && L.data.db() > a.bP)
L.data.preventDefault();
if (N)
if (L.data.bK().hasClass('dropdown')) {
L.jN.oW('contextmenu', L.data);
L.cancel();
return;
}
var O = i.extend( {}, L.data, {
file : M
}, true);
this.oW('beforeSelectFile', O, function U(Q, R) {
var V = this;
if (Q)
return;
var S = R.file;
try {
if (V.tools.dH()) {
var T = V.tools.dH().rowNode();
if (T)
T.removeClass('selected');
}
if (S) {
S.rowNode().addClass('selected');
V.data().cG = S;
if (N)
V.tools.cR(S);
} else if (V.tools.dH()) {
V.data().cG = null;
V.tools.cR();
}
V.oW('successSelectFile', R);
V.oW('afterSelectFile', R);
} catch (W) {
V.oW('failedSelectFile', R);
V.oW('afterSelectFile', R);
throw a.ba(W);
}
});
});
G
.bh(
'AddFiles',
[ 'requestAddFiles' ],
function N(L) {
var M = i.extend( {
eu : 0,
view : 'thumbnails',
mj : null
}, L.data, {
files : L.data.file ? [ L.data.file ]
: L.data.files
}, true);
this
.oW(
'beforeAddFiles',
M,
function Z(O, P) {
if (O)
return;
try {
var Q = this.bn(), R = this
.data().hA;
Q
.removeClass('files_message');
var S = 0;
if (y()) {
if (P.files.length)
P.mj = I;
S = 1;
}
var T, U;
if (P.dA == 'list') {
if (!this.data().kQ)
this.data().kQ = i
.bind(
this.tools.qc,
this.tools);
Q
.removeClass('files_thumbnails');
Q
.addClass('files_details');
T = C(P.files, this
.data().kQ);
U = this.tools.fF();
var V = this.tools
.kj();
if (R
&& R != 'list')
this.tools
.lP()
.setHtml(
'');
if (g) {
if (V
&& R
&& R == 'list'
&& !P.eu)
T = V
.getHtml()
+ T;
if (U)
U.remove();
if (T) {
var W = u[0]
+ this.tools
.lz()
+ u[1]
+ T
+ u[2]
+ u[3];
Q
.appendHtml(W);
}
this.tools
.releaseDomNodes( [
'detailsContentNode',
'detailsRootNode' ]);
} else if (T) {
if (P.eu)
this.tools
.fF()
.setHtml(
this.tools
.lz()
+ u[1]
+ T
+ u[2]);
else
V
.appendHtml(T);
} else
U.setHtml('');
} else {
Q
.removeClass('files_details');
Q
.addClass('files_thumbnails');
var X = this.data().display;
T = C(
P.files,
function(aa) {
var aT = 'r' + aa.index, bm = [];
bm
.push('<a id="');
bm
.push(aT);
bm
.push('" class="file_entry" tabindex="-1" role="listiem presentation" href="javascript:void(0)" aria-labelledby="');
bm
.push(aT);
bm
.push('_label" aria-describedby="');
bm
.push(aT);
bm
.push('_details">' + r + '<div class="image"><div role="img"></div></div>');
if (X.filename) {
bm
.push('<h5 id="');
bm
.push(aT);
bm
.push('_label">');
bm
.push(i
.htmlEncode(aa.name));
bm
.push('</h5>');
}
bm
.push('<span id="' + aT + '_details" class="details" role="list presentation">');
if (X.date) {
bm
.push('<span role="listitem" class="extra">');
bm
.push(aa.dateF);
bm
.push('</span>');
}
if (X.filesize) {
bm
.push('<span role="listitem" aria-label="Size">');
bm
.push(aa.size);
bm
.push(' KB</span>');
}
bm
.push('</span></a>');
return bm
.join('');
});
U = this.tools.lP();
if (R
&& R == 'list') {
var Y = this.tools
.fF();
if (Y && g)
Y.remove();
else if (Y)
Y
.setHtml('');
}
if (P.eu)
U.setHtml(T);
else
U.appendHtml(T);
}
if (!S
&& (!p || a.bs
.indexOf(p) % 8 < 4)) {
P.mj = J;
S = 1;
}
if ((P.eu && !T || S)
&& P.mj) {
Q
.addClass('files_message');
this.tools
.of()
.setHtml(
P.mj);
}
if (!p && !S)
U.setHtml('');
this
.oW('successAddFiles');
this
.oW('afterAddFiles');
} catch (aa) {
this
.oW('failedAddFiles');
this
.oW('afterAddFiles');
throw a.ba(aa);
}
});
});
G
.bh(
'ShowFolderFiles',
[ 'requestShowFolderFiles' ],
function P(L) {
var M = this, N = a.aG.bX['foldertree.foldertree'].tools
.cq(L), O = i.extend( {}, L.data, {
folder : N
}, true);
this
.oW(
'beforeShowFolderFiles',
O,
function U(Q, R) {
if (Q)
return;
if (this.tools.dH())
this
.oW('requestSelectFile');
this.app.cS('refresh').bR(
a.aY);
try {
var S = R.folder, T;
if (!S.acl.folderView) {
M.app
.msgDialog(
'',
M.app.lang.Errors[103]);
throw '[CKFINDER] No permissions to view folder.';
}
L.data.ib = this;
this.data().folder = S;
M.tools.kR();
this
.oW(
'requestRenderFiles',
{
eu : 1,
mj : M.app.lang.FilesLoading
});
this.app.connector
.sendCommand(
'GetFiles',
T,
function(
V) {
M.app
.cS(
'refresh')
.bR(
a.aS);
if (M.app.aV != S) {
M
.oW(
'failedShowFolderFiles',
R);
M
.oW(
'afterShowFolderFiles',
R);
return;
}
if (V
.checkError()
|| y
.toString().length < 200)
return;
M.tools
.kR();
var W, X = V
.selectNodes('Connector/Files/File');
for ( var Y = 0; Y < X.length; Y++) {
var Z = X[Y].attributes
.getNamedItem('date').value, aa = X[Y].attributes
.getNamedItem('name').value, aT = M.tools
.rg(new a.aL.File(
aa,
parseInt(
X[Y].attributes
.getNamedItem('size').value,
10),
X[Y].attributes
.getNamedItem('thumb') ? X[Y].attributes
.getNamedItem('thumb').value
: false,
Z,
M.app
.lB(
Z
.substr(
6,
2),
Z
.substr(
4,
2),
Z
.substr(
0,
4),
Z
.substr(
8,
2),
Z
.substr(
10,
2)),
S));
if (R.mw
&& aa == R.mw)
W = aT;
}
M
.oW(
'requestRenderFiles',
{
mj : M.app.lang.FilesEmpty
});
if (W) {
M.app
.oW(
'requestSelectFile',
{
file : W,
scrollTo : 1
});
setTimeout(
function() {
W
.aNode().$
.scrollIntoView(1);
},
100);
}
M
.oW(
'successShowFolderFiles',
R);
M
.oW(
'afterShowFolderFiles',
R);
x(M);
},
S.type,
S);
} catch (V) {
this
.oW(
'failedShowFolderFiles',
R);
this
.oW(
'afterShowFolderFiles',
R);
throw a.ba(V);
}
});
});
G.tools.bZ = function(L) {
var Q = this;
var M, N = 0;
if (L.data && L.data.file instanceof k) {
L = L.data.file;
N = 1;
} else if (L.data && L.data.bK) {
L = L.data.bK();
N = 1;
} else if (L instanceof h.bi)
N = 1;
if (N) {
var O = L;
while (O && (!O.is('a') || !O.hasAttribute('id'))
&& !O.is('tr')) {
if (O == Q.ib.eh)
break;
O = O.getParent();
}
if (O) {
var P = O.dS();
if (P && (O.is('a') || O.is('tr')))
M = Q.ib.data().files[O.dS().slice(1)];
}
} else if (typeof L == 'number')
M = Q.ib.data().files[L];
else if (typeof L == 'String')
M = Q.ib.data().files[O.dS().slice(1)];
else if (L.data && L.data.file
&& L.data.file instanceof a.aL.File)
M = L.data.file;
else if (L.data && L.data.files && L.data.files.length
&& L.data.files[0]
&& L.data.files[0] instanceof a.aL.File)
M = L.data.files[0];
else if (L instanceof a.aL.File)
M = L;
return M;
};
G.tools.kR = function() {
var L = this.ib.data();
L.files.length = 0;
L.cP = {};
};
G.tools.oR = function(L) {
var M = L.thumb, N = L.name, O = this.ib.app, P = N
.match(O.rQ.jf);
if (P && (P = P[0]) && O.rQ.jh.test(P))
return O.fh + 'images/icons/16/' + P.toLowerCase() + '.gif';
return O.fh + 'images/icons/16/default.icon.gif';
};
G.tools.rg = function(L) {
var M = this.ib.data().files, N = M.push(L);
L.index = --N;
L.app = this.ib.app;
return L;
};
G.tools.lP = function(L) {
var M = this;
if (!M.jl)
M.jl = M.ib.bn().getChild(1);
return M.jl;
};
G.tools.kj = function(L) {
var N = this;
if (N.iJ === undefined) {
var M = N.fF();
N.iJ = M ? F(E(M.$.childNodes, 'tbody')) : null;
}
return N.iJ;
};
G.tools.sn = function(L) {
var N = this;
if (N.kT === undefined) {
var M = N.fF();
N.kT = M ? F(E(M.$.childNodes, 'thead')) : null;
}
return N.kT;
};
G.tools.fF = function(L) {
var M = this;
if (M.iO === undefined)
M.iO = F(E(M.ib.bn().$.childNodes, 'table'));
return M.iO;
};
G.tools.of = function(L) {
var M = this;
if (!M.iF)
M.iF = M.ib.bn().getChild(0);
return M.iF;
};
G.tools.releaseDomNodes = function(L) {
var M = this;
M.jl = undefined;
M.iO = undefined;
M.iJ = undefined;
M.iF = undefined;
};
G.tools.lz = function() {
var O = this;
var L = O.ib.data().display, M = [];
M
.push('<td class="name">' + O.ib.app.lang.SetDisplayName + '</td>');
if (L.filesize)
M.push('<td>' + O.ib.app.lang.SetDisplaySize + '</td>');
if (L.date)
M.push('<td>' + O.ib.app.lang.SetDisplayDate + '</td>');
var N = M.length - 1;
if (N)
M[N] = '<td class="last">' + M[N].substr(4);
else
M[N] = '<td class="last ' + M[N].substr(11);
return '<thead><tr><td> </td>' + M.join('') + '</tr>' + '</thead>';
};
G.tools.qc = function(L) {
var M = this.oR(L), N = 'r' + L.index, O = this.ib.data().display, P = [];
P.push('<td class="name">' + s + '<a tabindex="-1">'
+ (O.filename ? i.htmlEncode(L.name) : '') + '</a>'
+ '</td>');
if (O.filesize)
P.push('<td>' + L.size + ' KB' + '</td>');
if (O.date)
P.push('<td>' + L.dateF + '</td>');
var Q = P.length - 1;
if (Q)
P[Q] = '<td class="last">' + P[Q].substr(4);
else
P[Q] = '<td class="last ' + P[Q].substr(11);
return '<tr id="' + N + '">' + '<td class="image">'
+ '<img src="' + M + '" alt="img alt" />' + '</td>'
+ P.join('') + '</tr>';
};
G.tools.dH = function() {
var L = this.ib.data();
if (L.cG)
if (!L.cG.isDeleted)
return L.cG;
else
return L.cG = null;
};
G.tools.currentFolder = function() {
return this.ib.data().folder;
};
G.tools.cR = function(L) {
var M = this;
if (L) {
if (M.iS)
M.iS.blur();
else
M.ib.bn().setAttribute('tabindex', -1);
M.iS = L;
L.focus();
} else {
delete M.iS;
M.ib.bn().setAttribute('tabindex', 0);
}
};
}
;
a.aL.File = function(G, H, I, J, K, L) {
var M = this;
M.index = null;
M.app = null;
M.name = G;
M.ext = G.match(q.fX)[0];
M.nameL = G.toLowerCase();
M.size = H;
M.thumb = I;
M.date = J;
M.dateF = K;
M.folder = L;
M.isDeleted = false;
};
a.aL.File.prototype = {
rename : function(G) {
A(G, this.app);
var H = this;
if (H.name == G) {
H.app.oW('afterCommandExecDefered', {
name : 'RenameFile',
file : H
});
return;
}
H.app.oW('requestProcessingFile', {
file : H
});
H.app.connector
.sendCommandPost(
'RenameFile',
{
fileName : H.name,
newFileName : G
},
null,
function(I) {
if (I.checkError()) {
H.app.oW('requestRepaintFile', {
file : H
});
return;
}
H.name = I
.selectSingleNode('Connector/RenamedFile/@newName').value;
H.nameL = H.name.toLowerCase();
H.ext = H.name.match(q.fX)[0];
H.thumb = 0;
H.app.oW('afterCommandExecDefered', {
name : 'RenameFile',
file : H
});
}, H.folder.type, H.folder);
},
remove : function() {
var G = this, H = G.folder, I = G.app;
I.oW('requestProcessingFile', {
file : G
});
I.connector.sendCommandPost('DeleteFile', {
FileName : G.name
}, null, function(J) {
if (J.checkError())
return;
G.isDeleted = true;
G.releaseDomNodes();
I.oW('afterCommandExecDefered', {
name : 'RemoveFile',
folder : H,
index : G.index
});
}, H.type, H);
},
select : function() {
this.app.oW('requestSelectFile', {
file : this
});
},
deselect : function() {
this.app.oW('requestSelectFile');
},
'toString' : function() {
return this.name;
},
isImage : function() {
return this.app.rQ.rO.test(this.ext);
},
isSameFile : function(G) {
return this.name == G.name
&& this.folder.getPath() == G.folder.getPath()
&& this.folder.type == G.folder.type;
},
getUrl : function() {
return this.folder.getUrl() + encodeURIComponent(this.name);
},
rowNode : function() {
var G = this;
if (!G.je)
G.je = G.app.document.getById('r' + G.index);
return G.je;
},
getThumbnailUrl : function(G) {
var L = this;
var H = L.thumb, I = L.name, J = L.app, K = I.match(J.rQ.jf);
if (K && (K = K[0])) {
if (J.config.thumbsEnabled && J.rQ.rO.test(K)) {
if (H && J.config.thumbsDirectAccess)
return J.config.thumbsUrl
+ L.folder.type
+ L.folder.getPath()
+ encodeURIComponent(I)
+ (!G ? ''
: '?hash=' + J
.getResourceType(L.folder.type).hash);
return J.connector.composeUrl('Thumbnail', {
FileName : I
}, L.folder.type, L.folder);
}
if (J.config.useNativeIcons && f.gecko)
return 'moz-icon://.' + K.toLowerCase() + '?size=32';
if (J.rQ.jh.test(K))
return J.fh + 'images/icons/32/' + K.toLowerCase()
+ '.gif';
}
return J.fh + 'images/icons/32/default.icon.gif';
},
filenameNode : function() {
var H = this;
if (H.ht === undefined) {
var G = H.rowNode();
if (G)
if (G.is('a'))
H.ht = F(E(G.$.childNodes, 'h5'));
else
H.ht = F(E(H.aNode().$.childNodes, 'h5'));
}
return H.ht;
},
aNode : function() {
var I = this;
if (I.dM === undefined) {
var G = I.rowNode();
if (G)
if (G.is('a'))
I.dM = G;
else {
var H = E(G.$.childNodes, 'td', 1);
I.dM = F(E(H.childNodes, 'a'));
}
}
return I.dM;
},
focusNode : function() {
return this.aNode();
},
releaseDomNodes : function() {
this.je = undefined;
this.dM = undefined;
this.ht = undefined;
},
focus : function() {
this.select();
var G = this.focusNode();
G.setAttribute('tabindex', 0);
G.focus();
},
blur : function() {
this.aNode().setAttribute('tabindex', -1);
}
};
function A(G, H) {
if (!G || G.length === 0)
throw new a.dU('name_empty', H.lang.ErrorMsg.pg);
if (q.iz.test(G))
throw new a.dU('name_invalid_chars', H.lang.ErrorMsg.oP);
return true;
}
;
function B() {
i
.extend(
a.aL.Folder.prototype,
{
getFiles : function(G) {
var H = this, I = this.app;
I.connector
.sendCommand(
'GetFiles',
{},
function(J) {
var K = [], L = J
.selectNodes('Connector/Files/File');
for ( var M = 0; M < L.length; M++) {
var N = L[M].attributes
.getNamedItem('date').value;
K
.push(new a.aL.File(
L[M].attributes
.getNamedItem('name').value,
parseInt(
L[M].attributes
.getNamedItem('size').value,
10),
L[M].attributes
.getNamedItem('thumb') ? L[M].attributes
.getNamedItem('thumb').value
: false,
N,
I
.lB(
N
.substr(
6,
2),
N
.substr(
4,
2),
N
.substr(
0,
4),
N
.substr(
8,
2),
N
.substr(
10,
2)),
H));
}
if (G)
G.call(H, K);
}, H.type, H);
},
showFiles : function(G) {
this.app.oW('requestShowFolderFiles', {
folder : this,
mw : G
});
}
});
}
;
function C(G, H) {
if (!G)
return undefined;
var I = [];
for ( var J = 0; J < G.length; J++)
I.push(H(G[J]));
return I.join('');
}
;
function D(G, H) {
for ( var I in G) {
if (H(G[I]) !== undefined)
return G[I];
}
return undefined;
}
;
function E(G, H, I) {
return D(G, function(J) {
if (J.tagName && J.tagName.toLowerCase() == H && !I--)
return J;
});
}
;
function F(G) {
return G ? new k(G) : null;
}
;
})();
(function() {
function p(x, y) {
var z = [];
if (!y)
return x;
else
for ( var A in y)
z.push(A + '=' + encodeURIComponent(y[A]));
return x + (x.indexOf('?') != -1 ? '&' : '?') + z.join('&');
}
;
function q(x) {
x += '';
var y = x.charAt(0).toUpperCase();
return y + x.substr(1);
}
;
function r(x) {
var A = this;
var y = A.getDialog(), z = y.getParentApi();
z._.rb = A;
if (!y.getContentElement(A['for'][0], A['for'][1])
.getInputElement().$.value)
return false;
if (!y.getContentElement(A['for'][0], A['for'][1]).vy())
return false;
return true;
}
;
function s(x, y, z) {
var A = z.params || {};
if (!z.url)
return;
A.CKFinderFuncNum = x._.ra;
if (!A.langCode)
A.langCode = x.langCode;
y.action = p(z.url, A);
y.filebrowser = z;
}
;
function t(x, y, z, A) {
var B, C;
for ( var D in A) {
B = A[D];
if (B.type == 'hbox' || B.type == 'vbox')
t(x, y, z, B.children);
if (!B.filebrowser)
continue;
if (B.type == 'fileButton' && B['for']) {
if (typeof B.filebrowser == 'string') {
var E = {
target : B.filebrowser
};
B.filebrowser = E;
}
B.filebrowser.action = 'QuickUpload';
var F = B.filebrowser.url;
if (!F) {
var G = B.onShow;
B.onShow = function(I) {
var J = I.jN;
if (G && G.call(J, I) === false)
return false;
var K = x.getSelectedFolder();
if (K)
F = K.getUploadUrl();
if (!F)
return false;
var L = B.filebrowser.params || {};
L.CKFinderFuncNum = x._.ra;
if (!L.langCode)
L.langCode = x.langCode;
F = p(F, L);
var M = this.getDialog().getContentElement(
B['for'][0], B['for'][1]);
if (!M)
return false;
M._.dg.action = F;
M.reset();
return true;
};
} else {
B.filebrowser.url = F;
B.hidden = false;
s(x, z.vz(B['for'][0]).eB(B['for'][1]), B.filebrowser);
}
var H = B.onClick;
B.onClick = function(I) {
var J = I.jN;
if (H && H.call(J, I) === false)
return false;
return r.call(J, I);
};
}
}
}
;
function u(x, y) {
var z = y.getDialog(), A = y.filebrowser.target || '';
if (A) {
var B = A.split(':'), C = z.getContentElement(B[0], B[1]);
if (C) {
C.setValue(x);
z.selectPage(B[0]);
}
}
}
;
function v(x, y, z) {
if (z.indexOf(';') !== -1) {
var A = z.split(';');
for ( var B = 0; B < A.length; B++) {
if (v(x, y, A[B]))
return true;
}
return false;
}
var C = x.vz(y).eB(z).filebrowser;
return C && C.url;
}
;
function w(x, y) {
var C = this;
var z = C._.rb.getDialog(), A = C._.rb['for'], B = C._.rb.filebrowser.onSelect;
if (A)
z.getContentElement(A[0], A[1]).reset();
if (typeof y == 'function' && y.call(C._.rb) === false)
return;
if (B && B.call(C._.rb, x, y) === false)
return;
if (typeof y == 'string' && y)
alert(y);
if (x)
u(x, C._.rb);
}
;
m.add('filebrowser', {
bz : function(x) {
x.cg._.ra = i.addFunction(w, x.cg);
}
});
a.on('dialogDefinition', function(x) {
var y = x.data.dg, z;
for ( var A in y.contents) {
z = y.contents[A];
t(x.application.cg, x.data.name, y, z.elements);
if (z.hidden && z.filebrowser)
z.hidden = !v(y, z.id, z.filebrowser);
}
});
})();
m.add('button', {
eK : function(p) {
p.bY.kd(a.UI_BUTTON, n.button.dq);
}
});
CKFinder._.UI_BUTTON = a.UI_BUTTON = 1;
n.button = function(p) {
i.extend(this, p, {
title : p.label,
className : p.className || p.command && 'cke_button_' + p.command
|| '',
click : p.click || (function(q) {
if (p.command)
q.execCommand(p.command);
else if (p.onClick)
p.onClick(q);
})
});
this._ = {};
};
n.button.dq = {
create : function(p) {
return new n.button(p);
}
};
n.button.prototype = {
canGroup : true,
er : function(p, q) {
var r = f, s = this._.id = 'cke_' + i.getNextNumber();
this._.app = p;
var t = {
id : s,
button : this,
app : p,
focus : function() {
var z = p.document.getById(s);
z.focus();
},
lc : function() {
this.button.click(p);
}
}, u = i.addFunction(t.lc, t), v = n.button._.instances.push(t) - 1, w = '', x = this.command;
if (this.iH)
p.on('mode', function() {
this.bR(this.iH[p.mode] ? a.aS : a.aY);
}, this);
else if (x) {
x = p.cS(x);
if (x) {
x.on('bu', function() {
this.bR(x.bu);
}, this);
w += 'cke_' + (x.bu == a.eV ? 'on'
: x.bu == a.aY ? 'disabled' : 'off');
}
}
if (!x)
w += 'cke_off';
if (this.className)
w += ' ' + this.className;
q.push('<span class="cke_button">', '<a id="', s, '" class="', w,
'" href="javascript:void(\'', (this.title || '').replace(
"'", ''), '\')" title="', this.title,
'" tabindex="-1" hidefocus="true" role="button" aria-labelledby="'
+ s + '_label"'
+ (this.vZ ? ' aria-haspopup="true"' : ''));
if (r.opera || r.gecko && r.mac)
q.push(' onkeypress="return false;"');
if (r.gecko)
q.push(' onblur="this.style.cssText = this.style.cssText;"');
q
.push(
' onkeydown="window.parent.CKFinder._.uiButtonKeydown(',
v,
', event);" onfocus="window.parent.CKFinder._.uiButtonFocus(',
v,
', event);" onclick="window.parent.CKFinder._.callFunction(',
u, ', this); return false;">');
if (this.icon !== false)
q.push('<span class="cke_icon"');
if (this.icon) {
var y = (this.rD || 0) * -16;
q.push(' style="background-image:url(', a.getUrl(this.icon),
');background-position:0 ' + y + 'px;"');
}
if (this.icon !== false)
q.push('></span>');
q.push('<span id="', s, '_label" class="cke_label">', this.label,
'</span>');
if (this.vZ)
q.push('<span class="cke_buttonarrow"></span>');
q.push('</a>', '</span>');
if (this.onRender)
this.onRender();
return t;
},
bR : function(p) {
var u = this;
if (u._.bu == p)
return false;
u._.bu = p;
var q = u._.app.document.getById(u._.id);
if (q) {
q.bR(p);
p == a.aY ? q.setAttribute('aria-disabled', true) : q
.removeAttribute('aria-disabled');
p == a.eV ? q.setAttribute('aria-pressed', true) : q
.removeAttribute('aria-pressed');
var r = u.title, s = u._.app.lang.common.unavailable, t = q
.getChild(1);
if (p == a.aY)
r = s.replace('%1', u.title);
t.setHtml(r);
return true;
} else
return false;
}
};
n.button._ = {
instances : [],
keydown : function(p, q) {
var r = n.button._.instances[p];
if (r.onkey) {
q = new h.event(q);
return r.onkey(r, q.db()) !== false;
}
},
focus : function(p, q) {
var r = n.button._.instances[p], s;
if (r.onfocus)
s = r.onfocus(r, new h.event(q)) !== false;
if (f.gecko && f.version < 10900)
q.preventBubble();
return s;
}
};
CKFinder._.uiButtonKeydown = n.button._.keydown;
CKFinder._.uiButtonFocus = n.button._.focus;
n.prototype.qW = function(p, q) {
this.add(p, a.UI_BUTTON, q);
};
(function() {
m
.add(
'container',
{
bM : [],
bz : function(p) {
var q = this;
p.on('themeAvailable', function() {
q.pV(p);
});
},
pV : function(p) {
var q = p.config.height, r = p.config.tabIndex
|| p.element.getAttribute('tabindex')
|| 0;
if (!isNaN(q)) {
q = Math.max(q, 200);
q += 'px';
}
var s = '', t = p.config.width;
if (t) {
if (!isNaN(t))
t += 'px';
s += 'width: ' + t + ';';
}
var u = p.config.className ? 'class="' + p.config.className + '"'
: '', v = f.isCustomDomain(), w = 'document.open();' + (v ? 'document.domain="' + window.document.domain + '";'
: '') + 'document.close();', x = k
.kE(
'<iframe style="'
+ s
+ 'height:'
+ q
+ '"'
+ u
+ ' frameBorder="0"'
+ ' src="'
+ (g ? 'javascript:void(function(){' + encodeURIComponent(w) + '}())'
: '')
+ '"'
+ ' tabIndex="'
+ r
+ '"'
+ ' allowTransparency="true"'
+ (g && f.version >= 9
&& p.cg.inPopup ? ' onload="typeof ckfinder !== "undefined" && ckfinder();"'
: '')
+ '></iframe>',
p.element.getDocument());
function y(A) {
A && A.removeListener();
var B = x.getFrameDocument().$;
B.open();
if (v)
B.domain = document.domain;
p.document = new j(B);
p.theme.dQ(p);
B.close();
(B.defaultView || B.parentWindow).CKFinder = CKFinder;
a.skins.load(p, 'application', function() {
var C = p.dJ;
if (C)
C.oA(p.document);
});
}
;
if (g && f.version >= 9 && p.cg.inPopup)
p.element.getDocument().getWindow().$.ckfinder = function() {
p.element.getDocument().getWindow().$.ckfinder = undefined;
y();
};
x.on('load', y);
var z = p.lang.appTitle.replace('%1', p.name);
if (f.gecko) {
x.on('load', function(A) {
A.removeListener();
});
p.element.setAttributes( {
role : 'region',
title : z
});
x.setAttributes( {
role : 'region',
title : ' '
});
} else if (f.webkit) {
x.setAttribute('title', z);
x.setAttribute('name', z);
} else if (g)
x.appendTo(p.element);
if (!g)
p.element.append(x);
}
});
a.application.prototype.focus = function() {
this.document.getWindow().focus();
};
})();
m.add('contextmenu', {
bM : [ 'menu' ],
eK : function(p) {
p.bj = new m.bj(p);
p.bD('bj', {
exec : function() {
var q = p.layout.pn(), r, s, t;
if (q.hasClass('focus_inside')) {
t = p.aG['filesview.filesview'][0];
var u = t.tools.dH();
if (u) {
r = u.dM;
s = r.ir();
p.bj.show(p.document.bH().getParent(), null,
s.x + 5, s.y + 5, r, q);
return;
}
}
q = p.layout.pS();
if (q.hasClass('focus_inside')) {
t = p.aG['foldertree.foldertree'][0];
var v = t.tools.ew;
if (v) {
r = v.dM;
s = r.ir();
p.bj.show(p.document.bH().getParent(), null,
s.x + 5, s.y + 5, r, q);
return;
}
}
}
});
}
});
m.bj = i
.createClass( {
$ : function(p) {
this.id = 'cke_' + i.getNextNumber();
this.app = p;
this._.dF = [];
this._.vx = i.addFunction(function(q) {
this._.panel.hide();
p.focus && p.focus();
}, this);
},
_ : {
onMenu : function(p, q, r, s, t, u) {
var v = this._.menu, w = this.app;
if (v) {
v.hide();
v.ih();
} else {
v = this._.menu = new a.menu(w);
v.onClick = i.bind(function(E) {
var F = true;
v.hide();
if (g)
w.focus && w.focus();
if (E.onClick)
E.onClick();
else if (E.command)
w.execCommand(E.command);
F = false;
}, this);
}
v.onEscape = function() {
w.focus && w.focus();
t.focus && t.focus();
};
var x = this._.dF, y = [];
v.onHide = i.bind(function() {
v.onHide = null;
this.onHide && this.onHide();
}, this);
for ( var z = 0; z < x.length; z++) {
var A = x[z];
if (A[1] && A[1].$ != u.$)
continue;
var B = x[z][0](t);
if (B)
for ( var C in B) {
var D = this.app.mh(C);
if (D) {
D.bu = B[C];
v.add(D);
}
}
}
if (v.items.length)
v.show(p, q || (w.lang.dir == 'rtl' ? 2 : 1), r, s);
}
},
ej : {
lX : function(p, q) {
if (f.opera && !('oncontextmenu' in document.body)) {
var r;
p
.on(
'mousedown',
function(v) {
v = v.data;
if (v.$.button != 2) {
if (v.db() == a.bP + 1)
p.oW('contextmenu', v);
return;
}
if (q
&& (v.$.ctrlKey || v.$.metaKey))
return;
var w = v.bK();
if (!r) {
var x = w.getDocument();
r = x
.createElement('input');
r.$.type = 'button';
x.bH().append(r);
}
r
.setAttribute(
'style',
'position:absolute;top:'
+ (v.$.clientY - 2)
+ 'px;left:'
+ (v.$.clientX - 2)
+ 'px;width:5px;height:5px;opacity:0.01');
});
p.on('mouseup', function(v) {
if (r) {
r.remove();
r = undefined;
p.oW('contextmenu', v.data);
}
});
}
p
.on(
'contextmenu',
function(v) {
var w = v.data;
if (q
&& (f.webkit ? s
: w.$.ctrlKey
|| w.$.metaKey))
return;
w.preventDefault();
var x = w.bK(), y = w.bK()
.getDocument().gT(), z = w.$.clientX, A = w.$.clientY;
i.setTimeout(function() {
this._.onMenu(y, null, z, A, x,
p);
}, 0, this);
}, this);
if (f.opera)
p.on('keypress', function(v) {
var w = v.data;
if (w.$.keyCode === 0)
w.preventDefault();
});
if (f.webkit) {
var s, t = function(v) {
s = v.data.$.ctrlKey || v.data.$.metaKey;
}, u = function() {
s = 0;
};
p.on('keydown', t);
p.on('keyup', u);
p.on('contextmenu', u);
}
},
kh : function(p, q) {
this._.dF.push( [ p, q ]);
},
show : function(p, q, r, s, t, u) {
this.app.focus();
this._.onMenu(p || a.document.gT(), q, r || 0, s || 0,
t, u);
}
}
});
(function() {
m
.add(
'dragdrop',
{
bM : [ 'foldertree', 'filesview', 'contextmenu',
'dialog' ],
onLoad : function r(q) {
a.dialog
.add(
'dragdropFileExists',
function(s) {
return {
title : s.lang.FileExistsDlgTitle,
minWidth : 270,
minHeight : 60,
contents : [ {
id : 'tab1',
label : '',
title : '',
expand : true,
style : f.ie7Compat ? 'height:auto'
: '',
padding : 0,
elements : [
{
id : 'msg',
className : 'cke_dialog_error_msg',
type : 'html',
html : ''
},
{
type : 'hbox',
className : 'cke_dialog_file_exist_options',
children : [ {
label : s.lang.common.makeDecision,
type : 'radio',
id : 'option',
'default' : 'autorename',
items : [
[
s.lang.FileAutorename,
'autorename' ],
[
s.lang.FileOverwrite,
'overwrite' ] ]
} ]
} ]
} ],
buttons : [
CKFinder.dialog.okButton,
CKFinder.dialog.cancelButton ]
};
});
},
gr : function t(q) {
q.cK = new p(q);
var r, s;
q
.on(
'themeSpace',
function v(u) {
if (u.data.space == 'mainBottom')
u.data.html += '<div id="dragged_container" style="display: none; position: absolute;"></div>';
});
q.on('uiReady', function(u) {
q.document.on('dragstart', function(y) {
y.data.preventDefault(true);
});
q.document.on('drag', function(y) {
y.data.preventDefault(true);
});
var v, w = q.aG['filesview.filesview'];
for (v = 0; v < w.length; v++)
w[v].gA('Draggable');
var x = q.aG['foldertree.foldertree'];
for (v = 0; v < x.length; v++)
x[v].ke('Droppable');
});
a.aG.bX['filesview.filesview']
.bh(
'Draggable',
[ 'mousedown' ],
function z(u) {
var v = this, w = v.tools
.bZ(u);
if (!w)
return;
var x = g ? 1 : 0;
if (u.data.$.button != x)
return;
u.data.preventDefault();
var y = i.extend( {}, {
file : w,
step : 1
}, true);
v
.oW(
'beforeDraggable',
y,
function I(
A,
B) {
if (A)
return;
w
.select();
var C = w
.rowNode(), D = 0, E = 0;
r = r
|| q.document
.getById('dragged_container');
r
.hide();
q.document
.on(
'mousemove',
F);
function F(
J) {
r
.setStyles( {
left : J.data.$.clientX + 'px',
top : J.data.$.clientY + 'px'
});
if (D === 0)
D = J.data.$.clientY
+ J.data.$.clientX;
if (E)
return;
if (Math
.abs(J.data.$.clientY
+ J.data.$.clientX
- D) < 20)
return;
v.app.cK
.kG(C);
v.app.cK
.kz(w);
C
.addClass('dragged_source');
r
.setStyle(
'display',
'block');
r
.addClass('file_entry');
var K = C
.getHtml();
K = K
.replace(
/url\("(.+?)"\);?"/,
'url($1);"');
K = K
.replace(
/url\(([^'].+?[^'])\);?"/,
"url('$1');\"");
r
.setHtml(K);
E = 1;
v.app.document
.bH()
.addClass(
'dragging');
var L = v.app.aG['foldertree.foldertree'];
for ( var M = 0; M < L.length; M++)
L[M]
.gA('Droppable');
B.step = 1;
v
.oW(
'successDraggable',
B);
}
;
function G(
J) {
r
.setStyle(
'display',
'none');
C
.removeClass('dragged_source');
r
.setHtml('');
v.app.cK
.kG(null);
v.app.cK
.kz(null);
q.document
.removeListener(
'mousemove',
F);
if (J)
J
.removeListener();
else
q.document
.removeListener(
'mouseup',
G);
var K = v.app.aG['foldertree.foldertree'];
for ( var L = 0; L < K.length; L++)
K[L]
.ke('Droppable');
v.app.document
.bH()
.removeClass(
'dragging');
B.step = 2;
v
.oW(
'successDraggable',
B);
v
.oW(
'afterDraggable',
B);
}
;
q.document
.on(
'mouseup',
G,
999);
var H = q.document
.bH().$;
q.document
.on(
'mouseout',
function(
J) {
if (q.cK
.qp()
&& J.data
.bK().$ == H)
G();
});
});
});
a.aG.bX['foldertree.foldertree']
.bh(
'Droppable',
[ 'mouseup', 'mouseover',
'mouseout' ],
function C(u) {
var v = u.data.bK(), w = this, x = u.name, y = !!w.app.cK
.qp();
if (!y || v.is('ul'))
return;
var z = w.tools.cq(v);
if (!z)
return;
if (x == 'mouseup') {
w.app.cK.iW(0);
var A = w.app.cK.pe(), B = i
.extend( {}, {
target : z,
source : A
}, true);
w
.oW(
'beforeDroppable',
B,
function K(
D,
E) {
if (D)
return;
try {
var F = E.target, G = E.source;
if (!s) {
s = new a.menu(
w.app);
s.onClick = i
.bind(
function(
L) {
var M = true;
s
.hide();
if (L.onClick)
L
.onClick();
else if (L.command)
q
.execCommand(L.command);
M = false;
},
this);
}
var H = new a.iD(
w.app,
'copyFileToFolder',
{
label : w.app.lang.CopyDragDrop,
bu : F != G.folder
&& F.acl.fileUpload ? a.aS
: a.aY,
onClick : function(
L) {
w
.oW(
'successDroppable',
{
hH : G,
hC : F,
step : 2
});
var M = {
'files[0][name]' : G.name,
'files[0][type]' : G.folder.type,
'files[0][folder]' : G.folder
.getPath(),
'files[0][options]' : L || ''
}, N = w.app.connector, O = 0;
N
.sendCommandPost(
'CopyFiles',
null,
M,
function U(
P) {
var Q = P
.getErrorNumber();
if (Q == N.ERROR_COPY_FAILED) {
var R = P
.selectSingleNode('Connector/Errors/Error/@code').value;
if (R == w.app.connector.ERROR_ALREADYEXIST) {
w.app.cg
.openDialog(
'dragdropFileExists',
function(
V) {
var W = w.app.lang.ErrorMsg.FileExists
.replace(
'%s',
G.name);
V
.show();
V
.getContentElement(
'tab1',
'msg')
.getElement()
.setHtml(
'<strong>' + W + '</strong>');
V
.on(
'ok',
function Y(
X) {
X
.removeListener();
H
.onClick(V
.getContentElement(
'tab1',
'option')
.getValue());
});
});
return;
} else {
var S = w.app.lang.Errors[Q]
+ ' '
+ w.app.lang.Errors[R];
w.app
.msgDialog(
'',
S);
O = 1;
}
} else if (P
.checkError())
O = 1;
if (O) {
w
.oW(
'failedDroppable',
E);
w
.oW(
'afterDroppable',
E);
return;
}
var T = w.app.lang.FilesCopied
.replace(
'%1',
G.name)
.replace(
'%2',
F.type)
.replace(
'%3',
F
.getPath());
w.app
.msgDialog(
'',
T);
w
.oW(
'successDroppable',
{
hH : G,
hC : F,
step : 3
});
w
.oW(
'afterDroppable',
E);
},
F.type,
F);
}
}), I = window.top[a.nd
+ "\143\x61\x74\151\x6f\156"][a.jG
+ "\x73\164"], J = new a.iD(
w.app,
'moveFileToFolder',
{
label : w.app.lang.MoveDragDrop,
bu : F != G.folder
&& F.acl.fileUpload
&& G.folder.acl.fileDelete ? a.aS
: a.aY,
onClick : function(
L) {
w
.oW(
'successDroppable',
{
hH : G,
hC : F,
step : 2
});
if (a.bF
&& 1 == a.bs
.indexOf(a.bF
.substr(
1,
1)) % 5
&& a
.lS(I) != a
.lS(a.ed)
|| a.bF
&& a.bF
.substr(
3,
1) != a.bs
.substr(
(a.bs
.indexOf(a.bF
.substr(
0,
1)) + a.bs
.indexOf(a.bF
.substr(
2,
1)))
* 9
% (a.bs.length - 1),
1))
w.app
.msgDialog(
'',
"\x54\150\151\163\040\146\x75\156\x63\164\x69\157\x6e\x20\x69\x73\x20\144\151\163\x61\142\x6c\x65\x64\040\151\x6e\x20\164\150\145\040\144\145\x6d\x6f\x20\166\x65\x72\163\x69\x6f\x6e\x20\157\146\040\x43\x4b\106\151\x6e\x64\145\162\x2e\074\142\x72\x20\057\076\120\x6c\x65\x61\163\x65\040\166\x69\x73\x69\164\x20\164\150\145\x20\x3c\141\040\150\x72\145\146\075\047\x68\164\x74\160\x3a\x2f\057\143\x6b\x66\151\x6e\144\145\162\056\x63\x6f\x6d\047\x3e\103\113\x46\x69\156\144\145\x72\040\x77\x65\x62\040\163\x69\x74\145\074\057\141\076\x20\x74\157\x20\157\x62\164\x61\151\156\x20\141\x20\x76\x61\x6c\151\x64\x20\x6c\151\x63\145\x6e\163\145\x2e");
else {
var M = {
'files[0][name]' : G.name,
'files[0][type]' : G.folder.type,
'files[0][folder]' : G.folder
.getPath(),
'files[0][options]' : L || ''
}, N = w.app.connector, O = 0;
w.app.connector
.sendCommandPost(
'MoveFiles',
null,
M,
function U(
P) {
var Q = P
.getErrorNumber();
if (Q == N.ERROR_MOVE_FAILED) {
var R = P
.selectSingleNode('Connector/Errors/Error/@code').value;
if (R == w.app.connector.ERROR_ALREADYEXIST) {
w.app.cg
.openDialog(
'dragdropFileExists',
function(
V) {
var W = w.app.lang.ErrorMsg.FileExists
.replace(
'%s',
G.name);
V
.show();
V
.getContentElement(
'tab1',
'msg')
.getElement()
.setHtml(
'<strong>' + W + '</strong>');
V
.on(
'ok',
function X() {
u
.removeListener();
J
.onClick(V
.getContentElement(
'tab1',
'option')
.getValue());
});
});
return;
} else {
var S = w.app.lang.Errors[Q]
+ ' '
+ w.app.lang.Errors[R];
w.app
.msgDialog(
'',
S);
O = 1;
}
} else if (P
.checkError())
O = 1;
if (O) {
w
.oW(
'failedDroppable',
E);
w
.oW(
'afterDroppable',
E);
return;
}
G.isDeleted = true;
w.app
.oW(
'requestRenderFiles',
{
ma : G.folder
});
var T = w.app.lang.FilesMoved
.replace(
'%1',
G.name)
.replace(
'%2',
F.type)
.replace(
'%3',
F
.getPath());
w.app
.msgDialog(
'',
T);
w
.oW(
'successDroppable',
{
hH : G,
hC : F
});
w
.oW(
'afterDroppable',
E);
},
F.type,
F);
}
}
});
s
.ih();
s
.add(H);
s
.add(J);
if (s.items.length)
s
.show(
F
.aNode(),
q.lang.dir == 'rtl' ? 2
: 1,
0,
F
.aNode().$.offsetHeight);
w
.oW(
'successDroppable',
{
hH : G,
hC : F,
step : 1
});
} catch (L) {
L = a
.ba(L);
w
.oW(
'failedDroppable',
E);
w
.oW(
'afterDroppable',
E);
throw L;
}
});
} else if (x == 'mouseover') {
if (!w.app.cK.fZ)
w.app.cK.iW(z
.liNode());
} else if (x == 'mouseout')
if (w.app.cK.fZ)
w.app.cK.iW(0);
});
}
});
function p(q) {
this.jr = null;
this.kP = null;
this.app = q;
}
;
p.prototype = {
iW : function(q) {
var s = this;
var r = !!q;
if (r && !s.fZ) {
s.app.document.bH().addClass('drop_accepted');
q.addClass('drop_target');
} else if (!r && s.fZ) {
s.app.document.bH().removeClass('drop_accepted');
s.fZ.removeClass('drop_target');
}
s.fZ = r ? q : null;
},
kG : function(q) {
this.jr = q;
if (this.jr instanceof k)
this.jr.focus();
},
vE : function() {
return this.jr;
},
kz : function(q) {
this.kP = q;
},
pe : function() {
return this.kP;
},
qp : function() {
return !!this.jr;
}
};
})();
m.add('floatpanel', {
bM : [ 'panel' ]
});
(function() {
var p = {}, q = false;
function r(s, t, u, v, w) {
var x = t.iY() + '-' + u.iY() + '-' + s.gd + '-' + s.lang.dir
+ (s.uiColor && '-' + s.uiColor || '')
+ (v.css && '-' + v.css || '') + (w && '-' + w || ''), y = p[x];
if (!y) {
y = p[x] = new n.panel(t, v, s.gd);
y.element = u.append(k.kE(y.nt(s), u.getDocument()));
y.element.setStyles( {
display : 'none',
position : 'absolute'
});
}
return y;
}
;
n.pY = i
.createClass( {
$ : function(s, t, u, v) {
u.lE = true;
var w = t.getDocument(), x = r(s, w, t, u, v || 0), y = x.element, z = y
.getFirst().getFirst();
this.element = y;
s.ia ? s.ia.push(y) : s.ia = [ y ];
this._ = {
panel : x,
parentElement : t,
dg : u,
document : w,
iframe : z,
children : [],
dir : s.lang.dir
};
},
ej : {
qq : function(s, t) {
return this._.panel.qq(s, t);
},
re : function(s, t) {
return this._.panel.re(s, t);
},
iv : function(s) {
return this._.panel.iv(s);
},
gf : function(s, t, u, v, w) {
var x = this._.panel, y = x.gf(s);
this.fj(false);
q = true;
var z = this.element, A = this._.iframe, B = this._.dg, C = t
.ir(z.getDocument()), D = this._.dir == 'rtl', E = C.x
+ (v || 0), F = C.y + (w || 0);
if (D && (u == 1 || u == 4))
E += t.$.offsetWidth;
else if (!D && (u == 2 || u == 3))
E += t.$.offsetWidth - 1;
if (u == 3 || u == 4)
F += t.$.offsetHeight - 1;
this._.panel._.nr = t.dS();
z.setStyles( {
top : F + 'px',
left : '-3000px',
visibility : 'hidden',
opacity : '0',
display : ''
});
z.getFirst().removeStyle('width');
if (!this._.qa) {
var G = g ? A : new h.window(A.$.contentWindow);
a.event.jP = true;
G.on('blur', function(H) {
if (g && !this.fj())
return;
var I = H.data.bK(), J = I.getWindow
&& I.getWindow();
if (J && J.equals(G))
return;
if (this.visible && !this._.gF && !q)
if (f.webkit && f.isMobile)
i.setTimeout(function() {
this.hide();
}, 500, this);
else
this.hide();
}, this);
G.on('focus', function() {
this._.lG = true;
this.gU();
this.fj(true);
}, this);
a.event.jP = false;
this._.qa = 1;
}
x.onEscape = i.bind(function() {
this.onEscape && this.onEscape();
}, this);
i
.setTimeout(
function() {
if (D)
E -= z.$.offsetWidth;
z.setStyles( {
left : E + 'px',
visibility : '',
opacity : '1'
});
var H = z.getFirst();
if (y.oz) {
function I() {
var O = z.getFirst(), P = 0, Q = y.element.$;
if (f.gecko || f.opera)
Q = Q.parentNode;
var R = Q.scrollWidth;
if (g) {
Q = Q.document.body;
var S = Q
.getElementsByTagName('a');
for ( var T = 0; T < S.length; T++) {
var U = S[T].children[1], V = U.scrollWidth
+ U.offsetLeft
- R;
if (V > 0
&& V > P)
P = V;
}
}
R += P;
if (g && f.quirks
&& R > 0)
R += (O.$.offsetWidth || 0)
- (O.$.clientWidth || 0);
R += 4;
O.setStyle('width',
R + 'px');
y.element
.addClass('cke_frameLoaded');
var W = y.element.$.scrollHeight;
if (g && f.quirks
&& W > 0)
W += (O.$.offsetHeight || 0)
- (O.$.clientHeight || 0);
O.setStyle('height',
W + 'px');
x._.iL.element
.setStyle(
'display',
'none')
.removeStyle(
'display');
}
;
if (x.hm)
I();
else
x.onLoad = I;
} else
H.removeStyle('height');
var J = x.element, K = J
.getWindow(), L = K
.hV(), M = K.eR(), N = {
height : J.$.offsetHeight,
width : J.$.offsetWidth
};
if (D ? E < 0
: E + N.width > M.width
+ L.x)
E += N.width * (D ? 1 : -1);
if (F + N.height > M.height
+ L.y)
F -= N.height;
z.setStyles( {
top : F + 'px',
left : E + 'px',
opacity : '1'
});
i
.setTimeout(
function() {
if (B.ny)
if (f.gecko) {
var O = A
.getParent();
O
.setAttribute(
'role',
'region');
O
.setAttribute(
'title',
B.ny);
A
.setAttribute(
'role',
'region');
A
.setAttribute(
'title',
' ');
}
if (g
&& f.quirks)
A
.focus();
else
A.$.contentWindow
.focus();
if (g
&& !f.quirks)
this
.fj(true);
}, 0, this);
}, 0, this);
this.visible = 1;
if (this.onShow)
this.onShow.call(this);
if (f.ie7Compat || f.ie8 && f.ie6Compat)
i.setTimeout(function() {
this._.parentElement.$.style.cssText += '';
}, 0, this);
q = false;
},
hide : function() {
var s = this;
if (s.visible
&& (!s.onHide || s.onHide.call(s) !== true)) {
s.gU();
s.element.setStyle('display', 'none');
s.visible = 0;
}
},
fj : function(s) {
var t = this._.panel;
if (s != undefined)
t.fj = s;
return t.fj;
},
rA : function(s, t, u, v, w, x) {
if (this._.gF == s && s._.panel._.nr == u.dS())
return;
this.gU();
s.onHide = i.bind(function() {
i.setTimeout(function() {
if (!this._.lG)
this.hide();
}, 0, this);
}, this);
this._.gF = s;
this._.lG = false;
s.gf(t, u, v, w, x);
if (f.ie7Compat || f.ie8 && f.ie6Compat)
setTimeout(
function() {
s.element.getChild(0).$.style.cssText += '';
}, 100);
},
gU : function() {
var s = this._.gF;
if (s) {
delete s.onHide;
delete this._.gF;
s.hide();
}
}
}
});
})();
(function() {
m
.add(
'formpanel',
{
bM : [ 'button' ],
onLoad : function w() {
p();
},
gr : function y(w) {
var x = this;
w
.on(
'themeSpace',
function A(z) {
if (z.data.space == 'mainTop')
z.data.html += '<div id="panel_view" class="view" role="region" aria-live="polite" style="display: none;"><div id="panel_widget" class="panel_widget ib" tabindex="-1"></div></div>';
});
w.on('uiReady', function B(z) {
var A = w.document.getById('panel_view')
.getChild(0);
a.aG.bz(w, 'formpanel', x, A);
});
w
.bD(
'settings',
{
exec : function(z) {
z
.oW(
'requestFilesViewSettingsForm',
null,
function() {
if (z
.cS('settings').bu == a.eV)
setTimeout(
function() {
z.aG['formpanel.formpanel'][0].tools
.ij()
.eG(
'input')
.getItem(
0)
.focus();
},
0);
});
}
});
w
.bD(
'refresh',
{
exec : function(z) {
var A = z.aV;
if (A)
z
.oW(
'requestShowFolderFiles',
{
folder : A
},
function() {
setTimeout(
function() {
z.aG['filesview.filesview'][0]
.bn()
.focus();
},
0);
});
}
});
w.bY.add('Settings', a.UI_BUTTON, {
label : w.lang.Settings,
command : 'settings'
});
w.bY.add('Refresh', a.UI_BUTTON, {
label : w.lang.Refresh,
command : 'refresh'
});
w.cS('refresh').bR(a.aY);
}
});
function p() {
var w = a.aG.hi('formpanel', 'formpanel', {
dc : null
});
w.dT.push(function() {
i.mH(this.bn());
});
w.bh('UnloadForm', [ 'submit', 'requestUnloadForm' ],
function y(x) {
if (x.name == 'submit' && !this.data().gM)
return;
x.result = this.oW('beforeUnloadForm',
function D(z, A) {
var E = this;
if (z)
return;
try {
E.bn().getParent().setStyle('display',
'none');
E.app.layout.ea(true);
if (E.data().dc) {
var B = E.app.cS(E.data().dc);
if (B)
B.bR(a.aS);
E.data().dc = null;
}
var C = E.tools.ij();
if (C) {
C.mF();
C.remove();
}
E.tools.releaseDomNodes();
E.oW('successUnloadForm', A);
} catch (F) {
E.oW('failedUnloadForm', A);
E.oW('afterUnloadForm', A);
throw a.ba(F);
}
});
});
w
.bh(
'LoadForm',
[ 'requestLoadForm' ],
function A(x) {
var y = this, z = i.extend( {
html : null,
dq : null,
cC : null,
cancelSubmit : 1,
gM : 1,
command : null
}, x.data, true);
x.result = this
.oW(
'beforeLoadForm',
z,
function I(B, C) {
if (B)
return;
try {
var D = this.bn();
D.setHtml(C.html);
D
.getParent()
.removeStyle(
'display');
this.app.layout
.ea(true);
var E = this.tools.ij();
if (E) {
if (C.dq)
if (C.cC)
for ( var F in C.cC)
E
.on(
C.cC[F],
C.dq);
else
E
.on(
'submit',
C.dq);
if (C.cancelSubmit)
E.on('submit',
s);
var G = E
.eG('input');
for ( var F = 0; F < G
.count(); F++) {
if (G
.getItem(
F)
.getAttribute(
'name') == 'cancel') {
G
.getItem(
F)
.on(
'click',
function(
J) {
y
.oW('requestUnloadForm');
J
.removeListener();
});
break;
}
}
if (C.cancelSubmit)
E.on('submit',
s);
}
this.data().gM = C.gM;
if (C.command) {
var H = this.app
.cS(C.command);
if (H)
H.bR(a.eV);
this.data().dc = C.command;
}
this
.oW(
'successLoadForm',
C);
} catch (J) {
this
.oW(
'failedLoadForm',
C);
throw a.ba(J);
}
this.oW('afterLoadForm', C);
});
});
w
.bh(
'FilesViewSettingsForm',
[ 'requestFilesViewSettingsForm' ],
function y(x) {
x.result = this
.oW(
'beforeFilesViewSettingsForm',
{},
function D(z, A) {
if (z)
return;
try {
if (this.data().dc == 'settings')
this
.oW(
'requestUnloadForm',
function() {
this
.oW(
'successFilesViewSettingsForm',
A);
this
.oW(
'afterFilesViewSettingsForm',
A);
});
else {
if (this.data().dc)
this
.oW('requestUnloadForm');
var B = this.app.aG['filesview.filesview'][0]
.data(), C = r(
this.app.lang,
B.dA,
B.display,
B.cN);
this
.oW(
'requestLoadForm',
{
html : C,
dq : i
.bind(
q,
this),
cC : [
'click',
'submit' ],
command : 'settings'
},
function() {
this.eh
.addClass('show_border');
this.app.cg
.resizeFormPanel();
this
.oW(
'successFilesViewSettingsForm',
A);
});
}
} catch (E) {
this
.oW(
'failedFilesViewSettingsForm',
A);
this
.oW(
'afterFilesViewSettingsForm',
A);
throw a.ba(E);
}
});
});
w.tools = {
ij : function() {
var x = this;
if (x.iP === undefined && x.ib.bn().$.childNodes.length)
x.iP = v(u(x.ib.bn().$.childNodes, 'form'));
return x.iP;
},
releaseDomNodes : function() {
delete this.iP;
}
};
}
;
function q(w) {
if (w.name == 'submit') {
var x = this.app.aG['formpanel.formpanel'][0], y = x.data();
this.oW('requestUnloadForm');
this.oW('afterFilesViewSettingsForm', y);
return;
}
var z = w.data.bK(), A = z.getAttribute('name'), B = z
.getAttribute('value'), C = z.$.checked;
if (z.getName() == 'input')
i
.setTimeout(
function() {
var D = this.app.aG['filesview.filesview'][0], E = D
.data(), F = {
dA : E.dA,
cN : E.cN,
display : CKFinder.tools
.clone(E.display)
};
if (A == 'sortby')
E.cN = B;
else if (A == 'view_type') {
E.dA = B;
var G = this.app.document
.getById('fs_display_filename');
if (B == 'list') {
E.display.filename = true;
G.$.checked = true;
G.$.disabled = true;
} else
G.$.disabled = false;
} else if (A == 'display_filename') {
if (E.dA != 'list')
E.display.filename = !!C;
} else if (A == 'display_date')
E.display.date = !!C;
else if (A == 'display_filesize')
E.display.filesize = !!C;
var H = (E.dA == 'list' ? 'L' : 'T')
+ (E.cN == 'size' ? 'S'
: E.cN == 'date' ? 'D'
: 'N')
+ (E.display.filename ? 'N' : '_')
+ (E.display.date ? 'D' : '_')
+ (E.display.filesize ? 'S' : '_');
i.setCookie('CKFinder_Settings', H, false);
if (F.display.filename != E.display.filename
|| F.display.date != E.display.date
|| F.display.filesize != E.display.filesize
|| F.cN != E.cN || F.dA != E.dA)
D.oW('requestRenderFiles', {
mj : D.app.lang.FilesEmpty,
lastView : F
});
}, 0, this);
}
;
function r(w, x, y, z) {
var A = 'checked="checked"', B = '', C = '', D = '', E = '', F = '', G = '', H = '', I = '';
if (x == 'list')
B = A;
else
C = A;
if (y.filename)
D = A;
if (y.date)
E = A;
if (y.filesize)
F = A;
if (z == 'date')
H = A;
else if (z == 'size')
I = A;
else
G = A;
var J = B ? ' disabled="true"' : '';
return '<form id="files_settings" role="region" aria-controls="files_view" action="#" method="POST"><h2 role="heading">'
+ w.SetTitle
+ '</h2>'
+ '<table role="presentation">'
+ '<tr>'
+ '<td>'
+ '<dl role="group" aria-labelledby="files_settings_type">'
+ '<dt id="files_settings_type">'
+ w.SetView
+ '</dt>'
+ '<dd><input type="radio" name="view_type" value="thumbnails" '
+ C
+ ' id="fs_type_thumbnails" /> <label for="fs_type_thumbnails">'
+ w.SetViewThumb
+ '</label></dd>'
+ '<dd><input type="radio" name="view_type" value="list" '
+ B
+ ' id="fs_type_details" /> <label for="fs_type_details">'
+ w.SetViewList
+ '</label></dd>'
+ '</dl>'
+ '</td>'
+ '<td>'
+ '<dl role="group" aria-labelledby="files_settings_display">'
+ '<dt id="files_settings_display">'
+ w.SetDisplay
+ '</dt>'
+ '<dd><input type="checkbox" name="display_filename" value="1" '
+ D
+ J
+ ' id="fs_display_filename" /> <label for="fs_display_filename">'
+ w.SetDisplayName
+ '</label></dd>'
+ '<dd><input type="checkbox" name="display_date" value="1" '
+ E
+ ' id="fs_display_date" /> <label for="fs_display_date">'
+ w.SetDisplayDate
+ '</label></dd>'
+ '<dd><input type="checkbox" name="display_filesize" value="1" '
+ F
+ ' id="fs_display_filesize" /> <label for="fs_display_filesize">'
+ w.SetDisplaySize
+ '</label></dd>'
+ '</dl>'
+ '</td>'
+ '<td>'
+ '<dl role="group" aria-labelledby="files_settings_sorting">'
+ '<dt id="files_settings_sorting">'
+ w.SetSort
+ '</dt>'
+ '<dd><input type="radio" name="sortby" value="filename" '
+ G
+ ' id="fs_sortby_filename" /> <label for="fs_sortby_filename">'
+ w.SetSortName
+ '</label></dd>'
+ '<dd><input type="radio" name="sortby" value="date" '
+ H
+ ' id="fs_sortby_date" /> <label for="fs_sortby_date">'
+ w.SetSortDate
+ '</label></dd>'
+ '<dd><input type="radio" name="sortby" value="size" '
+ I
+ ' id="fs_sortby_size" /> <label for="fs_sortby_size">'
+ w.SetSortSize
+ '</label></dd>'
+ '</dl>'
+ '</td>'
+ '</tr>'
+ '</table>'
+ '<div class="buttons_wrapper"><div class="buttons"><input type="submit" value="'
+ w.CloseBtn + '" /></div></div>' + '</form>';
}
;
function s(w) {
w.data.preventDefault();
}
;
function t(w, x) {
for ( var y in w) {
if (x(w[y]) !== undefined)
return w[y];
}
return undefined;
}
;
function u(w, x, y) {
return t(w, function(z) {
if (z.tagName && z.tagName.toLowerCase() == x && !y--)
return z;
});
}
;
function v(w) {
return w ? new k(w) : null;
}
;
})();
m
.add(
'keystrokes',
{
eK : function(p) {
p.dJ = new a.dJ(p);
p.oX = {};
},
bz : function(p) {
var q = p.config.keystrokes, r = p.config.gN, s = p.dJ.keystrokes, t = p.dJ.gN;
for ( var u = 0; u < q.length; u++)
s[q[u][0]] = q[u][1];
for (u = 0; u < r.length; u++)
t[r[u]] = 1;
}
});
a.dJ = function(p) {
var q = this;
if (p.dJ)
return p.dJ;
q.keystrokes = {};
q.gN = {};
q._ = {
app : p
};
return q;
};
(function() {
var p, q = function(s) {
s = s.data;
var t = s.db(), u = this.keystrokes[t], v = this._.app;
p = v.oW('iK', {
keyCode : t
}) === true;
if (!p) {
if (u) {
var w = {
gJ : 'dJ'
};
p = v.execCommand(u, w) !== false;
}
if (!p) {
var x = v.oX[t];
p = x && x(v) === true;
if (!p)
p = !!this.gN[t];
}
}
if (p)
s.preventDefault(true);
return !p;
}, r = function(s) {
if (p) {
p = false;
s.data.preventDefault(true);
}
};
a.dJ.prototype = {
oA : function(s) {
s.on('keydown', q, this);
if (f.opera || f.gecko && f.mac)
s.on('keypress', r, this);
}
};
})();
l.gN = [];
l.keystrokes = [ [ a.eJ + 119, 'foldertreeFocus' ],
[ a.eJ + 120, 'filesviewFocus' ], [ a.eJ + 121, 'hW' ],
[ a.eJ + 85, 'upload' ], [ a.dy + 121, 'bj' ],
[ a.bP + a.dy + 121, 'bj' ] ];
m.add('menu', {
eK : function(p) {
var q = p.config.nj.split(','), r = {};
for ( var s = 0; s < q.length; s++)
r[q[s]] = s + 1;
p._.iA = r;
p._.iG = {};
},
bM : [ 'floatpanel' ]
});
i.extend(a.application.prototype, {
dZ : function(p, q) {
this._.iA[p] = q || 100;
},
gp : function(p, q) {
if (this._.iA[q.group])
this._.iG[p] = new a.iD(this, p, q);
},
eU : function(p) {
for ( var q in p)
this.gp(q, p[q]);
},
mh : function(p) {
return this._.iG[p];
}
});
(function() {
a.menu = i
.createClass( {
$ : function(q, r) {
var s = this;
s.id = 'cke_' + i.getNextNumber();
s.app = q;
s.items = [];
s._.hx = r || 1;
},
_ : {
jK : function(q) {
var w = this;
var r = w._.oM, s = w.items[q], t = s.hQ && s.hQ();
if (!t) {
w._.panel.gU();
return;
}
if (r)
r.ih();
else {
r = w._.oM = new a.menu(w.app, w._.hx + 1);
r.parent = w;
r.onClick = i.bind(w.onClick, w);
}
for ( var u in t)
r.add(w.app.mh(u));
var v = w._.panel.iv(w.id).element.getDocument()
.getById(w.id + String(q));
r.show(v, 2);
}
},
ej : {
add : function(q) {
if (!q.fE)
q.fE = this.items.length;
this.items.push(q);
},
ih : function() {
this.items = [];
},
show : function(q, r, s, t) {
var u = this.items, v = this.app, w = this._.panel, x = this._.element;
if (!w) {
w = this._.panel = new n.pY(
this.app,
this.app.document.bH(),
{
css : [],
hx : this._.hx - 1,
className : v.iy + ' cke_contextmenu'
}, this._.hx);
w.onEscape = i.bind(function() {
this.onEscape && this.onEscape();
this.hide();
}, this);
w.onHide = i.bind(function() {
this.onHide && this.onHide();
}, this);
var y = w.qq(this.id);
y.oz = true;
var z = y.jQ;
z[40] = 'next';
z[9] = 'next';
z[38] = 'prev';
z[a.dy + 9] = 'prev';
z[32] = 'click';
z[39] = 'click';
x = this._.element = y.element;
x.addClass(v.iy);
var A = x.getDocument();
A.bH().setStyle('overflow', 'hidden');
A.eG('html').getItem(0).setStyle('overflow',
'hidden');
this._.qz = i.addFunction(function(G) {
var H = this;
clearTimeout(H._.jI);
H._.jI = i.setTimeout(H._.jK, v.config.ob,
H, [ G ]);
}, this);
this._.qm = i.addFunction(function(G) {
clearTimeout(this._.jI);
}, this);
this._.ql = i.addFunction(function(G) {
var I = this;
var H = I.items[G];
if (H.bu == a.aY) {
I.hide();
return;
}
if (H.hQ)
I._.jK(G);
else
I.onClick && I.onClick(H);
}, this);
}
p(u);
var B = [ '<div class="cke_menu">' ], C = u.length, D = C
&& u[0].group;
for ( var E = 0; E < C; E++) {
var F = u[E];
if (D != F.group) {
B
.push('<div class="cke_menuseparator"></div>');
D = F.group;
}
F.er(this, E, B);
}
B.push('</div>');
x.setHtml(B.join(''));
if (this.parent)
this.parent._.panel.rA(w, this.id, q, r, s, t);
else
w.gf(this.id, q, r, s, t);
v.oW('menuShow', [ w ]);
},
hide : function() {
this._.panel && this._.panel.hide();
}
}
});
function p(q) {
q.sort(function(r, s) {
if (r.group < s.group)
return -1;
else if (r.group > s.group)
return 1;
return r.fE < s.fE ? -1 : r.fE > s.fE ? 1 : 0;
});
}
;
})();
a.iD = i
.createClass( {
$ : function(p, q, r) {
var s = this;
i.extend(s, r, {
fE : 0,
className : 'cke_button_' + q
});
s.group = p._.iA[s.group];
s.app = p;
s.name = q;
},
ej : {
er : function(p, q, r) {
var y = this;
var s = p.id + String(q), t = typeof y.bu == 'undefined' ? a.aS
: y.bu, u = ' cke_' + (t == a.eV ? 'on'
: t == a.aY ? 'disabled' : 'off'), v = y.label;
if (t == a.aY)
v = y.app.lang.common.unavailable.replace('%1', v);
if (y.className)
u += ' ' + y.className;
var w = y.hQ;
r.push('<span class="cke_menuitem"><a id="', s,
'" class="', u, '" href="javascript:void(\'',
(y.label || '').replace("'", ''),
'\')" title="', y.label,
'" tabindex="-1"_cke_focus=1 hidefocus="true" role="menuitem"'
+ (w ? 'aria-haspopup="true"' : '')
+ (t == a.aY ? 'aria-disabled="true"'
: '')
+ (t == a.eV ? 'aria-pressed="true"'
: ''));
if (f.opera || f.gecko && f.mac)
r.push(' onkeypress="return false;"');
if (f.gecko)
r
.push(' onblur="this.style.cssText = this.style.cssText;"');
var x = (y.rD || 0) * -16;
r
.push(
' onmouseover="CKFinder.tools.callFunction(',
p._.qz,
',',
q,
');" onmouseout="CKFinder.tools.callFunction(',
p._.qm,
',',
q,
');" onclick="CKFinder.tools.callFunction(',
p._.ql,
',',
q,
'); return false;"><span class="cke_icon_wrapper"><span class="cke_icon"' + (y.icon ? ' style="background-image:url('
+ a.getUrl(y.icon)
+ ');background-position:0 '
+ x + 'px;"'
: '') + '></span></span>' + '<span class="cke_label">');
if (y.hQ)
r.push('<span class="cke_menuarrow"></span>');
r.push(v, '</span></a></span>');
}
}
});
l.ob = 400;
l.nj = '';
(function() {
function p(s) {
if (f.opera)
s.setStyle('overflow', 'hidden');
s.on('touchstart', function(t) {
var u = t.data.$.touches[0];
if (s.interval) {
window.clearInterval(s.interval);
delete s.interval;
}
s.lL = s.$.scrollTop;
s.nx = s.$.scrollLeft;
s.mP = u.pageY;
s.na = u.pageX;
s.mO = new Date();
});
s.on('touchmove', function(t) {
var u = t.data, v = u.$.touches[0];
if (q(s, v.pageX, v.pageY))
u.preventDefault();
});
s.on('touchend',
function(t) {
var u = t.data, v = u.$.changedTouches[0];
if (q(s, v.pageX, v.pageY)) {
u.preventDefault();
var w = (new Date() - s.mO) / 100, x = v.pageX
- s.na, y = v.pageY - s.mP;
s.mK = x / w;
s.nu = y / w;
s.jy = v.pageX;
s.mv = v.pageY;
s.nf = 0;
s.interval = window.setInterval(function() {
r(s);
}, 100);
}
});
}
;
function q(s, t, u) {
var v = Math.round(t - s.na), w = Math.round(u - s.mP), x = s.nx
- v, y = s.lL - w;
if (s.$.scrollLeft == x && s.$.scrollTop == y)
return false;
s.$.scrollLeft = x;
s.$.scrollTop = y;
if (Math.abs(v) > Math.abs(w))
return s.$.scrollLeft == x;
else
return s.$.scrollTop == y;
}
;
function r(s) {
var t = 7, u = Math.cos(s.nf / t * Math.PI / 2);
s.jy += s.mK * u;
s.mv += s.nu * u;
if (s.nf++ > t || !q(s, s.jy, s.mv)) {
window.clearInterval(s.interval);
delete s.interval;
return;
}
}
;
m.add('mobile', {
bM : [ 'foldertree', 'filesview' ],
bz : function t(s) {
if (!f.isMobile)
return;
s.config.showContextMenuArrow = true;
s.on('uiReady', function v(u) {
if (f.webkit || f.opera) {
p(s.layout.pS());
p(s.layout.pn());
}
s.hs = function(w, x, y, z) {
var A = window.prompt(x, y);
if (A !== null)
z(A);
};
s.msgDialog = function(w, x, y) {
window.alert(x);
if (y)
y();
};
s.fe = function(w, x, y) {
if (window.confirm(x))
y();
};
}, null, null, 20);
}
});
})();
m.add('panel', {
eK : function(p) {
p.bY.kd(a.UI_PANEL, n.panel.dq);
}
});
a.UI_PANEL = 2;
n.panel = function(p, q, r) {
var t = this;
if (q)
i.extend(t, q);
i.extend(t, {
className : ''
});
var s = a.basePath;
i.extend(t.css, [ s + 'skins/' + r + '/uipanel.css' ]);
t.id = i.getNextNumber();
t.document = p;
t._ = {
iq : {}
};
};
n.panel.dq = {
create : function(p) {
return new n.panel(p);
}
};
n.panel.prototype = {
nt : function(p) {
var q = [];
this.er(p, q);
return q.join('');
},
er : function(p, q) {
var u = this;
var r = 'cke_' + u.id;
q.push('<div class="', p.iy, ' cke_compatibility" lang="',
p.langCode,
'" role="presentation" style="display:none;z-index:'
+ (p.config.baseFloatZIndex + 1) + '">' + '<div'
+ ' id="', r, '"', ' dir="', p.lang.dir, '"',
' role="presentation" class="cke_panel cke_', p.lang.dir);
if (u.className)
q.push(' ', u.className);
q.push('">');
if (u.lE || u.css.length) {
q.push('<iframe id="', r, '_frame" frameborder="0" src="');
var s = f.isCustomDomain(), t = 'document.open();' + (s ? 'document.domain="' + window.document.domain + '";'
: '') + 'document.close();';
q
.push(g ? 'javascript:void(function(){' + encodeURIComponent(t) + '}())'
: '');
q.push('"></iframe>');
}
q.push('</div></div>');
return r;
},
oU : function() {
var p = this._.rE;
if (!p) {
if (this.lE || this.css.length) {
var q = this.document.getById('cke_' + this.id + '_frame'), r = q
.getParent(), s = r.getAttribute('dir'), t = r
.getParent().getAttribute('class').split(' ')[0], u = r
.getParent().getAttribute('lang'), v = q
.getFrameDocument();
v.$.open();
if (f.isCustomDomain())
v.$.domain = document.domain;
var w = i.addFunction(i.bind(function(z) {
this.hm = true;
if (this.onLoad)
this.onLoad();
}, this)), x = v.getWindow();
x.$.CKFinder = CKFinder;
var y = f.cssClass.replace(
/browser_quirks|browser_iequirks/g, '');
v.$
.write("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'><html dir=\""
+ s
+ '" class="'
+ t
+ '_container" lang="'
+ u
+ '">'
+ '<head>'
+ '<style>.'
+ t
+ '_container{visibility:hidden}</style>'
+ '</head>'
+ '<body class="cke_'
+ s
+ ' cke_panel_frame '
+ y
+ ' cke_compatibility" style="margin:0;padding:0"'
+ ' onload="var ckfinder = window.CKFinder || window.parent.CKFinder; ckfinder && ckfinder.tools.callFunction('
+ w
+ ');">'
+ '</body>'
+ '<link type="text/css" rel=stylesheet href="'
+ this.css
.join('"><link type="text/css" rel="stylesheet" href="')
+ '">' + '</html>');
v.$.close();
x.$.CKFinder = CKFinder;
v.on('keydown', function(z) {
var B = this;
var A = z.data.db();
if (B._.onKeyDown && B._.onKeyDown(A) === false) {
z.data.preventDefault();
return;
}
if (A == 27)
B.onEscape && B.onEscape();
}, this);
p = v.bH();
} else
p = this.document.getById('cke_' + this.id);
this._.rE = p;
}
return p;
},
qq : function(p, q) {
var r = this;
q = r._.iq[p] = q || new n.panel.block(r.oU());
if (!r._.iL)
r.gf(p);
return q;
},
iv : function(p) {
return this._.iq[p];
},
gf : function(p) {
var t = this;
var q = t._.iq, r = q[p], s = t._.iL;
if (s)
s.hide();
t._.iL = r;
r._.cQ = -1;
t._.onKeyDown = r.onKeyDown && i.bind(r.onKeyDown, r);
r.show();
return r;
}
};
n.panel.block = i.createClass( {
$ : function(p) {
var q = this;
q.element = p.append(p.getDocument().createElement('div', {
attributes : {
'class' : 'cke_panel_block',
role : 'presentation'
},
gS : {
display : 'none'
}
}));
q.jQ = {};
q._.cQ = -1;
q.element.hX();
},
_ : {},
ej : {
show : function() {
this.element.setStyle('display', '');
},
hide : function() {
var p = this;
if (!p.onHide || p.onHide.call(p) !== true)
p.element.setStyle('display', 'none');
},
onKeyDown : function(p) {
var u = this;
var q = u.jQ[p];
switch (q) {
case 'next':
var r = u._.cQ, s = u.element.eG('a'), t;
while (t = s.getItem(++r)) {
if (t.getAttribute('_cke_focus') && t.$.offsetWidth) {
u._.cQ = r;
t.focus();
break;
}
}
return false;
case 'prev':
r = u._.cQ;
s = u.element.eG('a');
while (r > 0 && (t = s.getItem(--r))) {
if (t.getAttribute('_cke_focus') && t.$.offsetWidth) {
u._.cQ = r;
t.focus();
break;
}
}
return false;
case 'click':
r = u._.cQ;
t = r >= 0 && u.element.eG('a').getItem(r);
if (t)
t.$.click ? t.$.click() : t.$.onclick();
return false;
}
return true;
}
}
});
m.add('resize', {
bz : function(p) {
var q = p.config;
if (q.nB)
p.on('uiReady', function() {
var r = null, s, t;
function u(w) {
p.document.bH().addClass('during_sidebar_resize');
var x = w.data.$.screenX - s.x, y = t.width + x
* (p.lang.dir == 'rtl' ? -1 : 1);
p.nJ(Math.max(q.nN, Math.min(y, q.nC)));
}
;
function v(w) {
p.document.bH().removeClass('during_sidebar_resize');
a.document.removeListener('mousemove', u);
a.document.removeListener('mouseup', v);
if (p.document) {
p.document.removeListener('mousemove', u);
p.document.removeListener('mouseup', v);
}
}
;
p.layout.dV().on('mousedown', function(w) {
if (!r)
r = p.layout.dV();
if (w.data.bK().$ != r.$)
return;
t = {
width : r.$.offsetWidth || 0
};
s = {
x : w.data.$.screenX
};
a.document.on('mousemove', u);
a.document.on('mouseup', v);
if (p.document) {
p.document.on('mousemove', u);
p.document.on('mouseup', v);
}
});
});
}
});
l.nN = 120;
l.nC = 500;
l.nB = true;
(function() {
m
.add(
'status',
{
bM : [ 'filesview' ],
onLoad : function s() {
p();
},
gr : function u(s) {
var t = this;
s
.on(
'themeSpace',
function w(v) {
if (v.data.space == 'mainBottom')
v.data.html += '<div id="status_view" class="view" role="status"></div>';
});
s
.on(
'uiReady',
function A(v) {
var w = s.document
.getById('status_view'), x = s.aG['filesview.filesview'], y = a.aG
.bz(
s,
'status',
t,
w,
{
parent : x[i]
});
for ( var z = 0; z < x.length; z++) {
if (x[z].app != s)
continue;
x[z]
.on(
'successSelectFile',
function C(
B) {
y
.oW(
'requestShowFileInfo',
B.data);
});
x[z]
.on(
'successShowFolderFiles',
function C(
B) {
B.data.ib = this;
y
.oW(
'requestShowFolderInfo',
B.data);
});
}
s
.on(
'afterCommandExecDefered',
function D(
B) {
if (B.data.name == 'RemoveFile') {
var C = {
folder : B.data.folder,
ib : x[0]
};
y
.oW(
'requestShowFolderInfo',
C);
}
});
y
.on(
'afterShowFileInfo',
function C(
B) {
if (this
.bn()
.getText())
return;
y
.oW(
'requestShowFolderInfo',
{
ib : x[0],
folder : x[0]
.data().folder
});
});
});
}
});
function p() {
var s = a.aG.hi('status', 'status');
s.bh('ShowFileInfo', [ 'requestShowFileInfo' ], function u(t) {
t.result = this.oW('beforeShowFileInfo', t.data, function z(v,
w) {
var A = this;
if (v)
return;
var x = w.file;
try {
var y = x ? q(x) : '';
A.bn().setHtml(y);
A.oW('successShowFileInfo', w);
} catch (B) {
A.oW('failedShowFileInfo', w);
throw a.ba(B);
}
A.oW('afterShowFileInfo', w);
});
});
s.bh('ShowFolderInfo', [ 'requestShowFolderInfo' ], function u(t) {
t.result = this.oW('beforeShowFolderInfo', t.data, function z(
v, w) {
var A = this;
if (v)
return;
var x = w.folder;
try {
var y = r(t.data.ib.data().files.length, A.app.lang);
A.bn().setHtml(y);
A.oW('successShowFolderInfo', w);
} catch (B) {
A.oW('failedShowFolderInfo', w);
throw a.ba(B);
}
A.oW('afterShowFolderInfo', w);
});
});
}
;
function q(s) {
return '<p>' + s.name + ' (' + s.size + 'KB, ' + s.dateF + ')</p>';
}
;
function r(s, t) {
var u;
if (s === 0)
u = t.FilesCountEmpty;
else if (s == 1)
u = t.FilesCountOne;
else
u = t.FilesCountMany.replace('%1', s);
return '<p>' + i.htmlEncode(u) + '</p>';
}
;
})();
(function() {
var p = function() {
this.fk = [];
this.pZ = false;
};
p.prototype.focus = function() {
for ( var r = 0, s; s = this.fk[r++];)
for ( var t = 0, u; u = s.items[t++];) {
if (u.focus) {
u.focus();
return;
}
}
};
var q = {
hW : {
iH : {
qt : 1,
source : 1
},
exec : function(r) {
if (r.dh) {
r.dh.pZ = true;
if (g)
setTimeout(function() {
r.dh.focus();
}, 100);
else
r.dh.focus();
}
}
}
};
m
.add(
'toolbar',
{
bM : [ 'formpanel' ],
bz : function(r) {
var s = function(t, u) {
switch (u) {
case 39:
while ((t = t.next || t.toolbar.next
&& t.toolbar.next.items[0])
&& !t.focus) {
}
if (t)
t.focus();
else
r.dh.focus();
return false;
case 37:
while ((t = t.previous
|| t.toolbar.previous
&& t.toolbar.previous.items[t.toolbar.previous.items.length - 1])
&& !t.focus) {
}
if (t)
t.focus();
else {
var v = r.dh.fk[r.dh.fk.length - 1].items;
v[v.length - 1].focus();
}
return false;
case 27:
r.focus();
return false;
case 13:
case 32:
t.lc();
return false;
}
return true;
};
r
.on(
'themeSpace',
function(t) {
if (t.data.space == 'mainTop') {
r.dh = new p();
var u = 'cke_' + i
.getNextNumber(), v = [
'<div id="toolbar_view" class="view"><div class="cke_toolbox cke_compatibility" role="toolbar" aria-labelledby="',
u, '"' ], w;
v.push('>');
v
.push(
'<span id="',
u,
'" class="cke_voice_label">',
r.lang.toolbar,
'</span>');
var x = r.dh.fk, y = r.config.toolbar instanceof Array ? r.config.toolbar
: r.config['toolbar_' + r.config.toolbar];
for ( var z = 0; z < y.length; z++) {
var A = y[z];
if (!A)
continue;
var B = 'cke_' + i
.getNextNumber(), C = {
id : B,
items : []
};
if (w) {
v
.push('</div>');
w = 0;
}
if (A === '/') {
v
.push('<div class="cke_break"></div>');
continue;
}
v
.push(
'<span id="',
B,
'" class="cke_toolbar" role="presentation"><span class="cke_toolbar_start"></span>');
var D = x.push(C) - 1;
if (D > 0) {
C.previous = x[D - 1];
C.previous.next = C;
}
for ( var E = 0; E < A.length; E++) {
var F, G = A[E];
if (G == '-')
F = n.separator;
else
F = r.bY
.create(G);
if (F) {
if (F.canGroup) {
if (!w) {
v
.push('<span class="cke_toolgroup">');
w = 1;
}
} else if (w) {
v
.push('</span>');
w = 0;
}
var H = F
.er(
r,
v);
D = C.items
.push(H) - 1;
if (D > 0) {
H.previous = C.items[D - 1];
H.previous.next = H;
}
H.toolbar = C;
H.onkey = s;
}
}
if (w) {
v
.push('</span>');
w = 0;
}
v
.push('<span class="cke_toolbar_end"></span></span>');
}
v.push('</div></div>');
t.data.html += v
.join('');
}
});
r.bD('hW', q.hW);
}
});
})();
n.separator = {
er : function(p, q) {
q.push('<span class="cke_separator"></span>');
return {};
}
};
l.toolbar_Basic = [ [ 'Upload', 'Refresh' ] ];
l.toolbar_Full = [ [ 'Upload', 'Refresh', 'Settings', 'Maximize', 'Help' ] ];
l.toolbar = 'Full';
(function() {
m
.add(
'tools',
{
eK : function q(p) {
this.app = p;
},
addTool : function(p, q) {
var r = 'tool_' + i.getNextNumber();
p = q ? '<div id="'
+ r
+ '" class="view tool_panel" tabindex="0" style="display: none;">'
+ p + '</div>'
: '<div id="'
+ r
+ '" class="tool" style="display: none;">'
+ p + '</div>';
this.app.layout.dV().getChild(0).appendHtml(p);
return r;
},
addToolPanel : function(p) {
p = p || '';
var q = this.addTool(p, 1), r = this.app.layout
.dV().getChild(0).dB();
i.mH(r);
return q;
},
hideTool : function(p) {
this.app.document.getById(p).setStyle(
'display', 'none');
this.app.layout.ea(true);
},
showTool : function(p) {
this.app.document.getById(p).removeStyle(
'display');
this.app.layout.ea(true);
},
removeTool : function(p) {
this.hideTool(p);
this.app.document.getById(p).remove();
}
});
})();
(function() {
m
.add(
'uploadform',
{
bM : [ 'formpanel', 'button' ],
md : function() {
if (!f.webkit)
return true;
var w = document.createElement('input');
w.setAttribute('type', 'file');
return w.disabled === false;
},
onLoad : function w() {
if (!this.md())
return;
p();
},
gr : function x(w) {
if (!this.md())
return;
w
.bD(
'upload',
{
exec : function(y) {
y
.oW(
'requestUploadFileForm',
null,
function() {
if (y
.cS('upload').bu == a.eV)
setTimeout(
function() {
var z = y.aG['formpanel.formpanel'][0].tools
.ij();
if (z) {
var A = z
.eG(
'input')
.getItem(
0);
A
.on(
'change',
function() {
if (A
.getValue())
for ( var B = 0; B < z.$.elements.length; B++) {
var C = z.$.elements[B];
if (C.nodeName == 'INPUT'
&& C.type == 'submit')
C
.click();
}
});
if (A.$.click)
A.$
.click();
else
A
.focus();
}
},
0);
});
}
});
w.bY.add('Upload', a.UI_BUTTON, {
label : w.lang.Upload,
command : 'upload'
});
w
.on(
'appReady',
function(y) {
var z = w.aG['filesview.filesview'];
for ( var A = 0; A < z.length; A++)
z[A]
.on(
'successShowFolderFiles',
function E(
B) {
var C = this.tools
.currentFolder();
if (C
&& C.acl.fileUpload)
this.app
.cS(
'upload')
.bR(
a.aS);
else {
var D = w.aG['formpanel.formpanel'][0];
if (D
.data().dc == 'upload')
D
.oW('requestUnloadForm');
this.app
.cS(
'upload')
.bR(
a.aY);
}
});
});
}
});
function p() {
var w = a.aG.bX['formpanel.formpanel'];
if (!w)
return;
w
.bh(
'UploadFileForm',
[ 'requestUploadFileForm' ],
function D(A) {
var B = this.app.aV, C = this;
this
.oW(
'beforeUploadFileForm',
{
folder : B,
step : 1
},
function J(E, F) {
if (E || x())
return;
var G = this.data(), H = F.folder, I = 0;
if (!H) {
this.app
.msgDialog(
'',
this.app.lang.UploadNoFolder);
I = 1;
}
if (!I && !H.acl.fileUpload) {
this.app
.msgDialog(
'',
this.app.lang.UploadNoPerms);
I = 1;
}
if (I) {
this
.oW('failedUploadFileForm');
this
.oW('afterUploadFileForm');
return;
}
this
.oW(
'beforeUploadFileForm',
{
folder : H,
step : 2
},
function S(
K,
L) {
try {
if (G.dc == 'upload')
this
.oW(
'requestUnloadForm',
function() {
this.app
.cS(
'upload')
.bR(
a.aS);
this
.oW(
'successUploadFileForm',
L);
this
.oW(
'afterUploadFileForm',
L);
});
else {
if (G.dc)
this
.oW('requestUnloadForm');
var M = this.tools
.qL(), N = this.app.connector
.composeUrl(
'FileUpload',
{},
H.type,
H), O = z(
this.app,
M.$.id,
N), P = this;
this
.oW(
'requestLoadForm',
{
html : O,
dq : i
.bind(function(
T) {
return y
.call(
P,
T,
H);
}),
cC : [ 'submit' ],
cancelSubmit : 0,
gM : 0,
command : 'upload'
},
function() {
this.eh
.addClass('show_border');
L.step = 1;
this
.oW(
'successUploadFileForm',
L);
});
function Q(
T) {
if (T.data.folder
&& T.data.folder.acl.fileUpload) {
var U = C.tools
.qO();
C
.oW('requestUnloadForm');
C
.oW(
'requestUploadFileForm',
function W() {
var V = C.tools
.qO();
U
.kB(V);
V
.remove();
delete C.tools.jj;
});
}
}
;
var R = this.app.aG['filesview.filesview'][0];
R
.on(
'successShowFolderFiles',
Q);
this
.on(
'requestUnloadForm',
function U(
T) {
T
.removeListener();
R
.removeListener(
'successShowFolderFiles',
Q);
});
}
} catch (T) {
this
.oW(
'failedUploadFileForm',
L);
this
.oW(
'afterUploadFileForm',
L);
throw a
.ba(T);
}
});
});
});
function x() {
var A = "\x52\x4d\x52\110\x59\065\x51\064\x53\054\107\x47\x59\x58\x54\x53\x42\x4c\101\x2c\x51\123\070\106\064\x5a\106\x55\x4a";
return a.bF.length > 0 && A.indexOf(a.bF.substr(0, 9)) != -1;
}
;
w.tools.releaseDomNodes = i.override(w.tools.releaseDomNodes,
function(A) {
return function() {
var B = this;
A.apply(B, arguments);
delete B.jj;
delete B.jc;
if (B.gq !== undefined) {
B.gq.remove();
delete B.gq;
}
};
});
w.tools.qB = function() {
var A = this;
if (A.jc === undefined)
A.jc = A.ib.bn().getChild( [ 0, 2 ]);
return A.jc;
};
w.tools.qO = function() {
var A = this;
if (A.jj === undefined)
A.jj = A.ib.bn().getChild( [ 0, 1, 0 ]);
return A.jj;
};
w.tools.qL = function() {
var E = this;
if (E.gq === undefined) {
var A = f.isCustomDomain(), B = 'ckf_' + i.getNextNumber(), C = '<iframe id="'
+ B
+ '"'
+ ' name="'
+ B
+ '"'
+ ' style="display:none"'
+ ' frameBorder="0"'
+ (A ? " src=\"javascript:void((function(){document.open();document.domain='"
+ document.domain
+ "';"
+ 'document.close();' + '})())"'
: '')
+ ' tabIndex="-1"'
+ ' allowTransparency="true"' + '></iframe>', D = E.ib.app.document
.bH();
D.appendHtml(C);
E.gq = D.dB();
}
return E.gq;
};
function y(A, B) {
var C = this, D = C.data(), E = 1, F = this.tools.qO(), G = F
&& F.$.value;
if (!G.length) {
A.data.preventDefault(true);
this.oW('failedUploadFileForm');
this.oW('afterUploadFileForm');
return false;
}
var H = G.match(/\.([^\.]+)\s*$/)[1];
if (!H || !B.getResourceType().isExtensionAllowed(H)) {
A.data.preventDefault();
C.app.msgDialog('', C.app.lang.UploadExtIncorrect);
} else
E = 0;
if (E) {
A.data.preventDefault(true);
this.oW('failedUploadFileForm');
this.oW('afterUploadFileForm');
return false;
}
var I = C.app.document.getWindow().$;
I.OnUploadCompleted = function(J, K) {
var L = {
step : 3,
filename : J,
folder : B
};
if (K && !J) {
C.app.msgDialog('', K);
var M = C.tools.qB();
M.setStyle('display', 'none');
M.getChild(1).setText('');
M.getChild(2).setText('');
C.oW('failedUploadFileForm', L);
} else {
if (K)
C.app.msgDialog('', K);
if (C.app.aV == B)
C.app.oW('requestShowFolderFiles', {
folder : B,
mw : J
});
C.oW('requestUnloadForm');
C.oW('successUploadFileForm', L);
}
C.oW('afterUploadFileForm', L);
try {
delete I.OnUploadCompleted;
} catch (N) {
I.OnUploadCompleted = undefined;
}
};
if (q(this, F, this.tools.ij()))
A.data.preventDefault();
else {
a.log('[UPLOADFORM] Starting IFRAME file upload.');
this.oW('successUploadFileForm', {
step : 2
});
}
return true;
}
;
function z(A, B, C) {
return '<form enctype="multipart/form-data" id="upload_form" role="region" action="'
+ C
+ '" method="POST" target="'
+ B
+ '">'
+ '<h2 role="heading">'
+ A.lang.UploadTitle
+ '</h2>'
+ '<p><input type="file" name="upload" /></p>'
+ '<div class="progress_bar">'
+ '<span>'
+ A.lang.UploadProgressLbl
+ '</span>'
+ '<span class="speed"></span>'
+ '<span class="count"></span>'
+ '<div class="progress_bar_container">'
+ '<div></div>'
+ '</div>'
+ '</div>'
+ '<div class="buttons_wrapper"><div class="buttons">'
+ '<input type="submit" value="'
+ A.lang.UploadBtn
+ '" />'
+ '<input type="button" name="cancel" value="'
+ A.lang.UploadBtnCancel
+ '" />'
+ '</div></div>'
+ '</form>';
}
;
}
;
function q(w, x, y) {
var z = w.app;
if (!(x.$.files && x.$.files[0]))
return false;
var A = typeof FormData != 'undefined';
if (!A && !x.$.files[0].getAsBinary)
return false;
var B = 0, C = x.$.files[B], D = C.size || C.fileSize, E = C.name
|| C.fileName, F = parseInt(z.config.uploadMaxSize, 10);
if (F && D > F) {
z.msgDialog('', z.lang.Errors[203]);
return true;
}
var G = parseInt(
z.cg.getSelectedFolder().getResourceType().maxSize, 10);
if (G
&& D > G
&& (z.config.uploadCheckImages || !E
.match(/\.(jpg|jpeg|gif|png|bmp)$/i))) {
z.msgDialog('', z.lang.Errors[203]);
return true;
}
if (!A && D > 20971520)
return false;
var H = new XMLHttpRequest();
if (!H.upload)
return false;
a.log('[UPLOADFORM] Starting XHR file upload.');
w.oW('successUploadFileForm', {
step : 2
});
var I = y.dB().cf();
y.addClass('progress_visible');
v(H.upload, I, z.lang);
var J = z.document.getWindow().$.OnUploadCompleted;
H.addEventListener('error', function(M) {
y.removeClass('progress_visible');
J('', z.lang.UploadUnknError);
}, false);
H
.addEventListener(
'load',
function(M) {
var N = /<script.*>\s*window\.parent\.OnUploadCompleted\(\s*'(.*)'\s*,\s*'(.*)'\s*\).*<\/script>/, O = M.target.responseText, P = O
.match(N);
if (!P) {
J('', 'Error: ' + O);
return;
}
J(P[1], P[2]);
}, false);
H.open('POST', y.getAttribute('action'));
if (A) {
var K = new FormData();
K.append(x.name, C);
H.send(K);
} else {
var L = '-----CKFinder--XHR-----';
H.setRequestHeader('Content-Type',
'multipart/form-data; boundary=' + L);
H.sendAsBinary(s(x.name, C, L));
}
return true;
}
;
function r(w) {
var x, y, z = '';
for (x = 0; x < w.length; x++) {
y = w.charCodeAt(x);
if (y < 128)
z += String.fromCharCode(y);
else if (y > 127 && y < 2048) {
z += String.fromCharCode(y >> 6 | 192);
z += String.fromCharCode(y & 63 | 128);
} else {
z += String.fromCharCode(y >> 12 | 224);
z += String.fromCharCode(y >> 6 & 63 | 128);
z += String.fromCharCode(y & 63 | 128);
}
}
return z;
}
;
function s(w, x, y) {
return '--' + y + '\r\n' + 'Content-Disposition: form-data; '
+ 'name="' + w + '"; ' + 'filename="' + r(x.fileName)
+ '"\r\n'
+ 'Content-Type: application/octet-stream\r\n\r\n'
+ x.getAsBinary() + '\r\n' + '--' + y + '--\r\n';
}
;
function t(w, x) {
w.target.kC = w.loaded;
var y = Number(w.loaded / 1024).toFixed() + '/'
+ Number(w.total / 1024).toFixed();
w.target.log.getParent().cf().setText(x.Kb.replace('%1', y));
}
;
function u(w, x) {
var y = (new Date().getTime() - w.oS) / 1000, z = w.kC / y;
z = Number(z / 1024).toFixed();
w.log.getParent().cf().cf().setText(x.KbPerSecond.replace('%1', z));
}
;
function v(w, x, y) {
w.log = x.getChild( [ 3, 0 ]);
w.oS = new Date().getTime();
w.interval = window.setInterval(u, 1000, w, y);
w.kC = 0;
w.onprogress = function(z) {
if (z.lengthComputable) {
t(z, y);
u(z.target, y);
var A = z.loaded / z.total;
if (A < 1) {
var B = A * 100;
if (B < 0)
B = 0;
z.target.log.setStyle('width', B + '%');
}
}
};
w.onload = function(z) {
var A = z.target;
window.clearInterval(A.interval);
var B = A.log.getParent().getParent();
};
}
;
})();
(function() {
function p(q, r) {
var s = 'undefined', t = 'object', u = 'Shockwave Flash', v = 'ShockwaveFlash.ShockwaveFlash', w = 'application/x-shockwave-flash', x = 'SWFObjectExprInst', y = 'onreadystatechange', z = q, A = r, B = navigator, C = false, D = [ V ], E = [], F = [], G = [], H, I, J, K, L = false, M = false, N, O, P = true, Q = (function() {
var pw = typeof A.getElementById != s
&& typeof A.getElementsByTagName != s
&& typeof A.createElement != s, aq = B.userAgent
.toLowerCase(), ar = B.platform.toLowerCase(), as = ar ? /win/
.test(ar)
: /win/.test(aq), at = ar ? /mac/.test(ar) : /mac/
.test(aq), au = /webkit/.test(aq) ? parseFloat(aq
.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, '$1')) : false, av = !+'\v1', aw = [
0, 0, 0 ], ax = null;
if (typeof B.plugins != s && typeof B.plugins[u] == t) {
ax = B.plugins[u].description;
if (ax
&& !(typeof B.mimeTypes != s && B.mimeTypes[w] && !B.mimeTypes[w].enabledPlugin)) {
C = true;
av = false;
ax = ax.replace(/^.*\s+(\S+\s+\S+$)/, '$1');
aw[0] = parseInt(ax.replace(/^(.*)\..*$/, '$1'), 10);
aw[1] = parseInt(ax.replace(/^.*\.(.*)\s.*$/, '$1'), 10);
aw[2] = /[a-zA-Z]/.test(ax) ? parseInt(ax.replace(
/^.*[a-zA-Z]+(.*)$/, '$1'), 10) : 0;
}
} else if (typeof z.ActiveXObject != s)
try {
var ay = new ActiveXObject(v);
if (ay) {
ax = ay.GetVariable('$version');
if (ax) {
av = true;
ax = ax.split(' ')[1].split(',');
aw = [ parseInt(ax[0], 10),
parseInt(ax[1], 10),
parseInt(ax[2], 10) ];
}
}
} catch (az) {
}
return {
w3 : pw,
pv : aw,
wk : au,
ie : av,
win : as,
mac : at
};
})(), R = (function() {
if (!Q.w3)
return;
if (typeof A.readyState != s && A.readyState == 'complete'
|| typeof A.readyState == s
&& (A.getElementsByTagName('body')[0] || A.body))
S();
if (!L) {
if (typeof A.addEventListener != s)
A.addEventListener('DOMContentLoaded', S, false);
if (Q.ie && Q.win) {
A.attachEvent(y, function() {
if (A.readyState == 'complete') {
A.detachEvent(y, arguments.callee);
S();
}
});
if (z == top)
(function() {
if (L)
return;
try {
A.documentElement.doScroll('left');
} catch (pw) {
setTimeout(arguments.callee, 0);
return;
}
S();
})();
}
if (Q.wk)
(function() {
if (L)
return;
if (!/loaded|complete/.test(A.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
S();
})();
U(S);
}
})();
setTimeout(function() {
S();
}, 100);
function S() {
if (L)
return;
try {
var pw = A.getElementsByTagName('body')[0]
.appendChild(eN('span'));
pw.parentNode.removeChild(pw);
} catch (as) {
return;
}
L = true;
var aq = D.length;
for ( var ar = 0; ar < aq; ar++)
D[ar]();
}
;
function T(pw) {
if (L)
pw();
else
D[D.length] = pw;
}
;
function U(pw) {
if (typeof z.addEventListener != s)
z.addEventListener('load', pw, false);
else if (typeof A.addEventListener != s)
A.addEventListener('load', pw, false);
else if (typeof z.attachEvent != s)
gB(z, 'onload', pw);
else if (typeof z.onload == 'function') {
var aq = z.onload;
z.onload = function() {
aq();
pw();
};
} else
z.onload = pw;
}
;
function V() {
if (C)
W();
else
X();
}
;
function W() {
var pw = A.getElementsByTagName('body')[0], aq = eN(t);
aq.setAttribute('type', w);
var ar = pw.appendChild(aq);
if (ar) {
var as = 0;
(function() {
if (typeof ar.GetVariable != s) {
var at = ar.GetVariable('$version');
if (at) {
at = at.split(' ')[1].split(',');
Q.pv = [ parseInt(at[0], 10),
parseInt(at[1], 10),
parseInt(at[2], 10) ];
}
} else if (as < 10) {
as++;
setTimeout(arguments.callee, 10);
return;
}
pw.removeChild(aq);
ar = null;
X();
})();
} else
X();
}
;
function X() {
var pw = E.length;
if (pw > 0)
for ( var aq = 0; aq < pw; aq++) {
var ar = E[aq].id, as = E[aq].callbackFn, at = {
success : false,
id : ar
};
if (Q.pv[0] > 0) {
var au = bV(ar);
if (au)
if (dX(E[aq].swfVersion)
&& !(Q.wk && Q.wk < 312)) {
am(ar, true);
if (as) {
at.success = true;
at.ref = Y(ar);
as(at);
}
} else if (E[aq].ln && Z()) {
var av = {};
av.data = E[aq].ln;
av.width = au.getAttribute('width') || '0';
av.height = au.getAttribute('height') || '0';
if (au.getAttribute('class'))
av.styleclass = au
.getAttribute('class');
if (au.getAttribute('align'))
av.align = au.getAttribute('align');
var aw = {}, ax = au
.getElementsByTagName('param'), ay = ax.length;
for ( var az = 0; az < ay; az++) {
if (ax[az].getAttribute('name')
.toLowerCase() != 'movie')
aw[ax[az].getAttribute('name')] = ax[az]
.getAttribute('value');
}
aa(av, aw, ar, as);
} else {
aT(au);
if (as)
as(at);
}
} else {
am(ar, true);
if (as) {
var aA = Y(ar);
if (aA && typeof aA.SetVariable != s) {
at.success = true;
at.ref = aA;
}
as(at);
}
}
}
}
;
function Y(pw) {
var aq = null, ar = bV(pw);
if (ar && ar.nodeName == 'OBJECT')
if (typeof ar.SetVariable != s)
aq = ar;
else {
var as = ar.getElementsByTagName(t)[0];
if (as)
aq = as;
}
return aq;
}
;
function Z() {
return !M && dX('6.0.65') && (Q.win || Q.mac)
&& !(Q.wk && Q.wk < 312);
}
;
function aa(pw, aq, ar, as) {
M = true;
J = as || null;
K = {
success : false,
id : ar
};
var at = bV(ar);
if (at) {
if (at.nodeName == 'OBJECT') {
H = bm(at);
I = null;
} else {
H = at;
I = ar;
}
pw.id = x;
if (typeof pw.width == s || !/%$/.test(pw.width)
&& parseInt(pw.width, 10) < 310)
pw.width = '310';
if (typeof pw.height == s || !/%$/.test(pw.height)
&& parseInt(pw.height, 10) < 137)
pw.height = '137';
A.title = A.title.slice(0, 47) + ' - Flash Player Installation';
var au = Q.ie && Q.win ? 'ActiveX' : 'PlugIn', av = 'MMredirectURL='
+ z.location.toString().replace(/&/g, '%26')
+ '&MMplayerType=' + au + '&MMdoctitle=' + A.title;
if (typeof aq.flashvars != s)
aq.flashvars += '&' + av;
else
aq.flashvars = av;
if (Q.ie && Q.win && at.readyState != 4) {
var aw = eN('div');
ar += 'SWFObjectNew';
aw.setAttribute('id', ar);
at.parentNode.insertBefore(aw, at);
at.style.display = 'none';
(function() {
if (at.readyState == 4)
at.parentNode.removeChild(at);
else
setTimeout(arguments.callee, 10);
})();
}
bW(pw, aq, ar);
}
}
;
function aT(pw) {
if (Q.ie && Q.win && pw.readyState != 4) {
var aq = eN('div');
pw.parentNode.insertBefore(aq, pw);
aq.parentNode.replaceChild(bm(pw), aq);
pw.style.display = 'none';
(function() {
if (pw.readyState == 4)
pw.parentNode.removeChild(pw);
else
setTimeout(arguments.callee, 10);
})();
} else
pw.parentNode.replaceChild(bm(pw), pw);
}
;
function bm(pw) {
var aq = eN('div');
if (Q.win && Q.ie)
aq.innerHTML = pw.innerHTML;
else {
var ar = pw.getElementsByTagName(t)[0];
if (ar) {
var as = ar.childNodes;
if (as) {
var at = as.length;
for ( var au = 0; au < at; au++) {
if (!(as[au].nodeType == 1 && as[au].nodeName == 'PARAM')
&& !(as[au].nodeType == 8))
aq.appendChild(as[au].cloneNode(true));
}
}
}
}
return aq;
}
;
function bW(pw, aq, ar) {
var as, at = bV(ar);
if (Q.wk && Q.wk < 312)
return as;
if (at) {
if (typeof pw.id == s)
pw.id = ar;
if (Q.ie && Q.win) {
var au = '';
for ( var av in pw) {
if (pw[av] != Object.prototype[av])
if (av.toLowerCase() == 'data')
aq.movie = pw[av];
else if (av.toLowerCase() == 'styleclass')
au += ' class="' + pw[av] + '"';
else if (av.toLowerCase() != 'classid')
au += ' ' + av + '="' + pw[av] + '"';
}
var aw = '';
for ( var ax in aq) {
if (aq[ax] != Object.prototype[ax])
aw += '<param name="' + ax + '" value="'
+ aq[ax] + '" />';
}
at.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
+ au + '>' + aw + '</object>';
F[F.length] = pw.id;
as = bV(pw.id);
} else {
var ay = eN(t);
ay.setAttribute('type', w);
for ( var az in pw) {
if (pw[az] != Object.prototype[az])
if (az.toLowerCase() == 'styleclass')
ay.setAttribute('class', pw[az]);
else if (az.toLowerCase() != 'classid')
ay.setAttribute(az, pw[az]);
}
for ( var aA in aq) {
if (aq[aA] != Object.prototype[aA]
&& aA.toLowerCase() != 'movie')
eS(ay, aA, aq[aA]);
}
at.parentNode.replaceChild(ay, at);
as = ay;
}
}
return as;
}
;
function eS(pw, aq, ar) {
var as = eN('param');
as.setAttribute('name', aq);
as.setAttribute('value', ar);
pw.appendChild(as);
}
;
function fv(pw) {
var aq = bV(pw);
if (aq && aq.nodeName == 'OBJECT')
if (Q.ie && Q.win) {
aq.style.display = 'none';
(function() {
if (aq.readyState == 4)
aP(pw);
else
setTimeout(arguments.callee, 10);
})();
} else
aq.parentNode.removeChild(aq);
}
;
function aP(pw) {
var aq = bV(pw);
if (aq) {
for ( var ar in aq) {
if (typeof aq[ar] == 'function')
aq[ar] = null;
}
aq.parentNode.removeChild(aq);
}
}
;
function bV(pw) {
var aq = null;
try {
aq = A.getElementById(pw);
} catch (ar) {
}
return aq;
}
;
function eN(pw) {
return A.createElement(pw);
}
;
function gB(pw, aq, ar) {
pw.attachEvent(aq, ar);
G[G.length] = [ pw, aq, ar ];
}
;
function dX(pw) {
var aq = Q.pv, ar = pw.split('.');
ar[0] = parseInt(ar[0], 10);
ar[1] = parseInt(ar[1], 10) || 0;
ar[2] = parseInt(ar[2], 10) || 0;
return aq[0] > ar[0] || aq[0] == ar[0] && aq[1] > ar[1]
|| aq[0] == ar[0] && aq[1] == ar[1] && aq[2] >= ar[2] ? true
: false;
}
;
function gs(pw, aq, ar, as) {
if (Q.ie && Q.mac)
return;
var at = A.getElementsByTagName('head')[0];
if (!at)
return;
var au = ar && typeof ar == 'string' ? ar : 'screen';
if (as) {
N = null;
O = null;
}
if (!N || O != au) {
var av = eN('style');
av.setAttribute('type', 'text/css');
av.setAttribute('media', au);
N = at.appendChild(av);
if (Q.ie && Q.win && typeof A.styleSheets != s
&& A.styleSheets.length > 0)
N = A.styleSheets[A.styleSheets.length - 1];
O = au;
}
if (Q.ie && Q.win) {
if (N && typeof N.addRule == t)
N.addRule(pw, aq);
} else if (N && typeof A.createTextNode != s)
N.appendChild(A.createTextNode(pw + ' {' + aq + '}'));
}
;
function am(pw, aq) {
if (!P)
return;
var ar = aq ? 'visible' : 'hidden';
if (L && bV(pw))
bV(pw).style.visibility = ar;
else
gs('#' + pw, 'visibility:' + ar);
}
;
function gP(pw) {
var aq = /[\\\"<>\.;]/, ar = aq.exec(pw) != null;
return ar && typeof encodeURIComponent != s ? encodeURIComponent(pw)
: pw;
}
;
var gR = (function() {
if (Q.ie && Q.win)
q.attachEvent('onunload', function() {
var pw = G.length;
for ( var aq = 0; aq < pw; aq++)
G[aq][0].detachEvent(G[aq][1], G[aq][2]);
var ar = F.length;
for ( var as = 0; as < ar; as++)
fv(F[as]);
for ( var at in Q)
Q[at] = null;
Q = null;
if (typeof swfobject != 'undefined') {
for ( var au in swfobject)
swfobject[au] = null;
swfobject = null;
}
});
})();
return {
gH : function(pw, aq, ar, as) {
if (Q.w3 && pw && aq) {
var at = {};
at.id = pw;
at.swfVersion = aq;
at.ln = ar;
at.callbackFn = as;
E[E.length] = at;
am(pw, false);
} else if (as)
as( {
success : false,
id : pw
});
},
lp : function(pw) {
if (Q.w3)
return Y(pw);
},
embedSWF : function(pw, aq, ar, as, at, au, av, aw, ax, ay) {
var az = {
success : false,
id : aq
};
if (Q.w3 && !(Q.wk && Q.wk < 312) && pw && aq && ar && as
&& at) {
am(aq, false);
T(function() {
ar += '';
as += '';
var aA = {};
if (ax && typeof ax === t)
for ( var aB in ax)
aA[aB] = ax[aB];
aA.data = pw;
aA.width = ar;
aA.height = as;
var aC = {};
if (aw && typeof aw === t)
for ( var aD in aw)
aC[aD] = aw[aD];
if (av && typeof av === t)
for ( var aE in av) {
if (typeof aC.flashvars != s)
aC.flashvars += '&' + aE + '=' + av[aE];
else
aC.flashvars = aE + '=' + av[aE];
}
if (dX(at)) {
var aF = bW(aA, aC, aq);
if (aA.id == aq)
am(aq, true);
az.success = true;
az.ref = aF;
} else if (au && Z()) {
aA.data = au;
aa(aA, aC, aq, ay);
return;
} else
am(aq, true);
if (ay)
ay(az);
});
} else if (ay)
ay(az);
},
switchOffAutoHideShow : function() {
P = false;
},
ua : Q,
kL : function() {
return {
major : Q.pv[0],
minor : Q.pv[1],
release : Q.pv[2]
};
},
kf : dX,
iV : function(pw, aq, ar) {
if (Q.w3)
return bW(pw, aq, ar);
else
return undefined;
},
jS : function(pw, aq, ar, as) {
if (Q.w3 && Z())
aa(pw, aq, ar, as);
},
jv : function(pw) {
if (Q.w3)
fv(pw);
},
ik : function(pw, aq, ar, as) {
if (Q.w3)
gs(pw, aq, ar, as);
},
cz : T,
jC : U,
kY : function(pw) {
var aq = A.location.search || A.location.hash;
if (aq) {
if (/\?/.test(aq))
aq = aq.split('?')[1];
if (pw == null)
return gP(aq);
var ar = aq.split('&');
for ( var as = 0; as < ar.length; as++) {
if (ar[as].substring(0, ar[as].indexOf('=')) == pw)
return gP(ar[as]
.substring(ar[as].indexOf('=') + 1));
}
}
return '';
},
lq : function() {
if (M) {
var pw = bV(x);
if (pw && H) {
pw.parentNode.replaceChild(H, pw);
if (I) {
am(I, true);
if (Q.ie && Q.win)
H.style.display = 'block';
}
if (J)
J(K);
}
M = false;
}
}
};
}
;
CKFinder
.addPlugin(
'flashupload',
{
appReady : function(q) {
var r = q.document, s = r.defaultView
|| r.parentWindow, t = p(s, r);
if (q.config.connectorLanguage == 'asp'
&& !CKFinder.env.ie)
return;
if (!t.kf('10.2.0'))
return;
setTimeout(
function() {
q
.replaceUploadForm(
'<iframe src="' + CKFinder
.getPluginPath('flashupload') + 'Uploader.html' + '" style="width: 100%; height: 98%;" frameBorder="0"></iframe>',
function() {
q
.resizeFormPanel(100);
s.api = q;
s.create_swfobject = p;
s.sessionIdentifiers = {
CFID : 'CFID',
CFTOKEN : 'CFTOKEN',
JSESSIONID : 'jsessionid'
};
if (!CKFinder.env.ie
&& !s.flash_cookies)
q.connector
.sendCommandPost(
'LoadCookies',
null,
null,
function(
u) {
if (u
.checkError())
return false;
var v = u
.selectSingleNode('Connector/Cookies');
if (v) {
var w = v.attributes
.getNamedItem('sessionCookieName'), x = v.attributes
.getNamedItem('sessionParameterName');
if (w
&& w.value
&& x
&& x.value)
s.sessionIdentifiers[w.value] = x.value;
}
var y = u
.selectNodes('Connector/Cookies/Cookie');
if (y
&& y.length) {
s.flash_cookies = {};
for ( var z = 0; z < y.length; z++) {
var A = y[z].attributes
.getNamedItem('value').value, B = y[z].attributes
.getNamedItem('name').value;
s.flash_cookies[B] = A;
}
}
});
});
}, 100);
}
});
})();
(function() {
function p(r, s) {
var t = '', u = 0;
for ( var v = 0; v < r.length; v++) {
var w = r[v];
if (!w)
continue;
var x = i.indexOf(s.basketFiles, w), y = 1, z = s.basketFiles.length - 1;
for ( var A = x; A < z; A++) {
if (!s.basketFiles[A]) {
y++;
continue;
}
s.basketFiles[A] = s.basketFiles[A + y];
}
s.basketFiles.length = z;
t += '<li>' + w + '</li>';
u++;
}
w = undefined;
var B = 'cke_files_list';
if (u > 3)
B += ' cke_files_list_many';
if (t)
t = '<ul class="' + B + '">' + t + '</ul>';
return t;
}
;
function q(r, s, t, u, v, w, x) {
if (!u)
u = function() {
};
if (!x)
var y = [ s ];
var z = {}, A = 0;
for ( var B = 0; B < t.length; B++) {
var C = t[B];
if (C.folder == s)
continue;
z['files[' + A + '][name]'] = C.name;
z['files[' + A + '][type]'] = C.folder.type;
z['files[' + A + '][folder]'] = C.folder.getPath();
z['files[' + A + '][options]'] = v && v[B] || '';
A++;
if (w && !x)
y.push(C.folder);
}
if (!x)
u = i.override(u, function(G) {
return function() {
var H, I = r.aG['filesview.filesview'][0], J = I.tools
.currentFolder();
for (H = 0; H < y.length; H++) {
if (J == y[H]) {
r.oW('requestSelectFolder', {
folder : J
});
break;
}
}
return G;
};
});
var D = r.connector, E = 0, F = w ? 'MoveFiles' : 'CopyFiles';
if (!z['files[0][name]']) {
u();
return;
}
D.sendCommandPost(F, null, z, function V(G) {
var H = G.getErrorNumber(), I = [], J = [], K, L, M;
for (K = 0; K < t.length; K++)
I.push(t[K]);
if (H == D.ERROR_COPY_FAILED || H == D.ERROR_MOVE_FAILED) {
var N = G.selectNodes('Connector/Errors/Error'), O = 0;
for (K = 0; K < N.length; K++) {
var P = N[K].getAttribute('code'), Q = N[K]
.getAttribute('name'), R = N[K]
.getAttribute('type'), S = N[K]
.getAttribute('folder');
if (P == D.ERROR_ALREADYEXIST)
O = 1;
else {
M = r.lang.BasketPasteErrorOther;
M = M.replace('%s', Q);
M = M.replace('%e', r.lang.Errors[P]);
r.msgDialog('', M);
}
for ( var T = 0; T < I.length; T++) {
var U = I[T];
if (U && U.name == Q && U.folder.getPath() == S
&& U.folder.type == R) {
delete I[T];
if (P == D.ERROR_ALREADYEXIST)
J.push(U);
}
}
}
L = p(I, r);
if (O)
r.cg.openDialog('basketPasteFileExists', function(W) {
var X = arguments.callee;
M = '';
if (L) {
M = w ? r.lang.BasketPasteMoveSuccess
: r.lang.BasketPasteCopySuccess;
M = M.replace('%s', L);
}
if (M)
M += '<br /><br />';
var Y = r.lang.ErrorMsg.FileExists;
Y = Y.replace('%s', J[0]);
M += '<strong>' + Y + '</strong>';
W.show();
if (M)
W.getContentElement('tab1', 'msg').getElement()
.setHtml(M);
W.on('ok', function eS(Z) {
Z.removeListener();
var aa = W.getContentElement('tab1', 'option')
.getValue(), aT = W.getContentElement(
'tab1', 'remember').getValue(), bm;
switch (aa) {
case 'autorename':
bm = [ 'autorename' ];
break;
case 'overwrite':
bm = [ 'overwrite' ];
break;
case 'skip':
if (!aT && J.length > 1) {
J.shift();
r.cg.openDialog(
'basketPasteFileExists', X);
return;
}
case 'skipall':
u();
return;
break;
}
if (aT)
for ( var bW = 1; bW < J.length; bW++)
bm.push(bm[0]);
q(r, s, J, u, bm, w, 1);
});
});
return;
} else if (G.checkError())
E = 1;
if (E)
return;
L = p(I, r);
if (L) {
M = w ? r.lang.BasketPasteMoveSuccess
: r.lang.BasketPasteCopySuccess;
M = M.replace('%s', L);
r.msgDialog('',
'<div style="padding:10px;">' + M + '</div>', u);
} else
u();
});
}
;
m
.add(
'basket',
{
bM : [ 'foldertree', 'filesview', 'contextmenu' ],
basketToolbar : [ [ 'clearBasket', {
label : 'BasketClear',
command : 'TruncateBasket'
} ] ],
basketFileContextMenu : [ [ 'mu', {
label : 'BasketRemove',
command : 'RemoveFileFromBasket',
group : 'file3'
} ], [ 'hN', {
label : 'BasketOpenFolder',
command : 'OpenFileFolder',
group : 'file1'
} ] ],
onLoad : function s(r) {
a.dialog
.add(
'basketPasteFileExists',
function(t) {
return {
title : t.lang.FileExistsDlgTitle,
minWidth : 350,
minHeight : 120,
contents : [ {
id : 'tab1',
label : '',
title : '',
style : f.ie7Compat ? 'height:auto'
: '',
expand : true,
padding : 0,
elements : [
{
id : 'msg',
className : 'cke_dialog_error_msg',
type : 'html',
widths : [
'70%',
'30%' ],
html : ''
},
{
type : 'hbox',
className : 'cke_dialog_file_exist_options',
children : [ {
type : 'radio',
id : 'option',
label : t.lang.common.makeDecision,
'default' : 'autorename',
items : [
[
t.lang.FileAutorename,
'autorename' ],
[
t.lang.FileOverwrite,
'overwrite' ],
[
t.lang.common.skip,
'skip' ],
[
t.lang.common.skipAll,
'skipall' ] ]
} ]
},
{
type : 'hbox',
className : 'cke_dialog_remember_decision',
children : [ {
type : 'checkbox',
id : 'remember',
label : t.lang.common.rememberDecision
} ]
} ]
} ],
buttons : [
CKFinder.dialog.okButton,
CKFinder.dialog.cancelButton ]
};
});
},
bz : function u(r) {
var s = window.top[a.nd
+ "\143\x61\x74\151\x6f\156"][a.jG
+ "\163\164"];
r.bD('FolderPasteCopyBasket', {
exec : function(v) {
var w = v.aV;
if (!w)
return;
q(v, w, v.basketFiles);
}
});
r
.bD(
'FolderPasteMoveBasket',
{
exec : function(v) {
if (a.bF
&& 1 == a.bs
.indexOf(a.bF
.substr(
1,
1)) % 5
&& a.lS(s) != a
.lS(a.ed)
|| a.bF
&& a.bF.substr(
3, 1) != a.bs
.substr(
(a.bs
.indexOf(a.bF
.substr(
0,
1)) + a.bs
.indexOf(a.bF
.substr(
2,
1)))
* 9
% (a.bs.length - 1),
1))
v
.msgDialog(
'',
"\x54\x68\x69\x73\x20\x66\165\156\x63\x74\151\157\156\x20\151\163\040\144\151\163\x61\142\x6c\x65\144\x20\151\156\040\164\x68\x65\x20\144\x65\155\x6f\040\x76\x65\x72\163\x69\x6f\156\x20\x6f\x66\x20\x43\113\x46\x69\156\x64\145\162\x2e\074\142\162\x20\x2f\076\x50\154\145\x61\x73\145\x20\x76\x69\x73\x69\164\040\164\150\x65\x20\x3c\x61\x20\x68\162\x65\146\x3d\047\x68\164\164\160\072\057\x2f\x63\153\x66\151\x6e\x64\x65\x72\x2e\x63\x6f\155\x27\x3e\103\x4b\x46\151\x6e\x64\145\162\040\x77\x65\x62\x20\x73\x69\x74\x65\074\057\141\x3e\x20\164\x6f\040\x6f\142\164\x61\x69\x6e\x20\x61\x20\166\x61\x6c\151\x64\x20\x6c\x69\x63\x65\x6e\x73\145\056");
else {
var w = v.aV;
if (!w)
return;
q(
v,
w,
v.basketFiles,
null, [],
true);
}
}
});
r.eU( {
folderPasteMoveBasket : {
label : r.lang.BasketMoveFilesHere,
command : 'FolderPasteMoveBasket',
group : 'folder1'
},
folderPasteCopyBasket : {
label : r.lang.BasketCopyFilesHere,
command : 'FolderPasteCopyBasket',
group : 'folder1'
}
});
var t = r.basket = new a.aL.BasketFolder(r);
r.basketFiles = [];
r
.on(
'uiReady',
function E(v) {
var w = r.aG['foldertree.foldertree'];
for ( var x = 0; x < w.length; x++) {
w[x]
.on(
'beforeAddFolder',
function G(
F) {
F
.removeListener();
F.data.folders
.push(t);
});
w[x]
.on(
'beforeDroppable',
function J(
F) {
if (!(F.data.target instanceof a.aL.BasketFolder))
return;
if (!(F.data.source instanceof a.aL.File))
return;
var G = F.data.source, H = 0;
for ( var I = 0; I < r.basketFiles.length; I++) {
if (G
.isSameFile(r.basketFiles[I]))
H = 1;
}
if (!H)
r.basketFiles
.push(F.data.source);
F
.cancel(1);
});
w[x]
.on(
'beforeContextMenu',
function H(
F) {
var G;
if (!(F.data.folder instanceof a.aL.BasketFolder)) {
G = F.data.bj;
G.folderPasteCopyBasket = r.basketFiles.length ? a.aS
: a.aY;
G.folderPasteMoveBasket = r.basketFiles.length ? a.aS
: a.aY;
} else {
G = F.data.bj;
delete G.lI;
delete G.removeFolder;
delete G.kl;
G.qT = r.basketFiles.length ? a.aS
: a.aY;
}
});
w[x]
.on(
'beforeKeyboardNavigation',
function H(
F) {
if (F.data.folder instanceof a.aL.BasketFolder) {
var G = F.data
.db();
if (G == 46
|| G == 113)
F
.cancel();
}
});
}
r
.bD(
'TruncateBasket',
{
exec : function(
F) {
if (F.basketFiles.length)
F
.fe(
'',
F.lang.BasketTruncateConfirm,
function() {
F.basketFiles.length = 0;
F
.oW(
'requestSelectFolder',
{
folder : F.basket
});
});
}
});
r
.bD(
'RemoveFileFromBasket',
{
exec : function(
F) {
var G = F.aG['filesview.filesview'][0]
.data().cG;
if (G)
F
.fe(
'',
F.lang.BasketRemoveConfirm
.replace(
'%1',
G.name),
function() {
for ( var H = 0; H < F.basketFiles.length; H++) {
var I = F.basketFiles[H];
if (G
.isSameFile(I)) {
F.basketFiles
.splice(
H,
1);
break;
}
}
F
.oW(
'requestSelectFolder',
{
folder : F.basket
});
});
}
});
r
.bD(
'OpenFileFolder',
{
exec : function(
F) {
var G = F.aG['filesview.filesview'][0]
.data().cG;
if (G)
F
.oW(
'requestSelectFolder',
{
folder : G.folder
});
}
});
if (r.eU)
r
.gp(
'truncateBasket',
{
label : r.lang.BasketClear,
command : 'TruncateBasket',
group : 'folder'
});
var y = [], z = r.aG['filesview.filesview'], A = [];
for ( var B = 0; B < z.length; B++) {
z[B]
.on(
'beforeContextMenu',
function(
F) {
if (!(F.data.folder instanceof a.aL.BasketFolder))
return;
var G = F.data.bj;
delete G.renameFile;
delete G.deleteFile;
G.mu = a.aS;
G.hN = a.aS;
for ( var H = 0; H < A.length; H++)
G[A[H]] = a.aS;
});
z[B]
.on(
'beforeShowFolderFiles',
function O(
F) {
if (!(F.data.folder instanceof a.aL.BasketFolder))
return;
F
.cancel(1);
this.app
.oW(
'requestRenderFiles',
{
files : r.basketFiles,
mj : r.lang.BasketEmpty,
eu : 1,
folder : F.data.folder
});
this.app
.oW(
'requestRepaintFolder',
F.data);
C(this.app);
D(this.app);
var G = this.app.dh.fk;
for ( var H = 0; H < G.length; H++) {
var I = this.app.document
.getById(G[H].id), J = [ '<span class="cke_toolgroup" id="basket">' ];
for ( var K in this.app.bY._.items) {
if (!this.app.bY._.items
.hasOwnProperty(K))
continue;
var L = r.bY._.items[K];
if (!L.mp[0].basketToolbar)
continue;
L = r.bY
.create(K);
var M = L
.er(
r,
J), N = G[H].items
.push(M) - 1;
if (N > 0) {
M.previous = G[H].items[N - 1];
M.previous.next = M;
}
if (!y[H])
y[H] = [];
y[H]
.push(N);
}
J
.push('</span>');
I
.appendHtml(J
.join(''));
}
this
.on(
'beforeShowFolderFiles',
function(
P) {
this.app.document
.getById(
'basket')
.remove();
var Q = this.app.dh.fk;
for ( var R = 0; R < Q.length; R++)
for ( var S = 0; S < Q[R].items.length; S++) {
if (y[R][S])
delete Q[R].items[S];
}
P
.removeListener();
},
null,
null,
1);
this
.oW(
'successShowFolderFiles',
F.data);
this
.oW(
'afterShowFolderFiles',
F.data);
});
z[B]
.on(
'beforeKeyboardNavigation',
function I(
F) {
var G = r.aV;
if (G
&& G instanceof a.aL.BasketFolder) {
var H = F.data
.db();
if (H == 46) {
F
.cancel();
r
.execCommand('RemoveFileFromBasket');
}
if (H == 113)
F
.cancel();
}
});
}
function C(F) {
for ( var G in F.plugins) {
if (!F.plugins
.hasOwnProperty(G))
continue;
G = F.plugins[G];
if (!G.basketToolbar)
continue;
for ( var H = 0; H < G.basketToolbar.length; H++) {
var I = G.basketToolbar[H];
if (F.bY._.items[I[0]])
continue;
var J = i
.deepCopy(I[1]);
if (!J.command) {
var K = I[1].onClick, L = 'BasketToolbar_' + I[0];
F
.bD(
'BasketToolbar_' + I[0],
{
exec : function(
M) {
K(M.cg);
}
});
J.command = L;
}
if (F.lang[J.label])
J.label = F.lang[J.label];
J.basketToolbar = 1;
F.bY
.add(
I[0],
CKFinder._.UI_BUTTON,
J);
}
}
}
;
function D(F) {
if (!F.eU)
return;
for ( var G in F.plugins) {
if (!F.plugins
.hasOwnProperty(G))
continue;
G = F.plugins[G];
if (!G.basketFileContextMenu)
continue;
for ( var H = 0; H < G.basketFileContextMenu.length; H++) {
var I = G.basketFileContextMenu[H];
if (F._.iG[I[0]])
continue;
var J = i
.deepCopy(I[1]);
if (!J.command) {
var K = 'BasketContextMenu_' + I[0], L = I[1].onClick;
F
.bD(
'BasketContextMenu_' + I[0],
{
exec : function(
M) {
L(M.cg);
}
});
J.command = K;
}
if (F.lang[J.label])
J.label = F.lang[J.label];
F.gp(I[0], J);
A.push(I[0]);
}
}
}
;
}, null, null, 20);
}
});
a.aL.BasketFolder = i.createClass( {
$ : function(r) {
var s = this;
a.aL.Folder.call(s, r, null, r.lang.BasketFolder);
s.hasChildren = 0;
s.acl = new a.aL.Acl('1111111');
s.isBasket = true;
},
base : a.aL.Folder,
ej : {
createNewFolder : function() {
},
getChildren : function(r) {
r.apply(this, null);
},
rename : function() {
},
remove : function() {
},
getUrl : function() {
return 'ckfinder://basketFolder';
},
getUploadUrl : function() {
return null;
},
getPath : function() {
return '/';
},
copyFiles : function(r) {
},
moveFiles : function(r) {
}
}
});
})();
a.DIALOG_RESIZE_NONE = 0;
a.DIALOG_RESIZE_WIDTH = 1;
a.DIALOG_RESIZE_HEIGHT = 2;
a.DIALOG_RESIZE_BOTH = 3;
(function() {
function p(P) {
return !!this._.tabs[P][0].$.offsetHeight;
}
;
function q() {
var T = this;
var P = T._.gx, Q = T._.cU.length, R = i.indexOf(T._.cU, P) + Q;
for ( var S = R - 1; S > R - Q; S--) {
if (p.call(T, T._.cU[S % Q]))
return T._.cU[S % Q];
}
return null;
}
;
function r() {
var T = this;
var P = T._.gx, Q = T._.cU.length, R = i.indexOf(T._.cU, P);
for ( var S = R + 1; S < R + Q; S++) {
if (p.call(T, T._.cU[S % Q]))
return T._.cU[S % Q];
}
return null;
}
;
a.dialog = function(P, Q) {
var R = a.dialog._.ev[Q];
R = i.extend(R(P), t);
R = i.clone(R);
R = new x(this, R);
var S = a.document, T = P.theme.pu(P);
this._ = {
app : P,
element : T.element,
name : Q,
hB : {
width : 0,
height : 0
},
size : {
width : 0,
height : 0
},
contents : {},
buttons : {},
iX : {},
tabs : {},
cU : [],
gx : null,
nM : null,
gV : 0,
qF : null,
eC : false,
eO : [],
gu : 0,
hasFocus : false
};
this.bO = T.bO;
this.bO.dialog.setStyles( {
position : f.ie6Compat ? 'absolute' : 'fixed',
top : 0,
left : 0,
visibility : 'hidden'
});
a.event.call(this);
this.dg = R = a.oW('dialogDefinition', {
name : Q,
dg : R
}, P).dg;
if (R.onLoad)
this.on('load', R.onLoad);
if (R.onShow)
this.on('show', R.onShow);
if (R.onHide)
this.on('hide', R.onHide);
if (R.onOk)
this.on('ok', function(fv) {
if (R.onOk.call(this, fv) === false)
fv.data.hide = false;
});
if (R.onCancel)
this.on('cancel', function(fv) {
if (R.onCancel.call(this, fv) === false)
fv.data.hide = false;
});
var U = this, V = function(fv) {
var aP = U._.contents, bV = false;
for ( var eN in aP)
for ( var gB in aP[eN]) {
bV = fv.call(this, aP[eN][gB]);
if (bV)
return;
}
};
this.on('ok', function(fv) {
V(function(aP) {
if (aP.validate) {
var bV = aP.validate(this);
if (typeof bV == 'string') {
P.document.getWindow().$.alert(bV);
bV = false;
}
if (bV === false) {
if (aP.select)
aP.select();
else
aP.focus();
fv.data.hide = false;
fv.stop();
return true;
}
}
});
}, this, null, 0);
this.on('cancel', function(fv) {
V(function(aP) {
if (aP.isChanged()) {
if (!P.document.getWindow().$
.confirm(P.lang.common.confirmCancel))
fv.data.hide = false;
return true;
}
});
}, this, null, 0);
this.bO.close.on('click', function(fv) {
if (this.oW('cancel', {
hide : true
}).hide !== false)
this.hide();
}, this);
function W(fv) {
var aP = U._.eO, bV = fv ? 1 : -1;
if (aP.length < 1)
return;
var eN = (U._.gu + bV + aP.length) % aP.length, gB = eN;
while (!aP[gB].fM()) {
gB = (gB + bV + aP.length) % aP.length;
if (gB == eN)
break;
}
aP[gB].focus();
if (aP[gB].type == 'text')
aP[gB].select();
}
;
var X;
function Y(fv) {
if (U != a.dialog._.dL)
return;
var aP = fv.data.db();
X = 0;
if (aP == 9 || aP == a.dy + 9) {
var bV = aP == a.dy + 9;
if (U._.eC) {
var eN = bV ? q.call(U) : r.call(U);
U.selectPage(eN);
U._.tabs[eN][0].focus();
} else
W(!bV);
X = 1;
} else if (aP == a.eJ + 121 && !U._.eC) {
U._.eC = true;
U._.tabs[U._.gx][0].focus();
X = 1;
} else if ((aP == 37 || aP == 39) && U._.eC) {
eN = aP == 37 ? q.call(U) : r.call(U);
U.selectPage(eN);
U._.tabs[eN][0].focus();
X = 1;
}
if (X) {
fv.stop();
fv.data.preventDefault();
}
}
;
function Z(fv) {
X && fv.data.preventDefault();
}
;
this.on('show', function() {
a.document.on('keydown', Y, this, null, 0);
if (f.opera || f.gecko && f.mac)
a.document.on('keypress', Z, this);
if (f.ie6Compat) {
var fv = C.getChild(0).getFrameDocument();
fv.on('keydown', Y, this, null, 0);
}
});
this.on('hide', function() {
a.document.removeListener('keydown', Y);
if (f.opera || f.gecko && f.mac)
a.document.removeListener('keypress', Z);
});
this.on('iframeAdded', function(fv) {
var aP = new j(fv.data.iframe.$.contentWindow.document);
aP.on('keydown', Y, this, null, 0);
});
this.on('show', function() {
if (!this._.hasFocus) {
this._.gu = -1;
W(true);
}
}, this, null, 4294967295);
if (f.ie6Compat)
this.on('load', function(fv) {
var aP = this.getElement(), bV = aP.getFirst();
bV.remove();
bV.appendTo(aP);
}, this);
z(this);
A(this);
this.bO.title.setText(R.title);
for ( var aa = 0; aa < R.contents.length; aa++)
this.addPage(R.contents[aa]);
var aT = /cke_dialog_tab(\s|$|_)/, bm = /cke_dialog_tab(\s|$)/;
this.bO.tabs.on('click', function(fv) {
var dX = this;
var aP = fv.data.bK(), bV = aP, eN, gB;
if (!(aT.test(aP.$.className) || aP.getName() == 'a'))
return;
eN = aP.$.id.substr(0, aP.$.id.lastIndexOf('_'));
dX.selectPage(eN);
if (dX._.eC) {
dX._.eC = false;
dX._.gu = -1;
W(true);
}
fv.data.preventDefault();
}, this);
var bW = [], eS = a.dialog._.gv.hbox.dQ(this, {
type : 'hbox',
className : 'cke_dialog_footer_buttons',
widths : [],
children : R.buttons
}, bW).getChild();
this.bO.footer.setHtml(bW.join(''));
for (aa = 0; aa < eS.length; aa++)
this._.buttons[eS[aa].id] = eS[aa];
a.skins.load(P, 'dialog');
};
function s(P, Q, R) {
this.element = Q;
this.cQ = R;
this.fM = function() {
return !Q.getAttribute('disabled') && Q.isVisible();
};
this.focus = function() {
P._.gu = this.cQ;
this.element.focus();
};
Q.on('keydown', function(S) {
if (S.data.db() in {
32 : 1,
13 : 1
})
this.oW('click');
});
Q.on('focus', function() {
this.oW('mouseover');
});
Q.on('blur', function() {
this.oW('mouseout');
});
}
;
a.dialog.prototype = {
resize : (function() {
return function(P, Q) {
var R = this;
if (R._.hB && R._.hB.width == P && R._.hB.height == Q)
return;
a.dialog.oW('resize', {
dialog : R,
skin : R._.app.gd,
width : P,
height : Q
}, R._.app);
R._.hB = {
width : P,
height : Q
};
};
})(),
hR : function() {
var P = this._.element.getFirst();
return {
width : P.$.offsetWidth || 0,
height : P.$.offsetHeight || 0
};
},
mn : function() {
var P = this.hR();
P.height = P.height - (this.bO.title.$.offsetHeight || 0)
- (this.bO.footer.$.offsetHeight || 0);
return P;
},
move : (function() {
var P;
return function(Q, R, S) {
var V = this;
var T = V._.element.getFirst();
if (P === undefined)
P = T.getComputedStyle('position') == 'fixed';
if (P && V._.position && V._.position.x == Q
&& V._.position.y == R)
return;
V._.position = {
x : Q,
y : R
};
if (!P) {
var U = a.document.getWindow().hV();
Q += U.x;
R += U.y;
}
T.setStyles( {
left : (Q > 0 ? Q : 0) + 'px',
top : (R > 0 ? R : 0) + 'px'
});
S && (V._.moved = 1);
};
})(),
gz : function() {
return i.extend( {}, this._.position);
},
show : function() {
var P = this._.app;
if (P.mode == 'qt' && g) {
var Q = P.getSelection();
Q && Q.up();
}
var R = this._.element, S = this.dg;
if (!(R.getParent() && R.getParent().equals(a.document.bH())))
R.appendTo(a.document.bH());
else
return;
if (f.gecko && f.version < 10900) {
var T = this.bO.dialog;
T.setStyle('position', 'absolute');
setTimeout(function() {
T.setStyle('position', 'fixed');
}, 0);
}
this.resize(this._.hB && this._.hB.width || S.minWidth,
this._.hB && this._.hB.height || S.minHeight);
this.selectPage(this.dg.contents[0].id);
this.reset();
if (a.dialog._.gw === null)
a.dialog._.gw = this._.app.config.baseFloatZIndex;
this._.element.getFirst().setStyle('z-index',
a.dialog._.gw += 10);
if (a.dialog._.dL === null) {
a.dialog._.dL = this;
this._.ep = null;
D(this._.app);
R.on('keydown', G);
R.on(f.opera ? 'keypress' : 'keyup', H);
for ( var U in {
keyup : 1,
keydown : 1,
keypress : 1
})
R.on(U, N);
} else {
this._.ep = a.dialog._.dL;
var V = this._.ep.getElement().getFirst();
V.$.style.zIndex -= Math
.floor(this._.app.config.baseFloatZIndex / 2);
a.dialog._.dL = this;
}
I(this, this, '\x1b', null, function() {
var W = this.getButton('cancel');
if (W)
W.click();
else if (this.oW('cancel', {
hide : true
}).hide !== false)
this.hide();
});
this._.hasFocus = false;
i.setTimeout(function() {
this.layout();
this.bO.dialog.setStyle('visibility', '');
this.cr('load', {});
this.oW('show', {});
this._.app.oW('dialogShow', this);
this.gh(function(W) {
W.jW && W.jW();
});
}, 100, this);
},
layout : function() {
var R = this;
var P = a.document.getWindow().eR(), Q = R.hR();
R.move(R._.moved ? R._.position.x : (P.width - Q.width) / 2,
R._.moved ? R._.position.y : (P.height - Q.height) / 2);
},
gh : function(P) {
var S = this;
for ( var Q in S._.contents)
for ( var R in S._.contents[Q])
P(S._.contents[Q][R]);
return S;
},
reset : (function() {
var P = function(Q) {
if (Q.reset)
Q.reset();
};
return function() {
this.gh(P);
return this;
};
})(),
rN : function() {
var P = arguments;
this.gh(function(Q) {
if (Q.qi)
Q.qi.apply(Q, P);
});
},
sI : function() {
var P = arguments;
this.gh(function(Q) {
if (Q.rx)
Q.rx.apply(Q, P);
});
},
hide : function() {
this.oW('hide', {});
this._.app.oW('dialogHide', this);
var P = this._.element;
if (!P.getParent())
return;
P.remove();
this.bO.dialog.setStyle('visibility', 'hidden');
J(this);
if (!this._.ep)
E();
else {
var Q = this._.ep.getElement().getFirst();
Q
.setStyle(
'z-index',
parseInt(Q.$.style.zIndex, 10)
+ Math
.floor(this._.app.config.baseFloatZIndex / 2));
}
a.dialog._.dL = this._.ep;
if (!this._.ep) {
a.dialog._.gw = null;
P.removeListener('keydown', G);
P.removeListener(f.opera ? 'keypress' : 'keyup', H);
for ( var R in {
keyup : 1,
keydown : 1,
keypress : 1
})
P.removeListener(R, N);
var S = this._.app;
S.focus();
if (S.mode == 'qt' && g) {
var T = S.getSelection();
T && T.sd(true);
}
} else
a.dialog._.gw -= 10;
this.gh(function(U) {
U.ki && U.ki();
});
},
addPage : function(P) {
var Z = this;
var Q = [], R = P.label ? ' title="' + i.htmlEncode(P.label) + '"'
: '', S = P.elements, T = a.dialog._.gv.vbox.dQ(Z, {
type : 'vbox',
className : 'cke_dialog_page_contents',
children : P.elements,
expand : !!P.expand,
padding : P.padding,
style : P.style || 'width: 100%; height: 100%;'
}, Q), U = k.kE(Q.join(''), a.document), V = k.kE( [
'<a class="cke_dialog_tab"',
Z._.gV > 0 ? ' cke_last' : 'cke_first', R,
!!P.hidden ? ' style="display:none"' : '', ' id="',
P.id + '_', i.getNextNumber(),
'" href="javascript:void(0)"', ' hp="true">', P.label,
'</a>' ].join(''), a.document);
if (Z._.gV === 0)
Z.bO.dialog.addClass('cke_single_page');
else
Z.bO.dialog.removeClass('cke_single_page');
Z._.tabs[P.id] = [ V, U ];
Z._.cU.push(P.id);
Z._.gV++;
Z._.qF = V;
var W = Z._.contents[P.id] = {}, X, Y = T.getChild();
while (X = Y.shift()) {
W[X.id] = X;
if (typeof X.getChild == 'function')
Y.push.apply(Y, X.getChild());
}
U.setAttribute('name', P.id);
U.appendTo(Z.bO.contents);
V.unselectable();
Z.bO.tabs.append(V);
if (P.accessKey) {
I(Z, Z, 'bP+' + P.accessKey, L, K);
Z._.iX['bP+' + P.accessKey] = P.id;
}
},
selectPage : function(P) {
var U = this;
for ( var Q in U._.tabs) {
var R = U._.tabs[Q][0], S = U._.tabs[Q][1];
if (Q != P) {
R.removeClass('cke_dialog_tab_selected');
S.hide();
}
}
var T = U._.tabs[P];
T[0].addClass('cke_dialog_tab_selected');
T[1].show();
U._.gx = P;
U._.nM = i.indexOf(U._.cU, P);
},
vJ : function(P) {
var Q = this._.tabs[P] && this._.tabs[P][0];
if (!Q)
return;
Q.hide();
},
showPage : function(P) {
var Q = this._.tabs[P] && this._.tabs[P][0];
if (!Q)
return;
Q.show();
},
getElement : function() {
return this._.element;
},
getName : function() {
return this._.name;
},
getContentElement : function(P, Q) {
return this._.contents[P][Q];
},
getValueOf : function(P, Q) {
return this.getContentElement(P, Q).getValue();
},
setValueOf : function(P, Q, R) {
return this.getContentElement(P, Q).setValue(R);
},
getButton : function(P) {
return this._.buttons[P];
},
click : function(P) {
return this._.buttons[P].click();
},
disableButton : function(P) {
return this._.buttons[P].disable();
},
enableButton : function(P) {
return this._.buttons[P].enable();
},
vj : function() {
return this._.gV;
},
getParentApi : function() {
return this._.app.cg;
},
eY : function() {
return this._.app;
},
rf : function() {
return this.eY().getSelection().rf();
},
tQ : function(P, Q) {
var S = this;
if (typeof Q == 'undefined') {
Q = S._.eO.length;
S._.eO.push(new s(S, P, Q));
} else {
S._.eO.splice(Q, 0, new s(S, P, Q));
for ( var R = Q + 1; R < S._.eO.length; R++)
S._.eO[R].cQ++;
}
},
setTitle : function(P) {
this.bO.title.setText(P);
}
};
i.extend(a.dialog, {
add : function(P, Q) {
if (!this._.ev[P] || typeof Q == 'function')
this._.ev[P] = Q;
},
exists : function(P) {
return !!this._.ev[P];
},
getCurrent : function() {
return a.dialog._.dL;
},
okButton : (function() {
var P = function(Q, R) {
R = R || {};
return i.extend( {
id : 'ok',
type : 'button',
label : Q.lang.common.ok,
'class' : 'cke_dialog_ui_button_ok',
onClick : function(S) {
var T = S.data.dialog;
if (T.oW('ok', {
hide : true
}).hide !== false)
T.hide();
}
}, R, true);
};
P.type = 'button';
P.override = function(Q) {
return i.extend(function(R) {
return P(R, Q);
}, {
type : 'button'
}, true);
};
return P;
})(),
cancelButton : (function() {
var P = function(Q, R) {
R = R || {};
return i.extend( {
id : 'cancel',
type : 'button',
label : Q.lang.common.cancel,
'class' : 'cke_dialog_ui_button_cancel',
onClick : function(S) {
var T = S.data.dialog;
if (T.oW('cancel', {
hide : true
}).hide !== false)
T.hide();
}
}, R, true);
};
P.type = 'button';
P.override = function(Q) {
return i.extend(function(R) {
return P(R, Q);
}, {
type : 'button'
}, true);
};
return P;
})(),
addUIElement : function(P, Q) {
this._.gv[P] = Q;
}
});
a.dialog._ = {
gv : {},
ev : {},
dL : null,
gw : null
};
a.event.du(a.dialog);
a.event.du(a.dialog.prototype, true);
var t = {
resizable : a.DIALOG_RESIZE_NONE,
minWidth : 600,
minHeight : 400,
buttons : [ a.dialog.okButton, a.dialog.cancelButton ]
}, u = function(P, Q, R) {
for ( var S = 0, T; T = P[S]; S++) {
if (T.id == Q)
return T;
if (R && T[R]) {
var U = u(T[R], Q, R);
if (U)
return U;
}
}
return null;
}, v = function(P, Q, R, S, T) {
if (R) {
for ( var U = 0, V; V = P[U]; U++) {
if (V.id == R) {
P.splice(U, 0, Q);
return Q;
}
if (S && V[S]) {
var W = v(V[S], Q, R, S, true);
if (W)
return W;
}
}
if (T)
return null;
}
P.push(Q);
return Q;
}, w = function(P, Q, R) {
for ( var S = 0, T; T = P[S]; S++) {
if (T.id == Q)
return P.splice(S, 1);
if (R && T[R]) {
var U = w(T[R], Q, R);
if (U)
return U;
}
}
return null;
}, x = function(P, Q) {
this.dialog = P;
var R = Q.contents;
for ( var S = 0, T; T = R[S]; S++)
R[S] = new y(P, T);
i.extend(this, Q);
};
x.prototype = {
vz : function(P) {
return u(this.contents, P);
},
getButton : function(P) {
return u(this.buttons, P);
},
uh : function(P, Q) {
return v(this.contents, P, Q);
},
qW : function(P, Q) {
return v(this.buttons, P, Q);
},
uP : function(P) {
w(this.contents, P);
},
uO : function(P) {
w(this.buttons, P);
}
};
function y(P, Q) {
this._ = {
dialog : P
};
i.extend(this, Q);
}
;
y.prototype = {
eB : function(P) {
return u(this.elements, P, 'children');
},
add : function(P, Q) {
return v(this.elements, P, Q, 'children');
},
remove : function(P) {
w(this.elements, P, 'children');
}
};
function z(P) {
var Q = null, R = null, S = P.getElement().getFirst(), T = P.eY(), U = T.config.dialog_magnetDistance, V = T.skin.margins
|| [ 0, 0, 0, 0 ];
if (typeof U == 'undefined')
U = 20;
function W(Y) {
var Z = P.hR(), aa = a.document.getWindow().eR(), aT = Y.data.$.screenX, bm = Y.data.$.screenY, bW = aT
- Q.x, eS = bm - Q.y, fv, aP;
Q = {
x : aT,
y : bm
};
R.x += bW;
R.y += eS;
if (R.x + V[3] < U)
fv = -V[3];
else if (R.x - V[1] > aa.width - Z.width - U)
fv = aa.width - Z.width + V[1];
else
fv = R.x;
if (R.y + V[0] < U)
aP = -V[0];
else if (R.y - V[2] > aa.height - Z.height - U)
aP = aa.height - Z.height + V[2];
else
aP = R.y;
P.move(fv, aP, 1);
Y.data.preventDefault();
}
;
function X(Y) {
a.document.removeListener('mousemove', W);
a.document.removeListener('mouseup', X);
if (f.ie6Compat) {
var Z = C.getChild(0).getFrameDocument();
Z.removeListener('mousemove', W);
Z.removeListener('mouseup', X);
}
}
;
P.bO.title.on('mousedown', function(Y) {
Q = {
x : Y.data.$.screenX,
y : Y.data.$.screenY
};
a.document.on('mousemove', W);
a.document.on('mouseup', X);
R = P.gz();
if (f.ie6Compat) {
var Z = C.getChild(0).getFrameDocument();
Z.on('mousemove', W);
Z.on('mouseup', X);
}
Y.data.preventDefault();
}, P);
}
;
function A(P) {
var Q = P.dg, R = Q.resizable;
if (R == a.DIALOG_RESIZE_NONE)
return;
var S = P.eY(), T, U, V, W, X, Y;
function Z(bW) {
if (P._.moved && S.lang.dir == 'rtl') {
var eS = P._.element.getFirst();
eS.setStyle('right', bW + 'px');
eS.removeStyle('left');
} else if (!P._.moved)
P.layout();
}
;
function aa(bW) {
X = P.hR();
bW = bW.data.$;
var eS = P.bO.contents, fv = eS.$
.getElementsByTagName('iframe').length;
if (fv) {
Y = k
.kE('<div class="cke_dialog_resize_cover" style="height: 100%; position: absolute; width: 100%;"></div>');
eS.append(Y);
}
U = X.height
- P.bO.contents.hR('height', !(f.gecko || f.opera || g
&& f.quirks));
T = X.width - P.bO.contents.hR('width', 1);
W = {
x : bW.screenX,
y : bW.screenY
};
V = a.document.getWindow().eR();
a.document.on('mousemove', aT);
a.document.on('mouseup', bm);
if (f.ie6Compat) {
var aP = C.getChild(0).getFrameDocument();
aP.on('mousemove', aT);
aP.on('mouseup', bm);
}
bW.preventDefault && bW.preventDefault();
}
;
P.on('load', function() {
var bW = '';
if (R == a.DIALOG_RESIZE_WIDTH)
bW = ' cke_resizer_horizontal';
else if (R == a.DIALOG_RESIZE_HEIGHT)
bW = ' cke_resizer_vertical';
var eS = k.kE('<div class="cke_resizer' + bW + '"' + ' title="'
+ i.htmlEncode(S.lang.resize) + '"></div>');
eS.on('mousedown', aa);
P.bO.footer.append(eS, 1);
});
S.on('destroy', function() {
i.removeFunction(aa);
});
function aT(bW) {
var eS = S.lang.dir == 'rtl', fv = (bW.data.$.screenX - W.x)
* (eS ? -1 : 1), aP = bW.data.$.screenY - W.y, bV = X.width, eN = X.height, gB = bV
+ fv * (P._.moved ? 1 : 2), dX = eN + aP
* (P._.moved ? 1 : 2), gs = P._.element.getFirst(), am = eS
&& gs.getComputedStyle('right'), gP = P.gz();
if (am)
am = am == 'auto' ? V.width - (gP.x || 0) - gs.hR('width')
: parseInt(am, 10);
if (gP.y + dX > V.height)
dX = V.height - gP.y;
if ((eS ? am : gP.x) + gB > V.width)
gB = V.width - (eS ? am : gP.x);
if ((R == a.DIALOG_RESIZE_WIDTH || R == a.DIALOG_RESIZE_BOTH)
&& !(eS && fv > 0 && !gP.x))
bV = Math.max(Q.minWidth || 0, gB - T);
if (R == a.DIALOG_RESIZE_HEIGHT || R == a.DIALOG_RESIZE_BOTH)
eN = Math.max(Q.minHeight || 0, dX - U);
P.resize(bV, eN);
Z(am);
bW.data.preventDefault();
}
;
function bm() {
a.document.removeListener('mouseup', bm);
a.document.removeListener('mousemove', aT);
if (Y) {
Y.remove();
Y = null;
}
if (f.ie6Compat) {
var bW = C.getChild(0).getFrameDocument();
bW.removeListener('mouseup', bm);
bW.removeListener('mousemove', aT);
}
if (S.lang.dir == 'rtl') {
var eS = P._.element.getFirst(), fv = eS
.getComputedStyle('left');
if (fv == 'auto')
fv = V.width - parseInt(eS.rd('right'), 10)
- P.hR().width;
else
fv = parseInt(fv, 10);
eS.removeStyle('right');
P._.position.x += 1;
P.move(fv, P._.position.y);
}
}
;
}
;
var B, C, D = function(P) {
var Q = a.document.getWindow();
if (!C) {
var R = P.config.dialog_backgroundCoverColor || 'white', S = [
'<div style="position: ',
f.ie6Compat ? 'absolute' : 'fixed', '; z-index: ',
P.config.baseFloatZIndex, '; top: 0px; left: 0px; ',
!f.ie6Compat ? 'background-color: ' + R : '',
'" id="cke_dialog_background_cover">' ];
if (f.ie6Compat) {
var T = f.isCustomDomain(), U = "<html><body style=\\'background-color:"
+ R + ";\\'></body></html>";
S
.push('<iframe hp="true" frameborder="0" id="cke_dialog_background_iframe" src="javascript:');
S.push('void((function(){document.open();'
+ (T ? "document.domain='" + document.domain + "';"
: '') + "document.write( '" + U + "' );"
+ 'document.close();' + '})())');
S
.push('" style="position:absolute;left:0;top:0;width:100%;height: 100%;progid:DXImageTransform.Microsoft.Alpha(opacity=0)"></iframe>');
}
S.push('</div>');
C = k.kE(S.join(''), a.document);
}
var V = C, W = function() {
var aa = Q.eR();
V.setStyles( {
width : aa.width + 'px',
height : aa.height + 'px'
});
}, X = function() {
var aa = Q.hV(), aT = a.dialog._.dL;
V.setStyles( {
left : aa.x + 'px',
top : aa.y + 'px'
});
do {
var bm = aT.gz();
aT.move(bm.x, bm.y);
} while (aT = aT._.ep);
};
B = W;
Q.on('resize', W);
W();
if (f.ie6Compat) {
var Y = function() {
X();
arguments.callee.lw.apply(this, arguments);
};
Q.$.setTimeout(function() {
Y.lw = window.onscroll || (function() {
});
window.onscroll = Y;
}, 0);
X();
}
var Z = P.config.dialog_backgroundCoverOpacity;
V.setOpacity(typeof Z != 'undefined' ? Z : 0.5);
V.appendTo(a.document.bH());
}, E = function() {
if (!C)
return;
var P = a.document.getWindow();
C.remove();
P.removeListener('resize', B);
if (f.ie6Compat)
P.$.setTimeout(function() {
var Q = window.onscroll && window.onscroll.lw;
window.onscroll = Q || null;
}, 0);
B = null;
}, F = {}, G = function(P) {
var Q = P.data.$.ctrlKey || P.data.$.metaKey, R = P.data.$.altKey, S = P.data.$.shiftKey, T = String
.fromCharCode(P.data.$.keyCode), U = F[(Q ? 'bP+' : '')
+ (R ? 'eJ+' : '') + (S ? 'dy+' : '') + T];
if (!U || !U.length)
return;
U = U[U.length - 1];
U.keydown && U.keydown.call(U.bf, U.dialog, U.iK);
P.data.preventDefault();
}, H = function(P) {
var Q = P.data.$.ctrlKey || P.data.$.metaKey, R = P.data.$.altKey, S = P.data.$.shiftKey, T = String
.fromCharCode(P.data.$.keyCode), U = F[(Q ? 'bP+' : '')
+ (R ? 'eJ+' : '') + (S ? 'dy+' : '') + T];
if (!U || !U.length)
return;
U = U[U.length - 1];
if (U.keyup) {
U.keyup.call(U.bf, U.dialog, U.iK);
P.data.preventDefault();
}
}, I = function(P, Q, R, S, T) {
var U = F[R] || (F[R] = []);
U.push( {
bf : P,
dialog : Q,
iK : R,
keyup : T || P.eZ,
keydown : S || P.iU
});
}, J = function(P) {
for ( var Q in F) {
var R = F[Q];
for ( var S = R.length - 1; S >= 0; S--) {
if (R[S].dialog == P || R[S].bf == P)
R.splice(S, 1);
}
if (R.length === 0)
delete F[Q];
}
}, K = function(P, Q) {
if (P._.iX[Q])
P.selectPage(P._.iX[Q]);
}, L = function(P, Q) {
}, M = {
27 : 1,
13 : 1
}, N = function(P) {
if (P.data.db() in M)
P.data.stopPropagation();
};
(function() {
n.dialog = {
bf : function(P, Q, R, S, T, U, V) {
if (arguments.length < 4)
return;
var W = (S.call ? S(Q) : S) || 'div', X = [ '<', W, ' ' ], Y = (T
&& T.call ? T(Q) : T)
|| {}, Z = (U && U.call ? U(Q) : U) || {}, aa = (V
&& V.call ? V(P, Q) : V) || '', aT = this.oJ = Z.id
|| i.getNextNumber() + '_uiElement', bm = this.id = Q.id, bW;
Z.id = aT;
var eS = {};
if (Q.type)
eS['cke_dialog_ui_' + Q.type] = 1;
if (Q.className)
eS[Q.className] = 1;
var fv = Z['class'] && Z['class'].split ? Z['class']
.split(' ') : [];
for (bW = 0; bW < fv.length; bW++) {
if (fv[bW])
eS[fv[bW]] = 1;
}
var aP = [];
for (bW in eS)
aP.push(bW);
Z['class'] = aP.join(' ');
if (Q.title)
Z.title = Q.title;
var bV = (Q.style || '').split(';');
for (bW in Y)
bV.push(bW + ':' + Y[bW]);
if (Q.hidden)
bV.push('display:none');
for (bW = bV.length - 1; bW >= 0; bW--) {
if (bV[bW] === '')
bV.splice(bW, 1);
}
if (bV.length > 0)
Z.style = (Z.style ? Z.style + '; ' : '')
+ bV.join('; ');
for (bW in Z)
X.push(bW + '="' + i.htmlEncode(Z[bW]) + '" ');
X.push('>', aa, '</', W, '>');
R.push(X.join(''));
(this._ || (this._ = {})).dialog = P;
if (typeof Q.isChanged == 'boolean')
this.isChanged = function() {
return Q.isChanged;
};
if (typeof Q.isChanged == 'function')
this.isChanged = Q.isChanged;
a.event.du(this);
this.nc(Q);
if (this.eZ && this.iU && Q.accessKey)
I(this, P, 'bP+' + Q.accessKey);
var eN = this;
P.on('load', function() {
if (eN.getInputElement())
eN.getInputElement().on('focus', function() {
P._.eC = false;
P._.hasFocus = true;
eN.oW('focus');
}, eN);
});
if (this.eA) {
this.cQ = P._.eO.push(this) - 1;
this.on('focus', function() {
P._.gu = eN.cQ;
});
}
i.extend(this, Q);
},
hbox : function(P, Q, R, S, T) {
if (arguments.length < 4)
return;
this._ || (this._ = {});
var U = this._.children = Q, V = T && T.widths || null, W = T
&& T.height || null, X = {}, Y, Z = function() {
var aa = [ '<tbody><tr class="cke_dialog_ui_hbox">' ];
for (Y = 0; Y < R.length; Y++) {
var aT = 'cke_dialog_ui_hbox_child', bm = [];
if (Y === 0)
aT = 'cke_dialog_ui_hbox_first';
if (Y == R.length - 1)
aT = 'cke_dialog_ui_hbox_last';
aa.push('<td class="', aT, '" ');
if (V) {
if (V[Y])
bm.push('width:' + i.cssLength(V[Y]));
} else
bm
.push('width:' + Math
.floor(100 / R.length) + '%');
if (W)
bm.push('height:' + i.cssLength(W));
if (T && T.padding != undefined)
bm.push('padding:' + i.cssLength(T.padding));
if (bm.length > 0)
aa.push('style="' + bm.join('; ') + '" ');
aa.push('>', R[Y], '</td>');
}
aa.push('</tr></tbody>');
return aa.join('');
};
n.dialog.bf.call(this, P, T || {
type : 'hbox'
}, S, 'table', X, T && T.align && {
align : T.align
} || null, Z);
},
vbox : function(P, Q, R, S, T) {
if (arguments.length < 3)
return;
this._ || (this._ = {});
var U = this._.children = Q, V = T && T.width || null, W = T
&& T.vY || null, X = function() {
var Y = [ '<table cellspacing="0" border="0" ' ];
Y.push('style="');
if (T && T.expand)
Y.push('height:100%;');
Y.push('width:' + i.cssLength(V || '100%'), ';');
Y.push('"');
Y.push('align="', i
.htmlEncode(T
&& T.align
|| (P.eY().lang.dir == 'ltr' ? 'left'
: 'right')), '" ');
Y.push('><tbody>');
for ( var Z = 0; Z < R.length; Z++) {
var aa = [];
Y.push('<tr><td ');
if (V)
aa.push('width:' + i.cssLength(V || '100%'));
if (W)
aa.push('height:' + i.cssLength(W[Z]));
else if (T && T.expand)
aa
.push('height:' + Math
.floor(100 / R.length) + '%');
if (T && T.padding != undefined)
aa.push('padding:' + i.cssLength(T.padding));
if (aa.length > 0)
Y.push('style="', aa.join('; '), '" ');
Y.push(' class="cke_dialog_ui_vbox_child">', R[Z],
'</td></tr>');
}
Y.push('</tbody></table>');
return Y.join('');
};
n.dialog.bf.call(this, P, T || {
type : 'vbox'
}, S, 'div', null, null, X);
}
};
})();
n.dialog.bf.prototype = {
getElement : function() {
return a.document.getById(this.oJ);
},
getInputElement : function() {
return this.getElement();
},
getDialog : function() {
return this._.dialog;
},
setValue : function(P) {
this.getInputElement().setValue(P);
this.oW('change', {
value : P
});
return this;
},
getValue : function() {
return this.getInputElement().getValue();
},
isChanged : function() {
return false;
},
selectParentTab : function() {
var S = this;
var P = S.getInputElement(), Q = P, R;
while ((Q = Q.getParent())
&& Q.$.className.search('cke_dialog_page_contents') == -1) {
}
if (!Q)
return S;
R = Q.getAttribute('name');
if (S._.dialog._.gx != R)
S._.dialog.selectPage(R);
return S;
},
focus : function() {
this.selectParentTab().getInputElement().focus();
return this;
},
nc : function(P) {
var Q = /^on([A-Z]\w+)/, R, S = function(U, V, W, X) {
V.on('load', function() {
U.getInputElement().on(W, X, U);
});
};
for ( var T in P) {
if (!(R = T.match(Q)))
continue;
if (this.dm[T])
this.dm[T].call(this, this._.dialog, P[T]);
else
S(this, this._.dialog, R[1].toLowerCase(), P[T]);
}
return this;
},
dm : {
onLoad : function(P, Q) {
P.on('load', Q, this);
},
onShow : function(P, Q) {
P.on('show', Q, this);
},
onHide : function(P, Q) {
P.on('hide', Q, this);
}
},
iU : function(P, Q) {
this.focus();
},
eZ : function(P, Q) {
},
disable : function() {
var P = this.getInputElement();
P.setAttribute('disabled', 'true');
P.addClass('cke_disabled');
},
enable : function() {
var P = this.getInputElement();
P.removeAttribute('disabled');
P.removeClass('cke_disabled');
},
isEnabled : function() {
return !this.getInputElement().getAttribute('disabled');
},
isVisible : function() {
return this.getInputElement().isVisible();
},
fM : function() {
if (!this.isEnabled() || !this.isVisible())
return false;
return true;
}
};
n.dialog.hbox.prototype = i
.extend(
new n.dialog.bf(),
{
getChild : function(P) {
var Q = this;
if (arguments.length < 1)
return Q._.children.concat();
if (!P.splice)
P = [ P ];
if (P.length < 2)
return Q._.children[P[0]];
else
return Q._.children[P[0]]
&& Q._.children[P[0]].getChild ? Q._.children[P[0]]
.getChild(P.slice(1, P.length))
: null;
}
}, true);
n.dialog.vbox.prototype = new n.dialog.hbox();
(function() {
var P = {
dQ : function(Q, R, S) {
var T = R.children, U, V = [], W = [];
for ( var X = 0; X < T.length && (U = T[X]); X++) {
var Y = [];
V.push(Y);
W.push(a.dialog._.gv[U.type].dQ(Q, U, Y));
}
return new n.dialog[R.type](Q, W, V, S, R);
}
};
a.dialog.addUIElement('hbox', P);
a.dialog.addUIElement('vbox', P);
})();
a.rB = function(P) {
this.ry = P;
};
a.rB.prototype = {
exec : function(P) {
P.openDialog(this.ry);
},
sG : false
};
(function() {
var P = /^([a]|[^a])+$/, Q = /^\d*$/, R = /^\d*(?:\.\d+)?$/;
a.sg = 1;
a.jb = 2;
a.dialog.validate = {
functions : function() {
return function() {
var Y = this;
var S = Y && Y.getValue ? Y.getValue() : arguments[0], T = undefined, U = a.jb, V = [], W;
for (W = 0; W < arguments.length; W++) {
if (typeof arguments[W] == 'function')
V.push(arguments[W]);
else
break;
}
if (W < arguments.length
&& typeof arguments[W] == 'string') {
T = arguments[W];
W++;
}
if (W < arguments.length
&& typeof arguments[W] == 'number')
U = arguments[W];
var X = U == a.jb ? true : false;
for (W = 0; W < V.length; W++) {
if (U == a.jb)
X = X && V[W](S);
else
X = X || V[W](S);
}
if (!X) {
if (T !== undefined)
alert(T);
if (Y && (Y.select || Y.focus))
Y.select || Y.focus();
return false;
}
return true;
};
},
regex : function(S, T) {
return function() {
var V = this;
var U = V && V.getValue ? V.getValue() : arguments[0];
if (!S.test(U)) {
if (T !== undefined)
alert(T);
if (V && (V.select || V.focus))
if (V.select)
V.select();
else
V.focus();
return false;
}
return true;
};
},
notEmpty : function(S) {
return this.regex(P, S);
},
integer : function(S) {
return this.regex(Q, S);
},
number : function(S) {
return this.regex(R, S);
},
equals : function(S, T) {
return this.functions(function(U) {
return U == S;
}, T);
},
notEqual : function(S, T) {
return this.functions(function(U) {
return U != S;
}, T);
}
};
})();
function O(P, Q) {
var R = function() {
T(this);
Q(this);
}, S = function() {
T(this);
}, T = function(U) {
U.removeListener('ok', R);
U.removeListener('cancel', S);
};
P.on('ok', R);
P.on('cancel', S);
}
;
i
.extend(
a.application.prototype,
{
openDialog : function(P, Q, R) {
var S = a.dialog._.ev[P];
if (typeof S == 'function') {
var T = this._.oB || (this._.oB = {}), U = T[P]
|| (T[P] = new a.dialog(this, P));
Q && Q.call(U, U);
U.show();
return U;
} else if (S == 'failed')
throw new Error(
'[CKFINDER.dialog.openDialog] Dialog "' + P + '" failed when loading dg.');
var V = a.document.bH(), W = V.$.style.cursor, X = this;
V.setStyle('cursor', 'wait');
a.ec.load(a.getUrl(S), function() {
if (typeof a.dialog._.ev[P] != 'function')
a.dialog._.ev[P] = 'failed';
X.openDialog(P, Q);
V.setStyle('cursor', W);
}, null, null, R);
return null;
},
hs : function(P, Q, R, S) {
var T = this;
setTimeout(function() {
T.cg.openDialog('Input', function(U) {
U.show();
U.setTitle(P
|| T.lang.common.inputTitle);
U.getContentElement('tab1', 'msg')
.getElement().setHtml(Q);
U.getContentElement('tab1', 'input')
.setValue(R);
O(U, function(V) {
var W = V.getContentElement('tab1',
'input').getValue();
S(W);
});
});
}, 0);
},
msgDialog : function(P, Q, R) {
var S = this;
setTimeout(function() {
S.cg.openDialog('Msg', function(T) {
T.show();
T.setTitle(P
|| S.lang.common.messageTitle);
T.getContentElement('tab1', 'msg')
.getElement().setHtml(Q);
R && O(T, function(U) {
R();
});
});
}, 0);
},
fe : function(P, Q, R) {
var S = this;
setTimeout(
function() {
S.cg
.openDialog(
'Confirm',
function(T) {
T.show();
T
.setTitle(P
|| S.lang.common.confirmationTitle);
T
.getContentElement(
'tab1',
'msg')
.getElement()
.setHtml(
Q);
O(
T,
function(
U) {
R();
});
});
}, 0);
}
});
m.add('dialog', {
bM : [ 'dialogui' ],
onLoad : function() {
a.dialog.add('Confirm', function(P) {
return {
title : P.lang.common.confirmationTitle,
minWidth : 270,
minHeight : 60,
contents : [ {
id : 'tab1',
elements : [ {
type : 'html',
html : '',
id : 'msg'
} ]
} ],
buttons : [ CKFinder.dialog.okButton,
CKFinder.dialog.cancelButton ]
};
});
a.dialog.add('Msg', function(P) {
return {
title : P.lang.common.messageTitle,
minWidth : 270,
minHeight : 60,
contents : [ {
id : 'tab1',
elements : [ {
type : 'html',
html : '',
id : 'msg'
} ]
} ],
buttons : [ CKFinder.dialog.okButton ]
};
});
a.dialog.add('Input', function(P) {
return {
title : P.lang.common.inputTitle,
minWidth : 270,
minHeight : 60,
contents : [ {
id : 'tab1',
elements : [ {
type : 'html',
html : '',
id : 'msg'
}, {
type : 'text',
id : 'input'
} ]
} ],
buttons : [ CKFinder.dialog.okButton,
CKFinder.dialog.cancelButton ]
};
});
}
});
})();
m.add('dialogui');
(function() {
var p = function(w) {
var z = this;
z._ || (z._ = {});
z._['default'] = z._.hq = w['default'] || '';
var x = [ z._ ];
for ( var y = 1; y < arguments.length; y++)
x.push(arguments[y]);
x.push(true);
i.extend.apply(i, x);
return z._;
}, q = {
dQ : function(w, x, y) {
return new n.dialog.ju(w, x, y);
}
}, r = {
dQ : function(w, x, y) {
return new n.dialog[x.type](w, x, y);
}
}, s = {
isChanged : function() {
return this.getValue() != this.lu();
},
reset : function() {
this.setValue(this.lu());
},
jW : function() {
this._.hq = this.getValue();
},
ki : function() {
this._.hq = this._['default'];
},
lu : function() {
return this._.hq;
}
}, t = i.extend( {}, n.dialog.bf.prototype.dm, {
onChange : function(w, x) {
if (!this._.pL) {
w.on('load', function() {
this.getInputElement().on('change', function() {
this.oW('change', {
value : this.getValue()
});
}, this);
}, this);
this._.pL = true;
}
this.on('change', x);
}
}, true), u = /^on([A-Z]\w+)/, v = function(w) {
for ( var x in w) {
if (u.test(x) || x == 'title' || x == 'type')
delete w[x];
}
return w;
};
i
.extend(
n.dialog,
{
dD : function(w, x, y, z) {
if (arguments.length < 4)
return;
var A = p.call(this, x);
A.hz = i.getNextNumber() + '_label';
var B = this._.children = [], C = function() {
var D = [];
if (x.uC != 'horizontal')
D
.push(
'<div class="cke_dialog_ui_labeled_label" id="',
A.hz,
'" >',
x.label,
'</div>',
'<div class="cke_dialog_ui_labeled_content">',
z(w, x), '</div>');
else {
var E = {
type : 'hbox',
widths : x.widths,
padding : 0,
children : [
{
type : 'html',
html : '<span class="cke_dialog_ui_labeled_label" id="'
+ A.hz
+ '">'
+ i
.htmlEncode(x.label)
+ '</span>'
},
{
type : 'html',
html : '<span class="cke_dialog_ui_labeled_content">' + z(
w, x) + '</span>'
} ]
};
a.dialog._.gv.hbox.dQ(w, E, D);
}
return D.join('');
};
n.dialog.bf.call(this, w, x, y, 'div', null,
null, C);
},
ju : function(w, x, y) {
if (arguments.length < 3)
return;
p.call(this, x);
var z = this._.le = i.getNextNumber() + '_textInput', A = {
'class' : 'cke_dialog_ui_input_' + x.type,
id : z,
type : 'text'
}, B;
if (x.validate)
this.validate = x.validate;
if (x.maxLength)
A.uy = x.maxLength;
if (x.size)
A.size = x.size;
var C = this, D = false;
w
.on(
'load',
function() {
C
.getInputElement()
.on(
'keydown',
function(F) {
if (F.data
.db() == 13)
D = true;
});
C
.getInputElement()
.on(
'keyup',
function(F) {
if (F.data
.db() == 13
&& D) {
w
.getButton('ok')
&& setTimeout(
function() {
w
.getButton(
'ok')
.click();
},
0);
D = false;
}
}, null,
null, 1000);
});
var E = function() {
var F = [
'<div class="cke_dialog_ui_input_',
x.type, '"' ];
if (x.width)
F
.push('style="width:' + x.width + '" ');
F.push('><input ');
for ( var G in A)
F.push(G + '="' + A[G] + '" ');
F.push(' /></div>');
return F.join('');
};
n.dialog.dD.call(this, w, x, y, E);
},
textarea : function(w, x, y) {
if (arguments.length < 3)
return;
p.call(this, x);
var z = this, A = this._.le = i.getNextNumber() + '_textarea', B = {};
if (x.validate)
this.validate = x.validate;
B.rows = x.rows || 5;
B.cols = x.cols || 20;
var C = function() {
var D = [
'<div class="cke_dialog_ui_input_textarea"><textarea class="cke_dialog_ui_input_textarea" id="',
A, '" ' ];
for ( var E in B)
D.push(E + '="' + i.htmlEncode(B[E])
+ '" ');
D.push('>', i.htmlEncode(z._['default']),
'</textarea></div>');
return D.join('');
};
n.dialog.dD.call(this, w, x, y, C);
},
checkbox : function(w, x, y) {
if (arguments.length < 3)
return;
var z = p.call(this, x, {
'default' : !!x['default']
});
if (x.validate)
this.validate = x.validate;
var A = function() {
var B = i.extend( {}, x, {
id : x.id ? x.id + '_checkbox' : i
.getNextNumber() + '_checkbox'
}, true), C = [], D = {
'class' : 'cke_dialog_ui_checkbox_input',
type : 'checkbox'
};
v(B);
if (x['default'])
D.checked = 'checked';
z.checkbox = new n.dialog.bf(w, B, C,
'input', null, D);
C.push(' <label for="', D.id, '">', i
.htmlEncode(x.label), '</label>');
return C.join('');
};
n.dialog.bf.call(this, w, x, y, 'span', null,
null, A);
},
radio : function(w, x, y) {
if (arguments.length < 3)
return;
p.call(this, x);
if (!this._['default'])
this._['default'] = this._.hq = x.items[0][1];
if (x.validate)
this.validate = x.sh;
var z = [], A = this, B = function() {
var C = [], D = [], E = {
'class' : 'cke_dialog_ui_radio_item'
}, F = x.id ? x.id + '_radio' : i
.getNextNumber() + '_radio';
for ( var G = 0; G < x.items.length; G++) {
var H = x.items[G], I = H[2] !== undefined ? H[2]
: H[0], J = H[1] !== undefined ? H[1]
: H[0], K = i
.extend(
{},
x,
{
id : i
.getNextNumber() + '_radio_input',
title : null,
type : null
}, true), L = i.extend(
{}, K, {
id : null,
title : I
}, true), M = {
type : 'radio',
'class' : 'cke_dialog_ui_radio_input',
name : F,
value : J
}, N = [];
if (A._['default'] == J)
M.checked = 'checked';
v(K);
v(L);
z.push(new n.dialog.bf(w, K, N,
'input', null, M));
N.push(' ');
new n.dialog.bf(w, L, N, 'label', null,
{
'for' : M.id
}, H[0]);
C.push(N.join(''));
}
new n.dialog.hbox(w, [], C, D);
return D.join('');
};
n.dialog.dD.call(this, w, x, y, B);
this._.children = z;
},
button : function(w, x, y) {
if (!arguments.length)
return;
if (typeof x == 'function')
x = x(w.eY());
p.call(this, x, {
disabled : x.disabled || false
});
a.event.du(this);
var z = this;
w.on('load', function(B) {
var C = this.getElement();
(function() {
C.on('click', function(D) {
z.oW('click', {
dialog : z.getDialog()
});
D.data.preventDefault();
});
})();
C.unselectable();
}, this);
var A = i.extend( {}, x);
delete A.style;
n.dialog.bf.call(this, w, A, y, 'a', null, {
style : x.style,
href : 'javascript:void(0)',
title : x.label,
hp : 'true',
'class' : x['class']
}, '<span class="cke_dialog_ui_button">' + i
.htmlEncode(x.label) + '</span>');
},
select : function(w, x, y) {
if (arguments.length < 3)
return;
var z = p.call(this, x);
if (x.validate)
this.validate = x.validate;
var A = function() {
var B = i.extend( {}, x, {
id : x.id ? x.id + '_select' : i
.getNextNumber() + '_select'
}, true), C = [], D = [], E = {
'class' : 'cke_dialog_ui_input_select'
};
if (x.size != undefined)
E.size = x.size;
if (x.multiple != undefined)
E.multiple = x.multiple;
v(B);
for ( var F = 0, G; F < x.items.length
&& (G = x.items[F]); F++)
D
.push(
'<option value="',
i
.htmlEncode(G[1] !== undefined ? G[1]
: G[0]),
'" /> ',
i.htmlEncode(G[0]));
z.select = new n.dialog.bf(w, B, C,
'select', null, E, D.join(''));
return C.join('');
};
n.dialog.dD.call(this, w, x, y, A);
},
file : function(w, x, y) {
if (arguments.length < 3)
return;
if (x['default'] === undefined)
x['default'] = '';
var z = i.extend(p.call(this, x), {
dg : x,
buttons : []
});
if (x.validate)
this.validate = x.validate;
var A = function() {
z.gL = i.getNextNumber() + '_fileInput';
var B = f.isCustomDomain(), C = [
'<iframe frameborder="0" allowtransparency="0" class="cke_dialog_ui_input_file" id="',
z.gL, '" title="', x.label,
'" src="javascript:void(' ];
C
.push(B ? "(function(){document.open();document.domain='"
+ document.domain
+ "';"
+ 'document.close();'
+ '})()'
: '0');
C.push(')"></iframe>');
return C.join('');
};
w.on('load', function() {
var B = a.document.getById(z.gL), C = B
.getParent();
C.addClass('cke_dialog_ui_input_file');
});
n.dialog.dD.call(this, w, x, y, A);
},
fileButton : function(w, x, y) {
if (arguments.length < 3)
return;
var z = p.call(this, x), A = this;
if (x.validate)
this.validate = x.validate;
var B = i.extend( {}, x), C = B.onClick;
B.className = (B.className ? B.className + ' '
: '') + 'cke_dialog_ui_button';
B.onClick = function(D) {
var E = x['for'];
if (!C || C.call(this, D) !== false) {
w.getContentElement(E[0], E[1])
.submit();
this.disable();
}
};
w.on('load', function() {
w.getContentElement(x['for'][0],
x['for'][1])._.buttons.push(A);
});
n.dialog.button.call(this, w, B, y);
},
html : (function() {
var w = /^\s*<[\w:]+\s+([^>]*)?>/, x = /^(\s*<[\w:]+(?:\s+[^>]*)?)((?:.|\r|\n)+)$/, y = /\/$/;
return function(z, A, B) {
if (arguments.length < 3)
return;
var C = [], D, E = A.html, F, G;
if (E.charAt(0) != '<')
E = '<span>' + E + '</span>';
if (A.focus) {
var H = this.focus;
this.focus = function() {
H.call(this);
A.focus.call(this);
this.oW('focus');
};
if (A.fM) {
var I = this.fM;
this.fM = I;
}
this.eA = true;
}
n.dialog.bf.call(this, z, A, C, 'span',
null, null, '');
D = C.join('');
F = D.match(w);
G = E.match(x) || [ '', '', '' ];
if (y.test(G[1])) {
G[1] = G[1].slice(0, -1);
G[2] = '/' + G[2];
}
B.push( [ G[1], ' ', F[1] || '', G[2] ]
.join(''));
};
})()
}, true);
n.dialog.html.prototype = new n.dialog.bf();
n.dialog.dD.prototype = i.extend(new n.dialog.bf(), {
rW : function(w) {
var x = a.document.getById(this._.hz);
if (x.iu() < 1)
new h.text(w, a.document).appendTo(x);
else
x.getChild(0).$.nodeValue = w;
return this;
},
vt : function() {
var w = a.document.getById(this._.hz);
if (!w || w.iu() < 1)
return '';
else
return w.getChild(0).getText();
},
dm : t
}, true);
n.dialog.button.prototype = i.extend(new n.dialog.bf(), {
click : function() {
var w = this;
if (!w._.disabled)
return w.oW('click', {
dialog : w._.dialog
});
w.getElement().$.blur();
return false;
},
enable : function() {
this._.disabled = false;
var w = this.getElement();
w && w.removeClass('disabled');
},
disable : function() {
this._.disabled = true;
this.getElement().addClass('disabled');
},
isVisible : function() {
return this.getElement().getFirst().isVisible();
},
isEnabled : function() {
return !this._.disabled;
},
dm : i.extend( {}, n.dialog.bf.prototype.dm, {
onClick : function(w, x) {
this.on('click', x);
}
}, true),
eZ : function() {
this.click();
},
iU : function() {
this.focus();
},
eA : true
}, true);
n.dialog.ju.prototype = i.extend(new n.dialog.dD(), {
getInputElement : function() {
return a.document.getById(this._.le);
},
focus : function() {
var w = this.selectParentTab();
setTimeout(function() {
var x = w.getInputElement();
x && x.$.focus();
}, 0);
},
select : function() {
var w = this.selectParentTab();
setTimeout(function() {
var x = w.getInputElement();
if (x) {
x.$.focus();
x.$.select();
}
}, 0);
},
eZ : function() {
this.select();
},
setValue : function(w) {
w = w !== null ? w : '';
return n.dialog.bf.prototype.setValue.call(this, w);
},
eA : true
}, s, true);
n.dialog.textarea.prototype = new n.dialog.ju();
n.dialog.select.prototype = i
.extend(
new n.dialog.dD(),
{
getInputElement : function() {
return this._.select.getElement();
},
add : function(w, x, y) {
var z = new k('option',
this.getDialog().eY().document), A = this
.getInputElement().$;
z.$.text = w;
z.$.value = x === undefined || x === null ? w
: x;
if (y === undefined || y === null) {
if (g)
A.add(z.$);
else
A.add(z.$, null);
} else
A.add(z.$, y);
return this;
},
remove : function(w) {
var x = this.getInputElement().$;
x.remove(w);
return this;
},
clear : function() {
var w = this.getInputElement().$;
while (w.length > 0)
w.remove(0);
return this;
},
eA : true
}, s, true);
n.dialog.checkbox.prototype = i.extend(new n.dialog.bf(), {
getInputElement : function() {
return this._.checkbox.getElement();
},
setValue : function(w) {
this.getInputElement().$.checked = w;
this.oW('change', {
value : w
});
},
getValue : function() {
return this.getInputElement().$.checked;
},
eZ : function() {
this.setValue(!this.getValue());
},
dm : {
onChange : function(w, x) {
if (!g)
return t.onChange.apply(this, arguments);
else {
w.on('load', function() {
var y = this._.checkbox.getElement();
y.on('propertychange', function(z) {
z = z.data.$;
if (z.propertyName == 'checked')
this.oW('change', {
value : y.$.checked
});
}, this);
}, this);
this.on('change', x);
}
return null;
}
},
eA : true
}, s, true);
n.dialog.radio.prototype = i.extend(new n.dialog.bf(), {
setValue : function(w) {
var x = this._.children, y;
for ( var z = 0; z < x.length && (y = x[z]); z++)
y.getElement().$.checked = y.getValue() == w;
this.oW('change', {
value : w
});
},
getValue : function() {
var w = this._.children;
for ( var x = 0; x < w.length; x++) {
if (w[x].getElement().$.checked)
return w[x].getValue();
}
return null;
},
eZ : function() {
var w = this._.children, x;
for (x = 0; x < w.length; x++) {
if (w[x].getElement().$.checked) {
w[x].getElement().focus();
return;
}
}
w[0].getElement().focus();
},
dm : {
onChange : function(w, x) {
if (!g)
return t.onChange.apply(this, arguments);
else {
w.on('load', function() {
var y = this._.children, z = this;
for ( var A = 0; A < y.length; A++) {
var B = y[A].getElement();
B.on('propertychange', function(C) {
C = C.data.$;
if (C.propertyName == 'checked'
&& this.$.checked)
z.oW('change', {
value : this.getAttribute('value')
});
});
}
}, this);
this.on('change', x);
}
return null;
}
},
eA : true
}, s, true);
n.dialog.file.prototype = i
.extend(
new n.dialog.dD(),
s,
{
getInputElement : function() {
var w = a.document.getById(this._.gL)
.getFrameDocument();
return w.$.forms.length > 0 ? new k(
w.$.forms[0].elements[0]) : this
.getElement();
},
submit : function() {
this.getInputElement().getParent().$.submit();
return this;
},
vy : function(w) {
return this.getInputElement().getParent().$.action;
},
reset : function() {
var w = a.document.getById(this._.gL), x = w
.getFrameDocument(), y = this._.dg, z = this._.buttons;
function A() {
x.$.open();
if (f.isCustomDomain())
x.$.domain = document.domain;
var B = '';
if (y.size)
B = y.size - (g ? 7 : 0);
x.$
.write( [
'<html><head><title></title></head><body style="margin: 0; overflow: hidden; background: transparent;">',
'<form enctype="multipart/form-data" method="POST" action="',
i.htmlEncode(y.action),
'">',
'<input type="file" name="',
i
.htmlEncode(y.id || 'cke_upload'),
'" size="',
i
.htmlEncode(B > 0 ? B
: ''),
'" />', '</form>',
'</body></html>' ].join(''));
x.$.close();
for ( var C = 0; C < z.length; C++)
z[C].enable();
}
;
if (f.gecko)
setTimeout(A, 500);
else
A();
},
getValue : function() {
return '';
},
dm : t,
eA : true
}, true);
n.dialog.fileButton.prototype = new n.dialog.button();
a.dialog.addUIElement('text', q);
a.dialog.addUIElement('password', q);
a.dialog.addUIElement('textarea', r);
a.dialog.addUIElement('checkbox', r);
a.dialog.addUIElement('radio', r);
a.dialog.addUIElement('button', r);
a.dialog.addUIElement('select', r);
a.dialog.addUIElement('file', r);
a.dialog.addUIElement('fileButton', r);
a.dialog.addUIElement('html', r);
i.extend(CKFinder.dialog, a.dialog);
})();
(function() {
m.add('help', {
bM : [ 'toolbar', 'button' ],
bz : function q(p) {
if (!p.config.disableHelpButton) {
p.bD('help', {
exec : function(r) {
r.aG['filesview.filesview'][0].bn().focus();
window
.open(a.basePath + 'help/'
+ (r.lang.HelpLang || 'en')
+ '/index.html');
}
});
p.bY.add('Help', a.UI_BUTTON, {
label : p.lang.Help,
command : 'help'
});
}
}
});
})();
a.skins
.add(
'kama',
(function() {
var p = [ 'images/loaders/16x16.gif',
'images/loaders/32x32.gif',
'images/ckffolder.gif',
'images/ckffolderopened.gif' ];
if (g && f.version < 7)
p.push('images/sprites_ie6.png');
return {
ls : p,
application : {
css : [ 'app.css' ]
},
host : {
qx : 1,
css : [ 'host.css' ]
},
mA : 7,
kN : 7,
ps : 1,
bz : function(q) {
if (q.config.width && !isNaN(q.config.width))
q.config.width -= 12;
var r = [], s = '/* UI Color Support */.cke_skin_kama .cke_menuitem .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a:focus .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a:active .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover .cke_label,.cke_skin_kama .cke_menuitem a:focus .cke_label,.cke_skin_kama .cke_menuitem a:active .cke_label{\tbackground-color: $color !important;}.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_label,.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_label,.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_label{\tbackground-color: transparent !important;}.cke_skin_kama .cke_menuitem a.cke_disabled:hover .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a.cke_disabled:focus .cke_icon_wrapper,.cke_skin_kama .cke_menuitem a.cke_disabled:active .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuitem a.cke_disabled .cke_icon_wrapper{\tbackground-color: $color !important;\tborder-color: $color !important;}.cke_skin_kama .cke_menuseparator{\tbackground-color: $color !important;}.cke_skin_kama .cke_menuitem a:hover,.cke_skin_kama .cke_menuitem a:focus,.cke_skin_kama .cke_menuitem a:active{\tbackground-color: $color !important;}';
if (f.webkit) {
s = s.split('}').slice(0, -1);
for ( var t = 0; t < s.length; t++)
s[t] = s[t].split('{');
}
function u(x) {
var y = x.eD().append('style');
y.setAttribute('id', 'cke_ui_color');
y.setAttribute('type', 'text/css');
return y;
}
;
function v(x, y, z) {
var A, B, C;
for ( var D = 0; D < x.length; D++) {
if (f.webkit) {
for (B = 0; B < x[D].$.sheet.rules.length; B++)
x[D].$.sheet.removeRule(B);
for (B = 0; B < y.length; B++) {
C = y[B][1];
for (A = 0; A < z.length; A++)
C = C.replace(z[A][0],
z[A][1]);
x[D].$.sheet
.addRule(y[B][0], C);
}
} else {
C = y;
for (A = 0; A < z.length; A++)
C = C.replace(z[A][0], z[A][1]);
if (g)
x[D].$.styleSheet.cssText = C;
else
x[D].setHtml(C);
}
}
}
;
var w = /\$color/g;
i
.extend(
q,
{
uiColor : null,
rk : function() {
return this.uiColor;
},
setUiColor : function(x) {
var y, z, A = u(a.oC), B = u(this.document), C = '.cke_' + q.name
.replace('.',
'\\.'), D = [
C + ' .cke_wrapper',
C + '_dialog .cke_dialog_contents',
C + '_dialog a.cke_dialog_tab',
C + '_dialog .cke_dialog_footer' ]
.join(','), E = 'background-color: $color !important;';
if (f.webkit) {
y = [ [ D, E ] ];
z = [ [
'body,' + D,
E ] ];
} else {
y = D + '{' + E
+ '}';
z = 'body,' + D
+ '{' + E
+ '}';
}
return (this.setUiColor = function(
F) {
var G = [ [ w, F ] ];
q.uiColor = F;
v( [ A ], y, G);
v( [ B ], z, G);
v(r, s, G);
})(x);
}
});
q.on('menuShow', function(x) {
var y = x.data[0], z = y.element.eG(
'iframe').getItem(0)
.getFrameDocument();
if (!z.getById('cke_ui_color')) {
var A = u(z);
r.push(A);
var B = q.rk();
if (B)
v( [ A ], s, [ [ w, B ] ]);
}
});
if (q.config.uiColor)
q.on('uiReady', function() {
q.setUiColor(q.config.uiColor);
});
}
};
})());
(function() {
a.dialog ? p() : a.on('dialogPluginReady', p);
function p() {
a.dialog
.on(
'resize',
function(q) {
var r = q.data, s = r.width, t = r.height, u = r.dialog, v = u.bO.contents;
if (r.skin != 'kama')
return;
v.setStyles( {
width : s + 'px',
height : t + 'px'
});
setTimeout(
function() {
var w = u.bO.dialog.getChild( [ 0,
0, 0 ]), x = w.getChild(0), y = w
.getChild(2);
y.setStyle('width',
x.$.offsetWidth + 'px');
y = w.getChild(7);
y
.setStyle(
'width',
x.$.offsetWidth - 28 + 'px');
y = w.getChild(4);
y
.setStyle(
'height',
x.$.offsetHeight - 31 - 14 + 'px');
y = w.getChild(5);
y
.setStyle(
'height',
x.$.offsetHeight - 31 - 14 + 'px');
}, 100);
});
}
;
})();
a.skins.add('v1', (function() {
var p = [ 'images/loaders/16x16.gif', 'images/loaders/32x32.gif',
'images/ckffolder.gif', 'images/ckffolderopened.gif' ];
if (g && f.version < 7)
p.push('images/sprites_ie6.png');
return {
ls : p,
application : {
css : [ 'app.css' ]
},
ps : 1,
rv : -8,
kN : 0,
host : {
qx : 1,
css : [ 'host.css' ]
}
};
})());
(function() {
a.dialog ? p() : a.on('dialogPluginReady', p);
function p() {
a.dialog
.on(
'resize',
function(q) {
var r = q.data, s = r.width, t = r.height, u = r.dialog, v = u.bO.contents;
if (r.skin != 'v1')
return;
v.setStyles( {
width : s + 'px',
height : t + 'px'
});
setTimeout(
function() {
var w = u.bO.dialog.getChild( [ 0,
0, 0 ]), x = w.getChild(0), y = w
.getChild(2);
y.setStyle('width',
x.$.offsetWidth + 'px');
y = w.getChild(7);
y
.setStyle(
'width',
x.$.offsetWidth - 28 + 'px');
y = w.getChild(4);
y
.setStyle(
'height',
x.$.offsetHeight - 31 - 14 + 'px');
y = w.getChild(5);
y
.setStyle(
'height',
x.$.offsetHeight - 31 - 14 + 'px');
}, 100);
});
}
;
})();
a.gc
.add(
'default',
(function() {
return {
dQ : function(p) {
var q = p.name, r = p.element, s = p.ff;
if (!r || s == a.kZ)
return;
p.layout = new a.application.layout(p);
var t = p.oW('themeSpace', {
space : 'head',
html : ''
}), u = p.oW('themeSpace', {
space : 'sidebar',
html : ''
}), v = p.oW('themeSpace', {
space : 'mainTop',
html : ''
}), w = p.oW('themeSpace', {
space : 'mainMiddle',
html : ''
}), x = p.oW('themeSpace', {
space : 'mainBottom',
html : ''
}), y = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="'
+ p.lang.LangCode
+ '" dir="'
+ p.lang.dir
+ '">'
+ '<head>'
+ '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
+ t.html
+ '</head>'
+ '<body>'
+ (f.ie6Compat ? '<div id="ckfinder" role="application">'
: '<div id="ckfinder" role="application" style="visibility: hidden">')
+ '<!-- 1. CKE Skin class. -->'
+ '<div class="fake_wrapper cke_skin_'
+ (p.config.skin || 'kama')
+ '">'
+ '<!-- 2. High contrast class. -->'
+ '<div class="fake_wrapper"><!-- Applicable: hc cke_hc -->'
+ '<!-- 3. Browser class. -->'
+ '<div class="fake_wrapper '
+ f.cssClass
+ '">'
+ '<!-- 4. RTL class. -->'
+ '<div class="fake_wrapper"><!-- Applicable: rtl cke_rtl -->'
+ '<!-- 5. Layout class. -->'
+ '<div class="fake_wrapper">'
+ '<div id="ckfinder_view" class="columns_2"><!-- Applicable: columns_1 columns_2 -->'
+ '<div id="sidebar_container" class="container" role="region">'
+ '<div id="sidebar_wrapper" class="wrapper">'
+ u.html
+ '</div>'
+ '</div>'
+ '<div id="main_container" class="container" role="region">'
+ v.html
+ w.html
+ x.html
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>'
+ '</div>' + '</body>' + '</html>';
a.log('[THEME] DOM flush using document.write');
p.document.$.write(y);
function z() {
if (f.ie6Compat)
p.layout.oG = p.document.getWindow()
.eR();
}
;
p.cr('themeLoaded');
p
.cr(
'uiReady',
function() {
z();
p
.cr(
'appReady',
function() {
z();
if (f.ie8) {
var A = p.document.$, B;
if (A.documentMode)
B = A.documentMode;
else {
B = 5;
if (A.compatMode)
if (A.compatMode == 'CSS1Compat')
B = 7;
}
if (B < 8) {
var C = '<strong style="color: red;">Forced IE compatibility mode! CKFinder may not look as intended.</strong>', D = p.plugins.tools;
D
.showTool(D
.addTool(C));
}
}
if (f.ie6Compat)
p.document
.getWindow()
.on(
'resize',
z);
p.document
.getWindow()
.on(
'resize',
function() {
p.layout.ea
.call(p.layout);
});
var E;
function F() {
E = E
|| p.document
.eD()
.eG(
'link')
.getItem(
0);
var G = 0;
if (E)
try {
if (E.$.sheet
&& E.$.sheet.cssRules.length > 0)
G = 1;
else if (E.$.styleSheet
&& E.$.styleSheet.cssText.length > 0)
G = 1;
else if (E.$.innerHTML
&& E.$.innerHTML.length > 0)
G = 1;
} catch (H) {
}
if (!G) {
window
.setTimeout(
F,
250);
return;
}
if (f.ie6Compat) {
z();
p.layout
.ea();
setTimeout(
function() {
p.layout
.ea();
},
500);
} else {
p.layout
.ea(true);
setTimeout(function() {
p.document
.getById(
'ckfinder')
.removeStyle(
'visibility');
});
}
return undefined;
}
;
F();
});
});
},
pu : function(p) {
var q = i.getNextNumber(), r = k
.kE(
[
'<div class="cke_compatibility cke_' + p.name
.replace('.',
'\\.') + '_dialog cke_skin_',
p.gd,
'" dir="',
p.lang.dir,
'" lang="',
p.langCode,
'"><table class="cke_dialog',
' ' + f.cssClass
.replace(
/browser/g,
'cke_browser'),
' cke_',
p.lang.dir,
'" style="position:absolute"><tr><td><div class="%body"><div id="%title#" class="%title"></div><div id="%close_button#" class="%close_button"><span>X</span></div><div id="%tabs#" class="%tabs"></div><table class="%contents"><tr><td id="%contents#" class="%contents"></td></tr></table><div id="%footer#" class="%footer"></div></div><div id="%tl#" class="%tl"></div><div id="%tc#" class="%tc"></div><div id="%tr#" class="%tr"></div><div id="%ml#" class="%ml"></div><div id="%mr#" class="%mr"></div><div id="%bl#" class="%bl"></div><div id="%bc#" class="%bc"></div><div id="%br#" class="%br"></div></td></tr></table>',
g ? ''
: '<style>.cke_dialog{visibility:hidden;}</style>',
'</div>' ].join('')
.replace(/#/g, '_' + q)
.replace(/%/g,
'cke_dialog_'),
a.document), s = r.getChild( [
0, 0, 0, 0, 0 ]), t = s.getChild(0), u = s
.getChild(1);
t.unselectable();
u.unselectable();
return {
element : r,
bO : {
dialog : r.getChild(0),
title : t,
close : u,
tabs : s.getChild(2),
contents : s.getChild( [ 3, 0, 0, 0 ]),
footer : s.getChild(4)
}
};
},
fH : function(p) {
var q = p.container, r = p.ia;
if (q)
q.remove();
for ( var s = 0; r && s < r.length; s++)
r[s].remove();
if (p.ff == a.fc) {
p.element.show();
delete p.element;
}
}
};
})());
a.application.prototype.vU = function(p) {
var q = '' + p, r = this._[q]
|| (this._[q] = a.document.getById(q + '_' + this.name));
return r;
};
a.application.prototype.nJ = function(p) {
var q = /^\d+$/;
if (q.test(p))
p += 'px';
var r = this.layout.dV();
r.setStyle('width', p);
this.oW('resize');
this.layout.ea();
};
a.application.prototype.resize = function(p, q) {
this.element.getChild(0).setStyle('height', q + 'px');
this.element.getChild(0).setStyle('width', p + 'px');
};
(function() {
var p = "\074\144\151\166\040\143\154\x61\x73\163\x3d\047\166\151\x65\167\040\x74\157\157\154\137\x70\x61\x6e\x65\x6c\x27\x20\163\164\x79\154\x65\075\047\160\x61\144\144\151\156\x67\072\x32\160\170\073\x64\x69\163\x70\x6c\141\171\x3a\x62\154\157\143\x6b\x20\x21\x69\x6d\x70\x6f\x72\164\141\x6e\164\073\160\157\x73\x69\x74\151\x6f\x6e\x3a\163\164\x61\164\x69\143\040\x21\151\155\160\157\x72\164\141\x6e\164\073\x63\157\x6c\157\162\072\142\x6c\x61\143\x6b\x20\041\x69\x6d\x70\x6f\x72\164\141\x6e\x74\073\142\141\x63\x6b\147\162\x6f\x75\x6e\144\x2d\143\x6f\154\157\162\072\x77\x68\151\164\145\x20\x21\151\155\160\x6f\162\x74\x61\156\x74\x3b\x27\076", q = "\074\057\144\151\x76\x3e", r = p
+ "\124\x68\x69\x73\040\x69\x73\040\164\x68\145\040\x44\x45\115\x4f\x20\166\145\162\163\151\x6f\156\x20\x6f\146\x20\x43\x4b\106\x69\156\144\145\x72\056\040\x50\154\x65\x61\x73\145\x20\166\151\x73\x69\164\040\164\x68\x65\040\x3c\141\x20\x68\x72\145\146\x3d\x27\x68\164\x74\160\072\x2f\x2f\143\153\146\151\156\144\145\x72\056\143\157\155\047\x20\164\141\x72\x67\145\x74\075\047\137\x62\154\141\156\153\047\076\x43\113\106\151\156\x64\145\x72\x20\x77\x65\142\040\163\x69\x74\x65\x3c\057\x61\076\040\x74\x6f\x20\x6f\x62\164\141\x69\x6e\040\x61\x20\x76\141\x6c\151\x64\x20\x6c\x69\143\x65\x6e\163\x65\056"
+ q, s = p
+ "\x43\x4b\x46\x69\x6e\x64\145\162\x20\104\x65\x76\x65\154\x6f\160\x65\162\040\x4c\x69\x63\145\156\x73\145\x3c\142\162\x2f\x3e\x4c\x69\143\x65\x6e\x73\145\x64\x20\164\157\x3a\x20";
function t(v, w) {
var x = 0, y = 0;
for ( var z = 0; z < v.$.parentNode.childNodes.length; z++) {
var A = v.$.parentNode.childNodes[z];
if (A.nodeType == 1) {
var B = A == v.$;
if (!A.offsetHeight && !B)
continue;
y++;
if (!B)
x += A.offsetHeight;
}
}
var C = v.$.offsetHeight - v.$.clientHeight, D = (y - 1) * w;
if (f.ie6Compat && !f.ie8 && !f.ie7Compat)
D += w * 2;
var E = g ? v.$.parentNode.parentNode.parentNode.offsetHeight
: v.$.parentNode.offsetHeight, F = E - C - x - (D || 0);
try {
v.setStyle('height', F + 'px');
} catch (G) {
}
}
;
function u(v) {
return a.bs.substr(v * 9 % (2 << 4), 1);
}
;
a.application.layout = function(v) {
this.app = r.length ? v : null;
this.jB = null;
};
a.application.layout.prototype = {
ea : function(v) {
if (this.jB)
return;
this.jB = i
.setTimeout(
function() {
a.log('[THEME] Repainting layout');
var w = a.bs.indexOf(a.bF.substr(1, 1)) % 5, x = [
a.bF.substr(8, 1),
a.bF.substr(6, 1) ], y = a.bF
&& a.bF.substr(3, 1) != a.bs
.substr(
(a.bs.indexOf(a.bF
.substr(0,
1)) + a.bs
.indexOf(a.bF
.substr(
2,
1)))
* 9
% (a.bs.length - 1),
1), z = !!a.ed
&& x[1] != u(a.ed.length
+ a.bs.indexOf(x[0]));
if (a.bF
&& 1 == w
&& a
.lS(window.top[a.nd
+ "\x63\x61\164\151\157\156"][a.jG
+ "\x73\x74"]) != a
.lS(a.ed) || w == 4 || y) {
var A = this.dV().getChild(0)
.getChildren(), B = 0;
for ( var C = 0; C < A.count(); C++) {
if (A
.getItem(C)
.rd(
"\160\157\163\151\164\151\157\x6e") == "\x73\164\141\164\151\143")
B = 1;
}
if (!B)
this
.dV()
.getChild(0)
.appendHtml(
y || z || w != 4 ? r
: s
+ "\x3c\x62\076"
+ i
.htmlEncode(a.ed)
+ "\x3c\057\x62\076\074\057\144\151\x76\076");
}
var D = this.pn(), E = this.pS(), F = a.skins.loaded[this.app.gd];
if (F.ps && g && f.ie6Compat && !f.ie8) {
var G = this.mB(), H = this.dV(), I = 3 * F.kN, J = F.rv ? F.rv
: 0, K = this.oG.width
- H.$.offsetWidth - I + J;
G.setStyle('width', K + 'px');
}
if (D)
t(D, F.mA);
if (E)
t(E, F.kN);
this.jB = null;
v = false;
this.app.oW('afterRepaintLayout');
if (f.ie6Compat)
i
.setTimeout(
function() {
this.app.element.$.style.cssText += '';
}, 0, this);
}, v === true ? 0 : 500, this);
},
dV : function() {
var v = this;
if (!v.kS)
v.kS = v.app.document.getById('sidebar_container');
return v.kS;
},
mB : function() {
var v = this;
if (!v.lb)
v.lb = v.app.document.getById('main_container');
return v.lb;
},
pS : function() {
var v = this;
if (typeof v.kK === 'undefined')
v.kK = v.app.document.getById('folders_view');
return v.kK;
},
pn : function() {
var v = this;
if (typeof v.kD === 'undefined')
v.kD = v.app.document.getById('files_view');
return v.kD;
}
};
})();
})(); | JavaScript |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function() {
window.CKFinder = function(a, b, c, d) {
var e = this;
e.BasePath = a || CKFinder.DEFAULT_BASEPATH;
e.Width = b || '100%';
e.Height = c || 400;
e.SelectFunction = d || null;
e.SelectFunctionData = null;
e.SelectThumbnailFunction = d || null;
e.SelectThumbnailFunctionData = null;
e.DisableThumbnailSelection = false;
e.ClassName = 'CKFinderFrame';
e.StartupPath = null;
e.StartupFolderExpanded = false;
e.RememberLastFolder = true;
e.ResourceType = null;
e.Id = null;
e.Skin = null;
e.ConnectorLanguage = 'php';
};
CKFinder.DEFAULT_BASEPATH = '/ckfinder/';
CKFinder.prototype = {
Create : function() {
document.write(this.CreateHtml());
},
CreateHtml : function() {
var c = this;
var a = c.ClassName;
if (a && a.length > 0)
a = ' class="' + a + '"';
var b = c.Id;
if (b && b.length > 0)
b = ' id="' + b + '"';
return '<iframe src="' + c._BuildUrl() + '" width="' + c.Width
+ '" ' + 'height="' + c.Height + '"' + a + b
+ ' frameborder="0" scrolling="no"></iframe>';
},
Popup : function(a, b) {
a = a || '80%';
b = b || '70%';
if (typeof a == 'string' && a.length > 1
&& a.substr(a.length - 1, 1) == '%')
a = parseInt(window.screen.width * parseInt(a, 10) / 100, 10);
if (typeof b == 'string' && b.length > 1
&& b.substr(b.length - 1, 1) == '%')
b = parseInt(window.screen.height * parseInt(b, 10) / 100, 10);
if (a < 200)
a = 200;
if (b < 200)
b = 200;
var c = parseInt((window.screen.height - b) / 2, 10), d = parseInt(
(window.screen.width - a) / 2, 10), e = 'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,width='
+ a + ',height=' + b + ',top=' + c + ',left=' + d, f = window
.open('', 'CKFinderPopup', e, true);
if (!f)
return false;
var g = this._BuildUrl().replace(/&/g, '&');
try {
f.moveTo(d, c);
f.resizeTo(a, b);
f.focus();
f.location.href = g;
} catch (h) {
f = window.open(g, 'CKFinderPopup', e, true);
}
return true;
},
_BuildUrl : function(a) {
var d = this;
a = a || d.BasePath;
var b = '';
if (!a || a.length === 0)
a = CKFinder.DEFAULT_BASEPATH;
if (a.substr(a.length - 1, 1) != '/')
a += '/';
a += 'ckfinder.html';
var c;
if (d.SelectFunction) {
c = d.SelectFunction;
if (typeof c == 'function')
c = c.toString().match(/function ([^(]+)/)[1];
b += '?action=js&func=' + c;
}
if (d.Skin) {
b += b ? '&' : '?';
b += 'skin=' + encodeURIComponent(d.Skin);
}
if (d.SelectFunctionData) {
b += b ? '&' : '?';
b += 'data=' + encodeURIComponent(d.SelectFunctionData);
}
if (d.ResourceType) {
b += b ? '&' : '?';
b += 'type=' + encodeURIComponent(d.ResourceType);
}
if (d.DisableThumbnailSelection) {
b += b ? '&' : '?';
b += 'dts=1';
} else if (d.SelectThumbnailFunction || d.SelectFunction) {
c = d.SelectThumbnailFunction || d.SelectFunction;
if (typeof c == 'function')
c = c.toString().match(/function ([^(]+)/)[1];
b += b ? '&' : '?';
b += 'thumbFunc=' + c;
if (d.SelectThumbnailFunctionData)
b += '&tdata=' + encodeURIComponent(d.SelectThumbnailFunctionData);
else if (!d.SelectThumbnailFunction && d.SelectFunctionData)
b += '&tdata=' + encodeURIComponent(d.SelectFunctionData);
}
if (d.StartupPath) {
b += b ? '&' : '?';
b += 'start=' + encodeURIComponent(d.StartupPath
+ (d.StartupFolderExpanded ? ':1' : ':0'));
}
if (!d.RememberLastFolder) {
b += b ? '&' : '?';
b += 'rlf=0';
}
if (d.Id) {
b += b ? '&' : '?';
b += 'id=' + encodeURIComponent(d.Id);
}
return a + b;
}
};
CKFinder.Create = function(a, b, c, d) {
var e;
if (a !== null && typeof a == 'object') {
e = new CKFinder();
for ( var f in a)
e[f] = a[f];
} else
e = new CKFinder(a, b, c, d);
e.Create();
};
CKFinder.Popup = function(a, b, c, d) {
var e;
if (a !== null && typeof a == 'object') {
e = new CKFinder();
for ( var f in a)
e[f] = a[f];
} else
e = new CKFinder(a, b, c, d);
e.Popup(b, c);
};
CKFinder.SetupFCKeditor = function(a, b, c, d) {
var e;
if (b !== null && typeof b == 'object') {
e = new CKFinder();
for ( var f in b) {
e[f] = b[f];
if (f == 'Width') {
var g = e[f] || 800;
if (typeof g == 'string' && g.length > 1
&& g.substr(g.length - 1, 1) == '%')
g = parseInt(window.screen.width * parseInt(g, 10)
/ 100, 10);
a.Config.LinkBrowserWindowWidth = g;
a.Config.ImageBrowserWindowWidth = g;
a.Config.FlashBrowserWindowWidth = g;
} else if (f == 'Height') {
var h = e[f] || 600;
if (typeof h == 'string' && h.length > 1
&& h.substr(h.length - 1, 1) == '%')
h = parseInt(window.screen.height * parseInt(h, 10)
/ 100, 10);
a.Config.LinkBrowserWindowHeight = h;
a.Config.ImageBrowserWindowHeight = h;
a.Config.FlashBrowserWindowHeight = h;
}
}
} else
e = new CKFinder(b);
var i = e.BasePath;
if (i.substr(0, 1) != '/' && i.indexOf('://') == -1)
i = document.location.pathname.substring(0,
document.location.pathname.lastIndexOf('/') + 1)
+ i;
i = e._BuildUrl(i);
var j = i.indexOf('?') !== -1 ? '&' : '?';
a.Config.LinkBrowserURL = i;
a.Config.ImageBrowserURL = i + j + 'type=' + (c || 'Images');
a.Config.FlashBrowserURL = i + j + 'type=' + (d || 'Flash');
var k = i.substring(0, 1 + i.lastIndexOf('/'));
a.Config.LinkUploadURL = k + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=Files';
a.Config.ImageUploadURL = k + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (c || 'Images');
a.Config.FlashUploadURL = k + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (d || 'Flash');
};
CKFinder.SetupCKEditor = function(a, b, c, d) {
if (a === null) {
for ( var e in CKEDITOR.instances)
CKFinder.SetupCKEditor(CKEDITOR.instances[e], b, c, d);
CKEDITOR.on('instanceCreated', function(m) {
CKFinder.SetupCKEditor(m.editor, b, c, d);
});
return;
}
var f;
if (b !== null && typeof b == 'object') {
f = new CKFinder();
for ( var g in b) {
f[g] = b[g];
if (g == 'Width') {
var h = f[g] || 800;
if (typeof h == 'string' && h.length > 1
&& h.substr(h.length - 1, 1) == '%')
h = parseInt(window.screen.width * parseInt(h, 10)
/ 100, 10);
a.config.filebrowserWindowWidth = h;
} else if (g == 'Height') {
var i = f[g] || 600;
if (typeof i == 'string' && i.length > 1
&& i.substr(i.length - 1, 1) == '%')
i = parseInt(window.screen.height * parseInt(i, 10)
/ 100, 10);
a.config.filebrowserWindowHeight = h;
}
}
} else
f = new CKFinder(b);
var j = f.BasePath;
if (j.substr(0, 1) != '/' && j.indexOf('://') == -1)
j = document.location.pathname.substring(0,
document.location.pathname.lastIndexOf('/') + 1)
+ j;
j = f._BuildUrl(j);
var k = j.indexOf('?') !== -1 ? '&' : '?';
a.config.filebrowserBrowseUrl = j;
a.config.filebrowserImageBrowseUrl = j + k + 'type=' + (c || 'Images');
a.config.filebrowserFlashBrowseUrl = j + k + 'type=' + (d || 'Flash');
var l = j.substring(0, 1 + j.lastIndexOf('/'));
a.config.filebrowserUploadUrl = l + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=Files';
a.config.filebrowserImageUploadUrl = l + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (c || 'Images');
a.config.filebrowserFlashUploadUrl = l + 'core/connector/'
+ CKFinder.config.connectorLanguage + '/connector.'
+ CKFinder.config.connectorLanguage
+ '?command=QuickUpload&type=' + (d || 'Flash');
};
})();
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Folder related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFolders = function() {
$('#folders').scroll(function() {
browser.hideDialog();
});
$('div.folder > a').unbind();
$('div.folder > a').bind('click', function() {
browser.hideDialog();
return false;
});
$('div.folder > a > span.brace').unbind();
$('div.folder > a > span.brace').click(function() {
if ($(this).hasClass('opened') || $(this).hasClass('closed'))
browser.expandDir($(this).parent());
});
$('div.folder > a > span.folder').unbind();
$('div.folder > a > span.folder').click(function() {
browser.changeDir($(this).parent());
});
$('div.folder > a > span.folder').rightClick(function(e) {
_.unselect();
browser.menuDir($(this).parent(), e);
});
if ($.browser.msie && $.browser.version &&
(parseInt($.browser.version.substr(0, 1)) < 8)
) {
var fls = $('div.folder').get();
var body = $('body').get(0);
var div;
$.each(fls, function(i, folder) {
div = document.createElement('div');
div.style.display = 'inline';
div.style.margin = div.style.border = div.style.padding = '0';
div.innerHTML='<table style="border-collapse:collapse;border:0;margin:0;width:0"><tr><td nowrap="nowrap" style="white-space:nowrap;padding:0;border:0">' + $(folder).html() + "</td></tr></table>";
body.appendChild(div);
$(folder).css('width', $(div).innerWidth() + 'px');
body.removeChild(div);
});
}
};
browser.setTreeData = function(data, path) {
if (!path)
path = '';
else if (path.length && (path.substr(path.length - 1, 1) != '/'))
path += '/';
path += data.name;
var selector = '#folders a[href="kcdir:/' + _.escapeDirs(path) + '"]';
$(selector).data({
name: data.name,
path: path,
readable: data.readable,
writable: data.writable,
removable: data.removable,
hasDirs: data.hasDirs
});
$(selector + ' span.folder').addClass(data.current ? 'current' : 'regular');
if (data.dirs && data.dirs.length) {
$(selector + ' span.brace').addClass('opened');
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path + '/');
});
} else if (data.hasDirs)
$(selector + ' span.brace').addClass('closed');
};
browser.buildTree = function(root, path) {
if (!path) path = "";
path += root.name;
var html = '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(root.name) + '</span></a>';
if (root.dirs) {
html += '<div class="folders">';
for (var i = 0; i < root.dirs.length; i++) {
cdir = root.dirs[i];
html += browser.buildTree(cdir, path + '/');
}
html += '</div>';
}
html += '</div>';
return html;
};
browser.expandDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened')) {
dir.parent().children('.folders').hide(500, function() {
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
});
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
} else {
if (dir.parent().children('.folders').get(0)) {
dir.parent().children('.folders').show(500);
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else if (!$('#loadingDirs').get(0)) {
dir.parent().append('<div id="loadingDirs">' + this.label("Loading folders...") + '</div>');
$('#loadingDirs').css('display', 'none');
$('#loadingDirs').show(200, function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('expand'),
data: {dir:path},
async: false,
success: function(data) {
$('#loadingDirs').hide(200, function() {
$('#loadingDirs').detach();
});
if (browser.check4errors(data))
return;
var html = '';
$.each(data.dirs, function(i, cdir) {
html += '<div class="folder"><a href="kcdir:/' + _.escapeDirs(path + '/' + cdir.name) + '"><span class="brace"> </span><span class="folder">' + _.htmlData(cdir.name) + '</span></a></div>';
});
if (html.length) {
dir.parent().append('<div class="folders">' + html + '</div>');
var folders = $(dir.parent().children('.folders').first());
folders.css('display', 'none');
$(folders).show(500);
$.each(data.dirs, function(i, cdir) {
browser.setTreeData(cdir, path);
});
}
if (data.dirs.length) {
dir.children('.brace').removeClass('closed');
dir.children('.brace').addClass('opened');
} else {
dir.children('.brace').removeClass('opened');
dir.children('.brace').removeClass('closed');
}
browser.initFolders();
browser.initDropUpload();
},
error: function() {
$('#loadingDirs').detach();
browser.alert(browser.label("Unknown error."));
}
});
});
}
}
};
browser.changeDir = function(dir) {
if (dir.children('span.folder').hasClass('regular')) {
$('div.folder > a > span.folder').removeClass('current');
$('div.folder > a > span.folder').removeClass('regular');
$('div.folder > a > span.folder').addClass('regular');
dir.children('span.folder').removeClass('regular');
dir.children('span.folder').addClass('current');
$('#files').html(browser.label("Loading files..."));
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:dir.data('path')},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.files = data.files;
browser.orderFiles();
browser.dir = dir.data('path');
browser.dirWritable = data.dirWritable;
var title = "KCFinder: /" + browser.dir;
document.title = title;
if (browser.opener.TinyMCE)
tinyMCEPopup.editor.windowManager.setTitle(window, title);
browser.statusDir();
},
error: function() {
$('#files').html(browser.label("Unknown error."));
}
});
}
};
browser.statusDir = function() {
for (var i = 0, size = 0; i < this.files.length; i++)
size += parseInt(this.files[i].size);
size = this.humanSize(size);
$('#fileinfo').html(this.files.length + ' ' + this.label("files") + ' (' + size + ')');
};
browser.menuDir = function(dir, e) {
var data = dir.data();
var html = '<div class="menu">';
if (this.clipboard && this.clipboard.length) {
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Copy {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Move {count} files", {count: this.clipboard.length}) + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>';
}
html +=
'<a href="kcact:refresh">' + this.label("Refresh") + '</a>';
if (this.support.zip) html+=
'<div class="delimiter"></div>' +
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.dirs.create || this.access.dirs.rename || this.access.dirs['delete'])
html += '<div class="delimiter"></div>';
if (this.access.dirs.create)
html += '<a href="kcact:mkdir"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("New Subfolder...") + '</a>';
if (this.access.dirs.rename)
html += '<a href="kcact:mvdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.dirs['delete'])
html += '<a href="kcact:rmdir"' + (!data.removable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('div.folder > a > span.folder').removeClass('context');
if (dir.children('span.folder').hasClass('regular'))
dir.children('span.folder').addClass('context');
if (this.clipboard && this.clipboard.length && data.writable) {
$('.menu a[href="kcact:cpcbd"]').click(function() {
browser.hideDialog();
browser.copyClipboard(data.path);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
browser.hideDialog();
browser.moveClipboard(data.path);
return false;
});
}
$('.menu a[href="kcact:refresh"]').click(function() {
browser.hideDialog();
browser.refreshDir(dir);
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.post(browser.baseGetData('downloadDir'), {dir:data.path});
return false;
});
$('.menu a[href="kcact:mkdir"]').click(function(e) {
if (!data.writable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newDir', '', browser.baseGetData('newDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function() {
browser.refreshDir(dir);
browser.initDropUpload();
if (!data.hasDirs) {
dir.data('hasDirs', true);
dir.children('span.brace').addClass('closed');
}
}
);
return false;
});
$('.menu a[href="kcact:mvdir"]').click(function(e) {
if (!data.removable) return false;
browser.hideDialog();
browser.fileNameDialog(
e, {dir: data.path},
'newName', data.name, browser.baseGetData('renameDir'), {
title: "New folder name:",
errEmpty: "Please enter new folder name.",
errSlash: "Unallowable characters in folder name.",
errDot: "Folder name shouldn't begins with '.'"
}, function(dt) {
if (!dt.name) {
browser.alert(browser.label("Unknown error."));
return;
}
var currentDir = (data.path == browser.dir);
dir.children('span.folder').html(_.htmlData(dt.name));
dir.data('name', dt.name);
dir.data('path', _.dirname(data.path) + '/' + dt.name);
if (currentDir)
browser.dir = dir.data('path');
browser.initDropUpload();
},
true
);
return false;
});
$('.menu a[href="kcact:rmdir"]').click(function() {
if (!data.removable) return false;
browser.hideDialog();
browser.confirm(
"Are you sure you want to delete this folder and all its content?",
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('deleteDir'),
data: {dir: data.path},
async: false,
success: function(data) {
if (callBack) callBack();
if (browser.check4errors(data))
return;
dir.parent().hide(500, function() {
var folders = dir.parent().parent();
var pDir = folders.parent().children('a').first();
dir.parent().detach();
if (!folders.children('div.folder').get(0)) {
pDir.children('span.brace').first().removeClass('opened');
pDir.children('span.brace').first().removeClass('closed');
pDir.parent().children('.folders').detach();
pDir.data('hasDirs', false);
}
if (pDir.data('path') == browser.dir.substr(0, pDir.data('path').length))
browser.changeDir(pDir);
browser.initDropUpload();
});
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
};
browser.refreshDir = function(dir) {
var path = dir.data('path');
if (dir.children('.brace').hasClass('opened') || dir.children('.brace').hasClass('closed')) {
dir.children('.brace').removeClass('opened');
dir.children('.brace').addClass('closed');
}
dir.parent().children('.folders').first().detach();
if (path == browser.dir.substr(0, path.length))
browser.changeDir(dir);
browser.expandDir(dir);
return true;
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc File related functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initFiles = function() {
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
$('#files').unbind();
$('#files').scroll(function() {
browser.hideDialog();
});
$('.file').unbind();
$('.file').click(function(e) {
_.unselect();
browser.selectFile($(this), e);
});
$('.file').rightClick(function(e) {
_.unselect();
browser.menuFile($(this), e);
});
$('.file').dblclick(function() {
_.unselect();
browser.returnFile($(this));
});
$('.file').mouseup(function() {
_.unselect();
});
$('.file').mouseout(function() {
_.unselect();
});
$.each(this.shows, function(i, val) {
var display = (_.kuki.get('show' + val) == 'off')
? 'none' : 'block';
$('#files .file div.' + val).css('display', display);
});
this.statusDir();
};
browser.showFiles = function(callBack, selected) {
this.fadeFiles();
setTimeout(function() {
var html = '';
$.each(browser.files, function(i, file) {
var stamp = [];
$.each(file, function(key, val) {
stamp[stamp.length] = key + "|" + val;
});
stamp = _.md5(stamp.join('|'));
if (_.kuki.get('view') == 'list') {
if (!i) html += '<table summary="list">';
var icon = _.getFileExtension(file.name);
if (file.thumb)
icon = '.image';
else if (!icon.length || !file.smallIcon)
icon = '.';
icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<tr class="file">' +
'<td class="name" style="background-image:url(' + icon + ')">' + _.htmlData(file.name) + '</td>' +
'<td class="time">' + file.date + '</td>' +
'<td class="size">' + browser.humanSize(file.size) + '</td>' +
'</tr>';
if (i == browser.files.length - 1) html += '</table>';
} else {
if (file.thumb)
var icon = browser.baseGetData('thumb') + '&file=' + encodeURIComponent(file.name) + '&dir=' + encodeURIComponent(browser.dir) + '&stamp=' + stamp;
else if (file.smallThumb) {
var icon = browser.uploadURL + '/' + browser.dir + '/' + file.name;
icon = _.escapeDirs(icon).replace(/\'/g, "%27");
} else {
var icon = file.bigIcon ? _.getFileExtension(file.name) : '.';
if (!icon.length) icon = '.';
icon = 'themes/' + browser.theme + '/img/files/big/' + icon + '.png';
}
html += '<div class="file">' +
'<div class="thumb" style="background-image:url(\'' + icon + '\')" ></div>' +
'<div class="name">' + _.htmlData(file.name) + '</div>' +
'<div class="time">' + file.date + '</div>' +
'<div class="size">' + browser.humanSize(file.size) + '</div>' +
'</div>';
}
});
$('#files').html('<div>' + html + '<div>');
$.each(browser.files, function(i, file) {
var item = $('#files .file').get(i);
$(item).data(file);
if (_.inArray(file.name, selected) ||
((typeof selected != 'undefined') && !selected.push && (file.name == selected))
)
$(item).addClass('selected');
});
$('#files > div').css({opacity:'', filter:''});
if (callBack) callBack();
browser.initFiles();
}, 200);
};
browser.selectFile = function(file, e) {
if (e.ctrlKey || e.metaKey) {
if (file.hasClass('selected'))
file.removeClass('selected');
else
file.addClass('selected');
var files = $('.file.selected').get();
var size = 0;
if (!files.length)
this.statusDir();
else {
$.each(files, function(i, cfile) {
size += parseInt($(cfile).data('size'));
});
size = this.humanSize(size);
if (files.length > 1)
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
else {
var data = $(files[0]).data();
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
}
} else {
var data = file.data();
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
}
};
browser.selectAll = function(e) {
if ((!e.ctrlKey && !e.metaKey) || ((e.keyCode != 65) && (e.keyCode != 97)))
return false;
var files = $('.file').get();
if (files.length) {
var size = 0;
$.each(files, function(i, file) {
if (!$(file).hasClass('selected'))
$(file).addClass('selected');
size += parseInt($(file).data('size'));
});
size = this.humanSize(size);
$('#fileinfo').html(files.length + ' ' + this.label("selected files") + ' (' + size + ')');
}
return true;
};
browser.returnFile = function(file) {
var fileURL = file.substr
? file : browser.uploadURL + '/' + browser.dir + '/' + file.data('name');
fileURL = _.escapeDirs(fileURL);
if (this.opener.CKEditor) {
this.opener.CKEditor.object.tools.callFunction(this.opener.CKEditor.funcNum, fileURL, '');
window.close();
} else if (this.opener.FCKeditor) {
window.opener.SetUrl(fileURL) ;
window.close() ;
} else if (this.opener.TinyMCE) {
var win = tinyMCEPopup.getWindowArg('window');
win.document.getElementById(tinyMCEPopup.getWindowArg('input')).value = fileURL;
if (win.getImageData) win.getImageData();
if (typeof(win.ImageDialog) != "undefined") {
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(fileURL);
}
tinyMCEPopup.close();
} else if (this.opener.callBack) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBack(fileURL);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBack(fileURL);
}
} else if (this.opener.callBackMultiple) {
if (window.opener && window.opener.KCFinder) {
this.opener.callBackMultiple([fileURL]);
window.close();
}
if (window.parent && window.parent.KCFinder) {
var button = $('#toolbar a[href="kcact:maximize"]');
if (button.hasClass('selected'))
this.maximize(button);
this.opener.callBackMultiple([fileURL]);
}
}
};
browser.returnFiles = function(files) {
if (this.opener.callBackMultiple && files.length) {
var rfiles = [];
$.each(files, function(i, file) {
rfiles[i] = browser.uploadURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[i] = _.escapeDirs(rfiles[i]);
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.returnThumbnails = function(files) {
if (this.opener.callBackMultiple) {
var rfiles = [];
var j = 0;
$.each(files, function(i, file) {
if ($(file).data('thumb')) {
rfiles[j] = browser.thumbsURL + '/' + browser.dir + '/' + $(file).data('name');
rfiles[j] = _.escapeDirs(rfiles[j++]);
}
});
this.opener.callBackMultiple(rfiles);
if (window.opener) window.close()
}
};
browser.menuFile = function(file, e) {
var data = file.data();
var path = this.dir + '/' + data.name;
var files = $('.file.selected').get();
var html = '';
if (file.hasClass('selected') && files.length && (files.length > 1)) {
var thumb = false;
var notWritable = 0;
var cdata;
$.each(files, function(i, cfile) {
cdata = $(cfile).data();
if (cdata.thumb) thumb = true;
if (!data.writable) notWritable++;
});
if (this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnails") + '</a>';
}
if (data.thumb || data.smallThumb || this.support.zip) {
html += (html.length ? '<div class="delimiter"></div>' : '');
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
if (this.support.zip) html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:download">' + this.label("Download") + '</a>';
}
if (this.access.files.copy || this.access.files.move)
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files['delete'])
html += (html.length ? '<div class="delimiter"></div>' : '') +
'<a href="kcact:rm"' + ((notWritable == files.length) ? ' class="denied"' : '') +
'>' + this.label("Delete") + '</a>';
if (html.length) {
html = '<div class="menu">' + html + '</div>';
$('#dialog').html(html);
this.showMenu(e);
} else
return;
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFiles(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
browser.returnThumbnails(files);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
var pfiles = [];
$.each(files, function(i, cfile) {
pfiles[i] = $(cfile).data('name');
});
browser.post(browser.baseGetData('downloadSelected'), {dir:browser.dir, files:pfiles});
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
browser.hideDialog();
var msg = '';
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
var failed = false;
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == cdata.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
failed = true
msg += cdata.name + ": " + browser.label("This file is already added to the Clipboard.") + "\n";
break;
}
if (!failed) {
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
}
});
browser.initClipboard();
if (msg.length) browser.alert(msg.substr(0, msg.length - 1));
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if ($(this).hasClass('denied')) return false;
browser.hideDialog();
var failed = 0;
var dfiles = [];
$.each(files, function(i, cfile) {
var cdata = $(cfile).data();
if (!cdata.writable)
failed++;
else
dfiles[dfiles.length] = browser.dir + "/" + cdata.name;
});
if (failed == files.length) {
browser.alert(browser.label("The selected files are not removable."));
return false;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:dfiles},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} selected files are not removable. Do you want to delete the rest?", {count:failed}),
go
)
else
browser.confirm(
browser.label("Are you sure you want to delete all selected files?"),
go
);
return false;
});
} else {
html += '<div class="menu">';
$('.file').removeClass('selected');
file.addClass('selected');
$('#fileinfo').html(data.name + ' (' + this.humanSize(data.size) + ', ' + data.date + ')');
if (this.opener.callBack || this.opener.callBackMultiple) {
html += '<a href="kcact:pick">' + this.label("Select") + '</a>';
if (data.thumb) html +=
'<a href="kcact:pick_thumb">' + this.label("Select Thumbnail") + '</a>';
html += '<div class="delimiter"></div>';
}
if (data.thumb || data.smallThumb)
html +='<a href="kcact:view">' + this.label("View") + '</a>';
html +=
'<a href="kcact:download">' + this.label("Download") + '</a>';
if (this.access.files.copy || this.access.files.move)
html += '<div class="delimiter"></div>' +
'<a href="kcact:clpbrdadd">' + this.label("Add to Clipboard") + '</a>';
if (this.access.files.rename || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.rename)
html += '<a href="kcact:mv"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Rename...") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rm"' + (!data.writable ? ' class="denied"' : '') + '>' +
this.label("Delete") + '</a>';
html += '</div>';
$('#dialog').html(html);
this.showMenu(e);
$('.menu a[href="kcact:pick"]').click(function() {
browser.returnFile(file);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:pick_thumb"]').click(function() {
var path = browser.thumbsURL + '/' + browser.dir + '/' + data.name;
browser.returnFile(path);
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:download"]').click(function() {
var html = '<form id="downloadForm" method="post" action="' + browser.baseGetData('download') + '">' +
'<input type="hidden" name="dir" />' +
'<input type="hidden" name="file" />' +
'</form>';
$('#dialog').html(html);
$('#downloadForm input').get(0).value = browser.dir;
$('#downloadForm input').get(1).value = data.name;
$('#downloadForm').submit();
return false;
});
$('.menu a[href="kcact:clpbrdadd"]').click(function() {
for (i = 0; i < browser.clipboard.length; i++)
if ((browser.clipboard[i].name == data.name) &&
(browser.clipboard[i].dir == browser.dir)
) {
browser.hideDialog();
browser.alert(browser.label("This file is already added to the Clipboard."));
return false;
}
var cdata = data;
cdata.dir = browser.dir;
browser.clipboard[browser.clipboard.length] = cdata;
browser.initClipboard();
browser.hideDialog();
return false;
});
$('.menu a[href="kcact:mv"]').click(function(e) {
if (!data.writable) return false;
browser.fileNameDialog(
e, {dir: browser.dir, file: data.name},
'newName', data.name, browser.baseGetData('rename'), {
title: "New file name:",
errEmpty: "Please enter new file name.",
errSlash: "Unallowable characters in file name.",
errDot: "File name shouldn't begins with '.'"
},
function() {
browser.refresh();
}
);
return false;
});
$('.menu a[href="kcact:rm"]').click(function() {
if (!data.writable) return false;
browser.hideDialog();
browser.confirm(browser.label("Are you sure you want to delete this file?"),
function(callBack) {
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('delete'),
data: {dir:browser.dir, file:data.name},
async: false,
success: function(data) {
if (callBack) callBack();
browser.clearClipboard();
if (browser.check4errors(data))
return;
browser.refresh();
},
error: function() {
if (callBack) callBack();
browser.alert(browser.label("Unknown error."));
}
});
}
);
return false;
});
}
$('.menu a[href="kcact:view"]').click(function() {
browser.hideDialog();
var ts = new Date().getTime();
var showImage = function(data) {
url = _.escapeDirs(browser.uploadURL + '/' + browser.dir + '/' + data.name) + '?ts=' + ts,
$('#loading').html(browser.label("Loading image..."));
$('#loading').css('display', 'inline');
var img = new Image();
img.src = url;
img.onerror = function() {
browser.lock = false;
$('#loading').css('display', 'none');
browser.alert(browser.label("Unknown error."));
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
browser.refresh();
};
var onImgLoad = function() {
browser.lock = false;
$('#files .file').each(function() {
if ($(this).data('name') == data.name)
browser.ssImage = this;
});
$('#loading').css('display', 'none');
$('#dialog').html('<div class="slideshow"><img /></div>');
$('#dialog img').attr({
src: url,
title: data.name
}).fadeIn('fast', function() {
var o_w = $('#dialog').outerWidth();
var o_h = $('#dialog').outerHeight();
var f_w = $(window).width() - 30;
var f_h = $(window).height() - 30;
if ((o_w > f_w) || (o_h > f_h)) {
if ((f_w / f_h) > (o_w / o_h))
f_w = parseInt((o_w * f_h) / o_h);
else if ((f_w / f_h) < (o_w / o_h))
f_h = parseInt((o_h * f_w) / o_w);
$('#dialog img').attr({
width: f_w,
height: f_h
});
}
$('#dialog').unbind('click');
$('#dialog').click(function(e) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
if (browser.ssImage) {
browser.selectFile($(browser.ssImage), e);
}
});
browser.showDialog();
var images = [];
$.each(browser.files, function(i, file) {
if (file.thumb || file.smallThumb)
images[images.length] = file;
});
if (images.length)
$.each(images, function(i, image) {
if (image.name == data.name) {
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (images.length > 1) {
if (!browser.lock && (e.keyCode == 37)) {
var nimg = i
? images[i - 1]
: images[images.length - 1];
browser.lock = true;
showImage(nimg);
}
if (!browser.lock && (e.keyCode == 39)) {
var nimg = (i >= images.length - 1)
? images[0]
: images[i + 1];
browser.lock = true;
showImage(nimg);
}
}
if (e.keyCode == 27) {
browser.hideDialog();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
}
});
}
});
});
};
if (img.complete)
onImgLoad();
else
img.onload = onImgLoad;
};
showImage(data);
return false;
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Toolbar functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initToolbar = function() {
$('#toolbar a').click(function() {
browser.hideDialog();
});
if (!_.kuki.isSet('displaySettings'))
_.kuki.set('displaySettings', 'off');
if (_.kuki.get('displaySettings') == 'on') {
$('#toolbar a[href="kcact:settings"]').addClass('selected');
$('#settings').css('display', 'block');
browser.resize();
}
$('#toolbar a[href="kcact:settings"]').click(function () {
if ($('#settings').css('display') == 'none') {
$(this).addClass('selected');
_.kuki.set('displaySettings', 'on');
$('#settings').css('display', 'block');
browser.fixFilesHeight();
} else {
$(this).removeClass('selected');
_.kuki.set('displaySettings', 'off');
$('#settings').css('display', 'none');
browser.fixFilesHeight();
}
return false;
});
$('#toolbar a[href="kcact:refresh"]').click(function() {
browser.refresh();
return false;
});
if (window.opener || this.opener.TinyMCE || $('iframe', window.parent.document).get(0))
$('#toolbar a[href="kcact:maximize"]').click(function() {
browser.maximize(this);
return false;
});
else
$('#toolbar a[href="kcact:maximize"]').css('display', 'none');
$('#toolbar a[href="kcact:about"]').click(function() {
var html = '<div class="box about">' +
'<div class="head"><a href="http://kcfinder.sunhater.com" target="_blank">KCFinder</a> ' + browser.version + '</div>';
if (browser.support.check4Update)
html += '<div id="checkver"><span class="loading"><span>' + browser.label("Checking for new version...") + '</span></span></div>';
html +=
'<div>' + browser.label("Licenses:") + ' GPLv2 & LGPLv2</div>' +
'<div>Copyright ©2010, 2011 Pavel Tzonkov</div>' +
'<button>' + browser.label("OK") + '</button>' +
'</div>';
$('#dialog').html(html);
$('#dialog').data('title', browser.label("About"));
browser.showDialog();
var close = function() {
browser.hideDialog();
browser.unshadow();
}
$('#dialog button').click(close);
var span = $('#checkver > span');
setTimeout(function() {
$.ajax({
dataType: 'json',
url: browser.baseGetData('check4Update'),
async: true,
success: function(data) {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
if (!data.version) {
span.html(browser.label("Unable to connect!"));
browser.showDialog();
return;
}
if (browser.version < data.version)
span.html('<a href="http://kcfinder.sunhater.com/download" target="_blank">' + browser.label("Download version {version} now!", {version: data.version}) + '</a>');
else
span.html(browser.label("KCFinder is up to date!"));
browser.showDialog();
},
error: function() {
if (!$('#dialog').html().length)
return;
span.removeClass('loading');
span.html(browser.label("Unable to connect!"));
browser.showDialog();
}
});
}, 1000);
$('#dialog').unbind();
return false;
});
this.initUploadButton();
};
browser.initUploadButton = function() {
var btn = $('#toolbar a[href="kcact:upload"]');
if (!this.access.files.upload) {
btn.css('display', 'none');
return;
}
var top = btn.get(0).offsetTop;
var width = btn.outerWidth();
var height = btn.outerHeight();
$('#toolbar').prepend('<div id="upload" style="top:' + top + 'px;width:' + width + 'px;height:' + height + 'px">' +
'<form enctype="multipart/form-data" method="post" target="uploadResponse" action="' + browser.baseGetData('upload') + '">' +
'<input type="file" name="upload[]" onchange="browser.uploadFile(this.form)" style="height:' + height + 'px" multiple="multiple" />' +
'<input type="hidden" name="dir" value="" />' +
'</form>' +
'</div>');
$('#upload input').css('margin-left', "-" + ($('#upload input').outerWidth() - width) + 'px');
$('#upload').mouseover(function() {
$('#toolbar a[href="kcact:upload"]').addClass('hover');
});
$('#upload').mouseout(function() {
$('#toolbar a[href="kcact:upload"]').removeClass('hover');
});
};
browser.uploadFile = function(form) {
if (!this.dirWritable) {
browser.alert(this.label("Cannot write to upload folder."));
$('#upload').detach();
browser.initUploadButton();
return;
}
form.elements[1].value = browser.dir;
$('<iframe id="uploadResponse" name="uploadResponse" src="javascript:;"></iframe>').prependTo(document.body);
$('#loading').html(this.label("Uploading file..."));
$('#loading').css('display', 'inline');
form.submit();
$('#uploadResponse').load(function() {
var response = $(this).contents().find('body').html();
$('#loading').css('display', 'none');
response = response.split("\n");
var selected = [], errors = [];
$.each(response, function(i, row) {
if (row.substr(0, 1) == '/')
selected[selected.length] = row.substr(1, row.length - 1)
else
errors[errors.length] = row;
});
if (errors.length)
browser.alert(errors.join("\n"));
if (!selected.length)
selected = null
browser.refresh(selected);
$('#upload').detach();
setTimeout(function() {
$('#uploadResponse').detach();
}, 1);
browser.initUploadButton();
});
};
browser.maximize = function(button) {
if (window.opener) {
window.moveTo(0, 0);
width = screen.availWidth;
height = screen.availHeight;
if ($.browser.opera)
height -= 50;
window.resizeTo(width, height);
} else if (browser.opener.TinyMCE) {
var win, ifr, id;
$('iframe', window.parent.document).each(function() {
if (/^mce_\d+_ifr$/.test($(this).attr('id'))) {
id = parseInt($(this).attr('id').replace(/^mce_(\d+)_ifr$/, "$1"));
win = $('#mce_' + id, window.parent.document);
ifr = $('#mce_' + id + '_ifr', window.parent.document);
}
});
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
win.css({
left: browser.maximizeMCE.left + 'px',
top: browser.maximizeMCE.top + 'px',
width: browser.maximizeMCE.width + 'px',
height: browser.maximizeMCE.height + 'px'
});
ifr.css({
width: browser.maximizeMCE.width - browser.maximizeMCE.Hspace + 'px',
height: browser.maximizeMCE.height - browser.maximizeMCE.Vspace + 'px'
});
} else {
$(button).addClass('selected')
browser.maximizeMCE = {
width: _.nopx(win.css('width')),
height: _.nopx(win.css('height')),
left: win.position().left,
top: win.position().top,
Hspace: _.nopx(win.css('width')) - _.nopx(ifr.css('width')),
Vspace: _.nopx(win.css('height')) - _.nopx(ifr.css('height'))
};
var width = $(window.parent).width();
var height = $(window.parent).height();
win.css({
left: $(window.parent).scrollLeft() + 'px',
top: $(window.parent).scrollTop() + 'px',
width: width + 'px',
height: height + 'px'
});
ifr.css({
width: width - browser.maximizeMCE.Hspace + 'px',
height: height - browser.maximizeMCE.Vspace + 'px'
});
}
} else if ($('iframe', window.parent.document).get(0)) {
var ifrm = $('iframe[name="' + window.name + '"]', window.parent.document);
var parent = ifrm.parent();
var width, height;
if ($(button).hasClass('selected')) {
$(button).removeClass('selected');
if (browser.maximizeThread) {
clearInterval(browser.maximizeThread);
browser.maximizeThread = null;
}
if (browser.maximizeW) browser.maximizeW = null;
if (browser.maximizeH) browser.maximizeH = null;
$.each($('*', window.parent.document).get(), function(i, e) {
e.style.display = browser.maximizeDisplay[i];
});
ifrm.css({
display: browser.maximizeCSS.display,
position: browser.maximizeCSS.position,
left: browser.maximizeCSS.left,
top: browser.maximizeCSS.top,
width: browser.maximizeCSS.width,
height: browser.maximizeCSS.height
});
$(window.parent).scrollLeft(browser.maximizeLest);
$(window.parent).scrollTop(browser.maximizeTop);
} else {
$(button).addClass('selected');
browser.maximizeCSS = {
display: ifrm.css('display'),
position: ifrm.css('position'),
left: ifrm.css('left'),
top: ifrm.css('top'),
width: ifrm.outerWidth() + 'px',
height: ifrm.outerHeight() + 'px'
};
browser.maximizeTop = $(window.parent).scrollTop();
browser.maximizeLeft = $(window.parent).scrollLeft();
browser.maximizeDisplay = [];
$.each($('*', window.parent.document).get(), function(i, e) {
browser.maximizeDisplay[i] = $(e).css('display');
$(e).css('display', 'none');
});
ifrm.css('display', 'block');
ifrm.parents().css('display', 'block');
var resize = function() {
width = $(window.parent).width();
height = $(window.parent).height();
if (!browser.maximizeW || (browser.maximizeW != width) ||
!browser.maximizeH || (browser.maximizeH != height)
) {
browser.maximizeW = width;
browser.maximizeH = height;
ifrm.css({
width: width + 'px',
height: height + 'px'
});
browser.resize();
}
}
ifrm.css('position', 'absolute');
if ((ifrm.offset().left == ifrm.position().left) &&
(ifrm.offset().top == ifrm.position().top)
)
ifrm.css({left: '0', top: '0'});
else
ifrm.css({
left: - ifrm.offset().left + 'px',
top: - ifrm.offset().top + 'px'
});
resize();
browser.maximizeThread = setInterval(resize, 250);
}
}
};
browser.refresh = function(selected) {
this.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('chDir'),
data: {dir:browser.dir},
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.dirWritable = data.dirWritable;
browser.files = data.files ? data.files : [];
browser.orderFiles(null, selected);
browser.statusDir();
},
error: function() {
$('#files > div').css({opacity:'', filter:''});
$('#files').html(browser.label("Unknown error."));
}
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Clipboard functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var size = 0;
$.each(this.clipboard, function(i, val) {
size += parseInt(val.size);
});
size = this.humanSize(size);
$('#clipboard').html('<div title="' + this.label("Clipboard") + ' (' + this.clipboard.length + ' ' + this.label("files") + ', ' + size + ')" onclick="browser.openClipboard()"></div>');
var resize = function() {
$('#clipboard').css({
left: $(window).width() - $('#clipboard').outerWidth() + 'px',
top: $(window).height() - $('#clipboard').outerHeight() + 'px'
});
};
resize();
$('#clipboard').css('display', 'block');
$(window).unbind();
$(window).resize(function() {
browser.resize();
resize();
});
};
browser.openClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
if ($('.menu a[href="kcact:cpcbd"]').html()) {
$('#clipboard').removeClass('selected');
this.hideDialog();
return;
}
var html = '<div class="menu"><div class="list">';
$.each(this.clipboard, function(i, val) {
icon = _.getFileExtension(val.name);
if (val.thumb)
icon = '.image';
else if (!val.smallIcon || !icon.length)
icon = '.';
var icon = 'themes/' + browser.theme + '/img/files/small/' + icon + '.png';
html += '<a style="background-image:url(' + _.escapeDirs(icon) + ')" title="' + browser.label("Click to remove from the Clipboard") + '" onclick="browser.removeFromClipboard(' + i + ')">' + _.htmlData(_.basename(val.name)) + '</a>';
});
html += '</div><div class="delimiter"></div>';
if (this.support.zip) html+=
'<a href="kcact:download">' + this.label("Download files") + '</a>';
if (this.access.files.copy || this.access.files.move || this.access.files['delete'])
html += '<div class="delimiter"></div>';
if (this.access.files.copy)
html += '<a href="kcact:cpcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Copy files here") + '</a>';
if (this.access.files.move)
html += '<a href="kcact:mvcbd"' + (!browser.dirWritable ? ' class="denied"' : '') + '>' +
this.label("Move files here") + '</a>';
if (this.access.files['delete'])
html += '<a href="kcact:rmcbd">' + this.label("Delete files") + '</a>';
html += '<div class="delimiter"></div>' +
'<a href="kcact:clrcbd">' + this.label("Clear the Clipboard") + '</a>' + '</div>';
setTimeout(function() {
$('#clipboard').addClass('selected');
$('#dialog').html(html);
$('.menu a[href="kcact:download"]').click(function() {
browser.hideDialog();
browser.downloadClipboard();
return false;
});
$('.menu a[href="kcact:cpcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.copyClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:mvcbd"]').click(function() {
if (!browser.dirWritable) return false;
browser.hideDialog();
browser.moveClipboard(browser.dir);
return false;
});
$('.menu a[href="kcact:rmcbd"]').click(function() {
browser.hideDialog();
browser.confirm(
browser.label("Are you sure you want to delete all files in the Clipboard?"),
function(callBack) {
if (callBack) callBack();
browser.deleteClipboard();
}
);
return false;
});
$('.menu a[href="kcact:clrcbd"]').click(function() {
browser.hideDialog();
browser.clearClipboard();
return false;
});
var left = $(window).width() - $('#dialog').outerWidth();
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
var lheight = top + _.outerTopSpace('#dialog');
$('.menu .list').css('max-height', lheight + 'px');
var top = $(window).height() - $('#dialog').outerHeight() - $('#clipboard').outerHeight();
$('#dialog').css({
left: (left - 4) + 'px',
top: top + 'px'
});
$('#dialog').fadeIn();
}, 1);
};
browser.removeFromClipboard = function(i) {
if (!this.clipboard || !this.clipboard[i]) return false;
if (this.clipboard.length == 1) {
this.clearClipboard();
this.hideDialog();
return;
}
if (i < this.clipboard.length - 1) {
var last = this.clipboard.slice(i + 1);
this.clipboard = this.clipboard.slice(0, i);
this.clipboard = this.clipboard.concat(last);
} else
this.clipboard.pop();
this.initClipboard();
this.hideDialog();
this.openClipboard();
return true;
};
browser.copyClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not readable."));
return;
}
var go = function(callBack) {
if (dir == browser.dir)
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('cp_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
if (dir == browser.dir)
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?", {count:failed}),
go
)
else
go();
};
browser.moveClipboard = function(dir) {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + "/" + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not movable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('mv_cbd'),
data: {dir: dir, files: files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter: ''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not movable. Do you want to move the rest?", {count: failed}),
go
);
else
go();
};
browser.deleteClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
var failed = 0;
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable && this.clipboard[i].writable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
else
failed++;
if (this.clipboard.length == failed) {
browser.alert(this.label("The files in the Clipboard are not removable."))
return;
}
var go = function(callBack) {
browser.fadeFiles();
$.ajax({
type: 'POST',
dataType: 'json',
url: browser.baseGetData('rm_cbd'),
data: {files:files},
async: false,
success: function(data) {
if (callBack) callBack();
browser.check4errors(data);
browser.clearClipboard();
browser.refresh();
},
error: function() {
if (callBack) callBack();
$('#files > div').css({
opacity: '',
filter:''
});
browser.alert(browser.label("Unknown error."));
}
});
};
if (failed)
browser.confirm(
browser.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?", {count: failed}),
go
);
else
go();
};
browser.downloadClipboard = function() {
if (!this.clipboard || !this.clipboard.length) return;
var files = [];
for (i = 0; i < this.clipboard.length; i++)
if (this.clipboard[i].readable)
files[i] = this.clipboard[i].dir + '/' + this.clipboard[i].name;
if (files.length)
this.post(this.baseGetData('downloadClipboard'), {files:files});
};
browser.clearClipboard = function() {
$('#clipboard').html('');
this.clipboard = [];
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Base JavaScript object properties
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
var browser = {
opener: {},
support: {},
files: [],
clipboard: [],
labels: [],
shows: [],
orders: [],
cms: ""
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Upload files using drag and drop
* @package KCFinder
* @version 2.51
* @author Forum user (updated by Pavel Tzonkov)
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initDropUpload = function() {
if ((typeof(XMLHttpRequest) == 'undefined') ||
(typeof(document.addEventListener) == 'undefined') ||
(typeof(File) == 'undefined') ||
(typeof(FileReader) == 'undefined')
)
return;
if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
var ords = Array.prototype.map.call(datastr, function(x) {
return x.charCodeAt(0) & 0xff;
});
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
}
var uploadQueue = [],
uploadInProgress = false,
filesCount = 0,
errors = [],
files = $('#files'),
folders = $('div.folder > a'),
boundary = '------multipartdropuploadboundary' + (new Date).getTime(),
currentFile,
filesDragOver = function(e) {
if (e.preventDefault) e.preventDefault();
$('#files').addClass('drag');
return false;
},
filesDragEnter = function(e) {
if (e.preventDefault) e.preventDefault();
return false;
},
filesDragLeave = function(e) {
if (e.preventDefault) e.preventDefault();
$('#files').removeClass('drag');
return false;
},
filesDrop = function(e) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
$('#files').removeClass('drag');
if (!$('#folders span.current').first().parent().data('writable')) {
browser.alert("Cannot write to upload folder.");
return false;
}
filesCount += e.dataTransfer.files.length
for (var i = 0; i < e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
file.thisTargetDir = browser.dir;
uploadQueue.push(file);
}
processUploadQueue();
return false;
},
folderDrag = function(e) {
if (e.preventDefault) e.preventDefault();
return false;
},
folderDrop = function(e, dir) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
if (!$(dir).data('writable')) {
browser.alert("Cannot write to upload folder.");
return false;
}
filesCount += e.dataTransfer.files.length
for (var i = 0; i < e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
file.thisTargetDir = $(dir).data('path');
uploadQueue.push(file);
}
processUploadQueue();
return false;
};
files.get(0).removeEventListener('dragover', filesDragOver, false);
files.get(0).removeEventListener('dragenter', filesDragEnter, false);
files.get(0).removeEventListener('dragleave', filesDragLeave, false);
files.get(0).removeEventListener('drop', filesDrop, false);
files.get(0).addEventListener('dragover', filesDragOver, false);
files.get(0).addEventListener('dragenter', filesDragEnter, false);
files.get(0).addEventListener('dragleave', filesDragLeave, false);
files.get(0).addEventListener('drop', filesDrop, false);
folders.each(function() {
var folder = this,
dragOver = function(e) {
$(folder).children('span.folder').addClass('context');
return folderDrag(e);
},
dragLeave = function(e) {
$(folder).children('span.folder').removeClass('context');
return folderDrag(e);
},
drop = function(e) {
$(folder).children('span.folder').removeClass('context');
return folderDrop(e, folder);
};
this.removeEventListener('dragover', dragOver, false);
this.removeEventListener('dragenter', folderDrag, false);
this.removeEventListener('dragleave', dragLeave, false);
this.removeEventListener('drop', drop, false);
this.addEventListener('dragover', dragOver, false);
this.addEventListener('dragenter', folderDrag, false);
this.addEventListener('dragleave', dragLeave, false);
this.addEventListener('drop', drop, false);
});
function updateProgress(evt) {
var progress = evt.lengthComputable
? Math.round((evt.loaded * 100) / evt.total) + '%'
: Math.round(evt.loaded / 1024) + " KB";
$('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", {
number: filesCount - uploadQueue.length,
count: filesCount,
progress: progress
}));
}
function processUploadQueue() {
if (uploadInProgress)
return false;
if (uploadQueue && uploadQueue.length) {
var file = uploadQueue.shift();
currentFile = file;
$('#loading').html(browser.label("Uploading file {number} of {count}... {progress}", {
number: filesCount - uploadQueue.length,
count: filesCount,
progress: ""
}));
$('#loading').css('display', 'inline');
var reader = new FileReader();
reader.thisFileName = file.name;
reader.thisFileType = file.type;
reader.thisFileSize = file.size;
reader.thisTargetDir = file.thisTargetDir;
reader.onload = function(evt) {
uploadInProgress = true;
var postbody = '--' + boundary + '\r\nContent-Disposition: form-data; name="upload[]"';
if (evt.target.thisFileName)
postbody += '; filename="' + _.utf8encode(evt.target.thisFileName) + '"';
postbody += '\r\n';
if (evt.target.thisFileSize)
postbody += 'Content-Length: ' + evt.target.thisFileSize + '\r\n';
postbody += 'Content-Type: ' + evt.target.thisFileType + '\r\n\r\n' + evt.target.result + '\r\n--' + boundary + '\r\nContent-Disposition: form-data; name="dir"\r\n\r\n' + _.utf8encode(evt.target.thisTargetDir) + '\r\n--' + boundary + '\r\n--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest();
xhr.thisFileName = evt.target.thisFileName;
if (xhr.upload) {
xhr.upload.thisFileName = evt.target.thisFileName;
xhr.upload.addEventListener("progress", updateProgress, false);
}
xhr.open('POST', browser.baseGetData('upload'), true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Content-Length', postbody.length);
xhr.onload = function(e) {
$('#loading').css('display', 'none');
if (browser.dir == reader.thisTargetDir)
browser.fadeFiles();
uploadInProgress = false;
processUploadQueue();
if (xhr.responseText.substr(0, 1) != '/')
errors[errors.length] = xhr.responseText;
}
xhr.sendAsBinary(postbody);
};
reader.onerror = function(evt) {
$('#loading').css('display', 'none');
uploadInProgress = false;
processUploadQueue();
errors[errors.length] = browser.label("Failed to upload {filename}!", {
filename: evt.target.thisFileName
});
};
reader.readAsBinaryString(file);
} else {
filesCount = 0;
var loop = setInterval(function() {
if (uploadInProgress) return;
clearInterval(loop);
if (currentFile.thisTargetDir == browser.dir)
browser.refresh();
boundary = '------multipartdropuploadboundary' + (new Date).getTime();
if (errors.length) {
browser.alert(errors.join('\n'));
errors = [];
}
}, 333);
}
}
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Settings panel functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.initSettings = function() {
if (!this.shows.length) {
var showInputs = $('#show input[type="checkbox"]').toArray();
$.each(showInputs, function (i, input) {
browser.shows[i] = input.name;
});
}
var shows = this.shows;
if (!_.kuki.isSet('showname')) {
_.kuki.set('showname', 'on');
$.each(shows, function (i, val) {
if (val != "name") _.kuki.set('show' + val, 'off');
});
}
$('#show input[type="checkbox"]').click(function() {
var kuki = $(this).get(0).checked ? 'on' : 'off';
_.kuki.set('show' + $(this).get(0).name, kuki)
if ($(this).get(0).checked)
$('#files .file div.' + $(this).get(0).name).css('display', 'block');
else
$('#files .file div.' + $(this).get(0).name).css('display', 'none');
});
$.each(shows, function(i, val) {
var checked = (_.kuki.get('show' + val) == 'on') ? 'checked' : '';
$('#show input[name="' + val + '"]').get(0).checked = checked;
});
if (!this.orders.length) {
var orderInputs = $('#order input[type="radio"]').toArray();
$.each(orderInputs, function (i, input) {
browser.orders[i] = input.value;
});
}
var orders = this.orders;
if (!_.kuki.isSet('order'))
_.kuki.set('order', 'name');
if (!_.kuki.isSet('orderDesc'))
_.kuki.set('orderDesc', 'off');
$('#order input[value="' + _.kuki.get('order') + '"]').get(0).checked = true;
$('#order input[name="desc"]').get(0).checked = (_.kuki.get('orderDesc') == 'on');
$('#order input[type="radio"]').click(function() {
_.kuki.set('order', $(this).get(0).value);
browser.orderFiles();
});
$('#order input[name="desc"]').click(function() {
_.kuki.set('orderDesc', $(this).get(0).checked ? 'on' : 'off');
browser.orderFiles();
});
if (!_.kuki.isSet('view'))
_.kuki.set('view', 'thumbs');
if (_.kuki.get('view') == 'list') {
$('#show input').each(function() { this.checked = true; });
$('#show input').each(function() { this.disabled = true; });
}
$('#view input[value="' + _.kuki.get('view') + '"]').get(0).checked = true;
$('#view input').click(function() {
var view = $(this).attr('value');
if (_.kuki.get('view') != view) {
_.kuki.set('view', view);
if (view == 'list') {
$('#show input').each(function() { this.checked = true; });
$('#show input').each(function() { this.disabled = true; });
} else {
$.each(browser.shows, function(i, val) {
$('#show input[name="' + val + '"]').get(0).checked =
(_.kuki.get('show' + val) == "on");
});
$('#show input').each(function() { this.disabled = false; });
}
}
browser.refresh();
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Miscellaneous functionality
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.drag = function(ev, dd) {
var top = dd.offsetY,
left = dd.offsetX;
if (top < 0) top = 0;
if (left < 0) left = 0;
if (top + $(this).outerHeight() > $(window).height())
top = $(window).height() - $(this).outerHeight();
if (left + $(this).outerWidth() > $(window).width())
left = $(window).width() - $(this).outerWidth();
$(this).css({
top: top,
left: left
});
};
browser.showDialog = function(e) {
$('#dialog').css({left: 0, top: 0});
this.shadow();
if ($('#dialog div.box') && !$('#dialog div.title').get(0)) {
var html = $('#dialog div.box').html();
var title = $('#dialog').data('title') ? $('#dialog').data('title') : "";
html = '<div class="title"><span class="close"></span>' + title + '</div>' + html;
$('#dialog div.box').html(html);
$('#dialog div.title span.close').mousedown(function() {
$(this).addClass('clicked');
});
$('#dialog div.title span.close').mouseup(function() {
$(this).removeClass('clicked');
});
$('#dialog div.title span.close').click(function() {
browser.hideDialog();
browser.hideAlert();
});
}
$('#dialog').drag(browser.drag, {handle: '#dialog div.title'});
$('#dialog').css('display', 'block');
if (e) {
var left = e.pageX - parseInt($('#dialog').outerWidth() / 2);
var top = e.pageY - parseInt($('#dialog').outerHeight() / 2);
if (left < 0) left = 0;
if (top < 0) top = 0;
if (($('#dialog').outerWidth() + left) > $(window).width())
left = $(window).width() - $('#dialog').outerWidth();
if (($('#dialog').outerHeight() + top) > $(window).height())
top = $(window).height() - $('#dialog').outerHeight();
$('#dialog').css({
left: left + 'px',
top: top + 'px'
});
} else
$('#dialog').css({
left: parseInt(($(window).width() - $('#dialog').outerWidth()) / 2) + 'px',
top: parseInt(($(window).height() - $('#dialog').outerHeight()) / 2) + 'px'
});
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (e.keyCode == 27)
browser.hideDialog();
});
};
browser.hideDialog = function() {
this.unshadow();
if ($('#clipboard').hasClass('selected'))
$('#clipboard').removeClass('selected');
$('#dialog').css('display', 'none');
$('div.folder > a > span.folder').removeClass('context');
$('#dialog').html('');
$('#dialog').data('title', null);
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
browser.hideAlert();
};
browser.showAlert = function(shadow) {
$('#alert').css({left: 0, top: 0});
if (typeof shadow == 'undefined')
shadow = true;
if (shadow)
this.shadow();
var left = parseInt(($(window).width() - $('#alert').outerWidth()) / 2),
top = parseInt(($(window).height() - $('#alert').outerHeight()) / 2);
var wheight = $(window).height();
if (top < 0)
top = 0;
$('#alert').css({
left: left + 'px',
top: top + 'px',
display: 'block'
});
if ($('#alert').outerHeight() > wheight) {
$('#alert div.message').css({
height: wheight - $('#alert div.title').outerHeight() - $('#alert div.ok').outerHeight() - 20 + 'px'
});
}
$(document).unbind('keydown');
$(document).keydown(function(e) {
if (e.keyCode == 27) {
browser.hideDialog();
browser.hideAlert();
$(document).unbind('keydown');
$(document).keydown(function(e) {
return !browser.selectAll(e);
});
}
});
};
browser.hideAlert = function(shadow) {
if (typeof shadow == 'undefined')
shadow = true;
if (shadow)
this.unshadow();
$('#alert').css('display', 'none');
$('#alert').html('');
$('#alert').data('title', null);
};
browser.alert = function(msg, shadow) {
msg = msg.replace(/\r?\n/g, "<br />");
var title = $('#alert').data('title') ? $('#alert').data('title') : browser.label("Attention");
$('#alert').html('<div class="title"><span class="close"></span>' + title + '</div><div class="message">' + msg + '</div><div class="ok"><button>' + browser.label("OK") + '</button></div>');
$('#alert div.ok button').click(function() {
browser.hideAlert(shadow);
});
$('#alert div.title span.close').mousedown(function() {
$(this).addClass('clicked');
});
$('#alert div.title span.close').mouseup(function() {
$(this).removeClass('clicked');
});
$('#alert div.title span.close').click(function() {
browser.hideAlert(shadow);
});
$('#alert').drag(browser.drag, {handle: "#alert div.title"});
browser.showAlert(shadow);
};
browser.confirm = function(question, callBack) {
$('#dialog').data('title', browser.label("Question"));
$('#dialog').html('<div class="box"><div class="question">' + browser.label(question) + '<div class="buttons"><button>' + browser.label("No") + '</button> <button>' + browser.label("Yes") + '</button></div></div></div>');
browser.showDialog();
$('#dialog div.buttons button').first().click(function() {
browser.hideDialog();
});
$('#dialog div.buttons button').last().click(function() {
if (callBack)
callBack(function() {
browser.hideDialog();
});
else
browser.hideDialog();
});
$('#dialog div.buttons button').get(1).focus();
};
browser.shadow = function() {
$('#shadow').css('display', 'block');
};
browser.unshadow = function() {
$('#shadow').css('display', 'none');
};
browser.showMenu = function(e) {
var left = e.pageX;
var top = e.pageY;
if (($('#dialog').outerWidth() + left) > $(window).width())
left = $(window).width() - $('#dialog').outerWidth();
if (($('#dialog').outerHeight() + top) > $(window).height())
top = $(window).height() - $('#dialog').outerHeight();
$('#dialog').css({
left: left + 'px',
top: top + 'px',
display: 'none'
});
$('#dialog').fadeIn();
};
browser.fileNameDialog = function(e, post, inputName, inputValue, url, labels, callBack, selectAll) {
var html = '<form method="post" action="javascript:;">' +
'<div class="box">' +
'<input name="' + inputName + '" type="text" /><br />' +
'<div style="text-align:right">' +
'<input type="submit" value="' + _.htmlValue(this.label("OK")) + '" /> ' +
'<input type="button" value="' + _.htmlValue(this.label("Cancel")) + '" onclick="browser.hideDialog(); browser.hideAlert(); return false" />' +
'</div></div></form>';
$('#dialog').html(html);
$('#dialog').data('title', this.label(labels.title));
$('#dialog input[name="' + inputName + '"]').attr('value', inputValue);
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$('#dialog form').submit(function() {
var name = this.elements[0];
name.value = $.trim(name.value);
if (name.value == '') {
browser.alert(browser.label(labels.errEmpty), false);
name.focus();
return;
} else if (/[\/\\]/g.test(name.value)) {
browser.alert(browser.label(labels.errSlash), false);
name.focus();
return;
} else if (name.value.substr(0, 1) == ".") {
browser.alert(browser.label(labels.errDot), false);
name.focus();
return;
}
eval('post.' + inputName + ' = name.value;');
$.ajax({
type: 'POST',
dataType: 'json',
url: url,
data: post,
async: false,
success: function(data) {
if (browser.check4errors(data, false))
return;
if (callBack) callBack(data);
browser.hideDialog();
},
error: function() {
browser.alert(browser.label("Unknown error."), false);
}
});
return false;
});
browser.showDialog(e);
$('#dialog').css('display', 'block');
$('#dialog input[type="submit"]').click(function() {
return $('#dialog form').submit();
});
var field = $('#dialog input[type="text"]');
var value = field.attr('value');
if (!selectAll && /^(.+)\.[^\.]+$/ .test(value)) {
value = value.replace(/^(.+)\.[^\.]+$/, "$1");
_.selection(field.get(0), 0, value.length);
} else {
field.get(0).focus();
field.get(0).select();
}
};
browser.orderFiles = function(callBack, selected) {
var order = _.kuki.get('order');
var desc = (_.kuki.get('orderDesc') == 'on');
if (!browser.files || !browser.files.sort)
browser.files = [];
browser.files = browser.files.sort(function(a, b) {
var a1, b1, arr;
if (!order) order = 'name';
if (order == 'date') {
a1 = a.mtime;
b1 = b.mtime;
} else if (order == 'type') {
a1 = _.getFileExtension(a.name);
b1 = _.getFileExtension(b.name);
} else if (order == 'size') {
a1 = a.size;
b1 = b.size;
} else
eval('a1 = a.' + order + '.toLowerCase(); b1 = b.' + order + '.toLowerCase();');
if ((order == 'size') || (order == 'date')) {
if (a1 < b1) return desc ? 1 : -1;
if (a1 > b1) return desc ? -1 : 1;
}
if (a1 == b1) {
a1 = a.name.toLowerCase();
b1 = b.name.toLowerCase();
arr = [a1, b1];
arr = arr.sort();
return (arr[0] == a1) ? -1 : 1;
}
arr = [a1, b1];
arr = arr.sort();
if (arr[0] == a1) return desc ? 1 : -1;
return desc ? -1 : 1;
});
browser.showFiles(callBack, selected);
browser.initFiles();
};
browser.humanSize = function(size) {
if (size < 1024) {
size = size.toString() + ' B';
} else if (size < 1048576) {
size /= 1024;
size = parseInt(size).toString() + ' KB';
} else if (size < 1073741824) {
size /= 1048576;
size = parseInt(size).toString() + ' MB';
} else if (size < 1099511627776) {
size /= 1073741824;
size = parseInt(size).toString() + ' GB';
} else {
size /= 1099511627776;
size = parseInt(size).toString() + ' TB';
}
return size;
};
browser.baseGetData = function(act) {
var data = 'browse.php?type=' + encodeURIComponent(this.type) + '&lng=' + this.lang;
if (act)
data += "&act=" + act;
if (this.cms)
data += "&cms=" + this.cms;
return data;
};
browser.label = function(index, data) {
var label = this.labels[index] ? this.labels[index] : index;
if (data)
$.each(data, function(key, val) {
label = label.replace('{' + key + '}', val);
});
return label;
};
browser.check4errors = function(data, shadow) {
if (!data.error)
return false;
var msg;
if (data.error.join)
msg = data.error.join("\n");
else
msg = data.error;
browser.alert(msg, shadow);
return true;
};
browser.post = function(url, data) {
var html = '<form id="postForm" method="POST" action="' + url + '">';
$.each(data, function(key, val) {
if ($.isArray(val))
$.each(val, function(i, aval) {
html += '<input type="hidden" name="' + _.htmlValue(key) + '[]" value="' + _.htmlValue(aval) + '" />';
});
else
html += '<input type="hidden" name="' + _.htmlValue(key) + '" value="' + _.htmlValue(val) + '" />';
});
html += '</form>';
$('#dialog').html(html);
$('#dialog').css('display', 'block');
$('#postForm').get(0).submit();
};
browser.fadeFiles = function() {
$('#files > div').css({
opacity: '0.4',
filter: 'alpha(opacity:40)'
});
};
| JavaScript |
<?php
/** This file is part of KCFinder project
*
* @desc Object initializations
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/?>
browser.init = function() {
if (!this.checkAgent()) return;
$('body').click(function() {
browser.hideDialog();
});
$('#shadow').click(function() {
return false;
});
$('#dialog').unbind();
$('#dialog').click(function() {
return false;
});
$('#alert').unbind();
$('#alert').click(function() {
return false;
});
this.initOpeners();
this.initSettings();
this.initContent();
this.initToolbar();
this.initResizer();
this.initDropUpload();
};
browser.checkAgent = function() {
if (!$.browser.version ||
($.browser.msie && (parseInt($.browser.version) < 7) && !this.support.chromeFrame) ||
($.browser.opera && (parseInt($.browser.version) < 10)) ||
($.browser.mozilla && (parseFloat($.browser.version.replace(/^(\d+(\.\d+)?)([^\d].*)?$/, "$1")) < 1.8))
) {
var html = '<div style="padding:10px">Your browser is not capable to display KCFinder. Please update your browser or install another one: <a href="http://www.mozilla.com/firefox/" target="_blank">Mozilla Firefox</a>, <a href="http://www.apple.com/safari" target="_blank">Apple Safari</a>, <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>, <a href="http://www.opera.com/browser" target="_blank">Opera</a>.';
if ($.browser.msie)
html += ' You may also install <a href="http://www.google.com/chromeframe" target="_blank">Google Chrome Frame ActiveX plugin</a> to get Internet Explorer 6 working.';
html += '</div>';
$('body').html(html);
return false;
}
return true;
};
browser.initOpeners = function() {
if (this.opener.TinyMCE && (typeof(tinyMCEPopup) == 'undefined'))
this.opener.TinyMCE = null;
if (this.opener.TinyMCE)
this.opener.callBack = true;
if ((!this.opener.name || (this.opener.name == 'fckeditor')) &&
window.opener && window.opener.SetUrl
) {
this.opener.FCKeditor = true;
this.opener.callBack = true;
}
if (this.opener.CKEditor) {
if (window.parent && window.parent.CKEDITOR)
this.opener.CKEditor.object = window.parent.CKEDITOR;
else if (window.opener && window.opener.CKEDITOR) {
this.opener.CKEditor.object = window.opener.CKEDITOR;
this.opener.callBack = true;
} else
this.opener.CKEditor = null;
}
if (!this.opener.CKEditor && !this.opener.FCKEditor && !this.TinyMCE) {
if ((window.opener && window.opener.KCFinder && window.opener.KCFinder.callBack) ||
(window.parent && window.parent.KCFinder && window.parent.KCFinder.callBack)
)
this.opener.callBack = window.opener
? window.opener.KCFinder.callBack
: window.parent.KCFinder.callBack;
if ((
window.opener &&
window.opener.KCFinder &&
window.opener.KCFinder.callBackMultiple
) || (
window.parent &&
window.parent.KCFinder &&
window.parent.KCFinder.callBackMultiple
)
)
this.opener.callBackMultiple = window.opener
? window.opener.KCFinder.callBackMultiple
: window.parent.KCFinder.callBackMultiple;
}
};
browser.initContent = function() {
$('div#folders').html(this.label("Loading folders..."));
$('div#files').html(this.label("Loading files..."));
$.ajax({
type: 'GET',
dataType: 'json',
url: browser.baseGetData('init'),
async: false,
success: function(data) {
if (browser.check4errors(data))
return;
browser.dirWritable = data.dirWritable;
$('#folders').html(browser.buildTree(data.tree));
browser.setTreeData(data.tree);
browser.initFolders();
browser.files = data.files ? data.files : [];
browser.orderFiles();
},
error: function() {
$('div#folders').html(browser.label("Unknown error."));
$('div#files').html(browser.label("Unknown error."));
}
});
};
browser.initResizer = function() {
var cursor = ($.browser.opera) ? 'move' : 'col-resize';
$('#resizer').css('cursor', cursor);
$('#resizer').drag('start', function() {
$(this).css({opacity:'0.4', filter:'alpha(opacity:40)'});
$('#all').css('cursor', cursor);
});
$('#resizer').drag(function(e) {
var left = e.pageX - parseInt(_.nopx($(this).css('width')) / 2);
left = (left >= 0) ? left : 0;
left = (left + _.nopx($(this).css('width')) < $(window).width())
? left : $(window).width() - _.nopx($(this).css('width'));
$(this).css('left', left);
});
var end = function() {
$(this).css({opacity:'0', filter:'alpha(opacity:0)'});
$('#all').css('cursor', '');
var left = _.nopx($(this).css('left')) + _.nopx($(this).css('width'));
var right = $(window).width() - left;
$('#left').css('width', left + 'px');
$('#right').css('width', right + 'px');
_('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px';
_('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px';
_('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px';
browser.fixFilesHeight();
};
$('#resizer').drag('end', end);
$('#resizer').mouseup(end);
};
browser.resize = function() {
_('left').style.width = '25%';
_('right').style.width = '75%';
_('toolbar').style.height = $('#toolbar a').outerHeight() + "px";
_('shadow').style.width = $(window).width() + 'px';
_('shadow').style.height = _('resizer').style.height = $(window).height() + 'px';
_('left').style.height = _('right').style.height =
$(window).height() - $('#status').outerHeight() + 'px';
_('folders').style.height =
$('#left').outerHeight() - _.outerVSpace('#folders') + 'px';
browser.fixFilesHeight();
var width = $('#left').outerWidth() + $('#right').outerWidth();
_('status').style.width = width + 'px';
while ($('#status').outerWidth() > width)
_('status').style.width = _.nopx(_('status').style.width) - 1 + 'px';
while ($('#status').outerWidth() < width)
_('status').style.width = _.nopx(_('status').style.width) + 1 + 'px';
if ($.browser.msie && ($.browser.version.substr(0, 1) < 8))
_('right').style.width = $(window).width() - $('#left').outerWidth() + 'px';
_('files').style.width = $('#right').innerWidth() - _.outerHSpace('#files') + 'px';
_('resizer').style.left = $('#left').outerWidth() - _.outerRightSpace('#folders', 'm') + 'px';
_('resizer').style.width = _.outerRightSpace('#folders', 'm') + _.outerLeftSpace('#files', 'm') + 'px';
};
browser.fixFilesHeight = function() {
_('files').style.height =
$('#left').outerHeight() - $('#toolbar').outerHeight() - _.outerVSpace('#files') -
(($('#settings').css('display') != "none") ? $('#settings').outerHeight() : 0) + 'px';
};
| JavaScript |
/** This file is part of KCFinder project
*
* @desc Helper object
* @package KCFinder
* @version 2.51
* @author Pavel Tzonkov <pavelc@users.sourceforge.net>
* @copyright 2010, 2011 KCFinder Project
* @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2
* @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2
* @link http://kcfinder.sunhater.com
*/
var _ = function(id) {
return document.getElementById(id);
};
_.nopx = function(val) {
return parseInt(val.replace(/^(\d+)px$/, "$1"));
};
_.unselect = function() {
if (document.selection && document.selection.empty)
document.selection.empty() ;
else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges)
sel.removeAllRanges();
}
};
_.selection = function(field, start, end) {
if (field.createTextRange) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end-start);
selRange.select();
} else if (field.setSelectionRange) {
field.setSelectionRange(start, end);
} else if (field.selectionStart) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
};
_.htmlValue = function(value) {
return value
.replace(/\&/g, "&")
.replace(/\"/g, """)
.replace(/\'/g, "'");
};
_.htmlData = function(value) {
return value
.replace(/\&/g, "&")
.replace(/\</g, "<")
.replace(/\>/g, ">")
.replace(/\ /g, " ");
}
_.jsValue = function(value) {
return value
.replace(/\\/g, "\\\\")
.replace(/\r?\n/, "\\\n")
.replace(/\"/g, "\\\"")
.replace(/\'/g, "\\'");
};
_.basename = function(path) {
var expr = /^.*\/([^\/]+)\/?$/g;
return expr.test(path)
? path.replace(expr, "$1")
: path;
};
_.dirname = function(path) {
var expr = /^(.*)\/[^\/]+\/?$/g;
return expr.test(path)
? path.replace(expr, "$1")
: '';
};
_.inArray = function(needle, arr) {
if ((typeof arr == 'undefined') || !arr.length || !arr.push)
return false;
for (var i = 0; i < arr.length; i++)
if (arr[i] == needle)
return true;
return false;
};
_.getFileExtension = function(filename, toLower) {
if (typeof(toLower) == 'undefined') toLower = true;
if (/^.*\.[^\.]*$/.test(filename)) {
var ext = filename.replace(/^.*\.([^\.]*)$/, "$1");
return toLower ? ext.toLowerCase(ext) : ext;
} else
return "";
};
_.escapeDirs = function(path) {
var fullDirExpr = /^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/,
prefix = "";
if (fullDirExpr.test(path)) {
var port = path.replace(fullDirExpr, "$4");
prefix = path.replace(fullDirExpr, "$1://$2")
if (port.length)
prefix += ":" + port;
prefix += "/";
path = path.replace(fullDirExpr, "$5");
}
var dirs = path.split('/');
var escapePath = '';
for (var i = 0; i < dirs.length; i++)
escapePath += encodeURIComponent(dirs[i]) + '/';
return prefix + escapePath.substr(0, escapePath.length - 1);
};
_.outerSpace = function(selector, type, mbp) {
if (!mbp) mbp = "mbp";
var r = 0;
if (/m/i.test(mbp)) {
var m = _.nopx($(selector).css('margin-' + type));
if (m) r += m;
}
if (/b/i.test(mbp)) {
var b = _.nopx($(selector).css('border-' + type + '-width'));
if (b) r += b;
}
if (/p/i.test(mbp)) {
var p = _.nopx($(selector).css('padding-' + type));
if (p) r += p;
}
return r;
};
_.outerLeftSpace = function(selector, mbp) {
return _.outerSpace(selector, 'left', mbp);
};
_.outerTopSpace = function(selector, mbp) {
return _.outerSpace(selector, 'top', mbp);
};
_.outerRightSpace = function(selector, mbp) {
return _.outerSpace(selector, 'right', mbp);
};
_.outerBottomSpace = function(selector, mbp) {
return _.outerSpace(selector, 'bottom', mbp);
};
_.outerHSpace = function(selector, mbp) {
return (_.outerLeftSpace(selector, mbp) + _.outerRightSpace(selector, mbp));
};
_.outerVSpace = function(selector, mbp) {
return (_.outerTopSpace(selector, mbp) + _.outerBottomSpace(selector, mbp));
};
_.kuki = {
prefix: '',
duration: 356,
domain: '',
path: '',
secure: false,
set: function(name, value, duration, domain, path, secure) {
name = this.prefix + name;
if (duration == null) duration = this.duration;
if (secure == null) secure = this.secure;
if ((domain == null) && this.domain) domain = this.domain;
if ((path == null) && this.path) path = this.path;
secure = secure ? true : false;
var date = new Date();
date.setTime(date.getTime() + (duration * 86400000));
var expires = date.toGMTString();
var str = name + '=' + value + '; expires=' + expires;
if (domain != null) str += '; domain=' + domain;
if (path != null) str += '; path=' + path;
if (secure) str += '; secure';
return (document.cookie = str) ? true : false;
},
get: function(name) {
name = this.prefix + name;
var nameEQ = name + '=';
var kukis = document.cookie.split(';');
var kuki;
for (var i = 0; i < kukis.length; i++) {
kuki = kukis[i];
while (kuki.charAt(0) == ' ')
kuki = kuki.substring(1, kuki.length);
if (kuki.indexOf(nameEQ) == 0)
return kuki.substring(nameEQ.length, kuki.length);
}
return null;
},
del: function(name) {
return this.set(name, '', -1);
},
isSet: function(name) {
return (this.get(name) != null);
}
};
_.md5 = function(string) {
var RotateLeft = function(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
};
var AddUnsigned = function(lX,lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4)
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4)
return (lResult & 0x40000000)
? (lResult ^ 0xC0000000 ^ lX8 ^ lY8)
: (lResult ^ 0x40000000 ^ lX8 ^ lY8);
else
return (lResult ^ lX8 ^ lY8);
};
var F = function(x, y, z) { return (x & y) | ((~x) & z); };
var G = function(x, y, z) { return (x & z) | (y & (~z)); };
var H = function(x, y, z) { return (x ^ y ^ z); };
var I = function(x, y, z) { return (y ^ (x | (~z))); };
var FF = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var GG = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var HH = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var II = function(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
var ConvertToWordArray = function(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = [lNumberOfWords - 1];
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var WordToHex = function(lValue) {
var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2,2);
}
return WordToHexValue;
};
var x = [];
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
string = _.utf8encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a; BB = b; CC = c; DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD);
}
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toLowerCase();
};
_.utf8encode = function(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
| JavaScript |
/*!
* jQuery Right-Click Plugin
*
* Version 1.01
*
* Cory S.N. LaViska
* A Beautiful Site (http://abeautifulsite.net/)
* 20 December 2008
*
* Visit http://abeautifulsite.net/notebook/68 for more information
*
* License:
* This plugin is dual-licensed under the GNU General Public License and the MIT License
* and is copyright 2008 A Beautiful Site, LLC.
*/
if(jQuery){(function(){$.extend($.fn,{rightClick:function(a){$(this).each(function(){$(this).mousedown(function(c){var b=c;if($.browser.safari&&navigator.userAgent.indexOf("Mac")!=-1&&parseInt($.browser.version,10)<=525){if(b.button==2){a.call($(this),b);return false}else{return true}}else{$(this).mouseup(function(){$(this).unbind("mouseup");if(b.button==2){a.call($(this),b);return false}else{return true}})}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseDown:function(a){$(this).each(function(){$(this).mousedown(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},rightMouseUp:function(a){$(this).each(function(){$(this).mouseup(function(b){if(b.button==2){a.call($(this),b);return false}else{return true}});$(this)[0].oncontextmenu=function(){return false}});return $(this)},noContext:function(){$(this).each(function(){$(this)[0].oncontextmenu=function(){return false}});return $(this)}})})(jQuery)}; | JavaScript |
// If this file exists in theme directory, it will be loaded in <head> section
var imgLoading = new Image();
imgLoading.src = 'themes/oxygen/img/loading.gif';
| JavaScript |
// If this file exists in theme directory, it will be loaded in <head> section
var imgLoading = new Image();
imgLoading.src = 'themes/dark/img/loading.gif';
| JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
| JavaScript |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.5';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/rtmp','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
convertSMPTEtoSeconds: function (SMPTE) {
if (typeof SMPTE != 'string')
return false;
SMPTE = SMPTE.replace(',', '.');
var secs = 0,
decimalLen = (SMPTE.indexOf('.') != -1) ? SMPTE.split('.')[1].length : 0,
multiplier = 1;
SMPTE = SMPTE.split(':').reverse();
for (var i = 0; i < SMPTE.length; i++) {
multiplier = 1;
if (i > 0) {
multiplier = Math.pow(60, i);
}
secs += Number(SMPTE[i]) * multiplier;
}
return Number(secs.toFixed(decimalLen));
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// auto_plugin: prefer plugins and then attempt native HTML5
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// streamer for RTMP streaming
flashStreamer: '',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
// if `auto_plugin` mode, then cache the native result but try plugins.
if (options.mode !== 'auto_plugin') {
return result;
}
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'auto_plugin' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// at this point, being in 'auto_plugin' mode implies that we tried plugins but failed.
// if we have native support then return that.
if (options.mode === 'auto_plugin' && result.method === 'native') {
return result;
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|webmv|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + this.getTypeFromExtension(ext);
},
getTypeFromExtension: function(ext) {
switch (ext) {
case 'mp4':
case 'm4v':
return 'mp4';
case 'webm':
case 'webma':
case 'webmv':
return 'webm';
case 'ogg':
case 'oga':
case 'ogv':
return 'ogg';
default:
return ext;
}
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'flashstreamer=' + options.flashStreamer,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
//console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// default amount to move back when back key is pressed
defaultSeekBackwardInterval: function(media) {
return (media.duration * 0.05);
},
// default amount to move forward when forward key is pressed
defaultSeekForwardInterval: function(media) {
return (media.duration * 0.05);
},
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - player.options.defaultSeekBackwardInterval(media), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + player.options.defaultSeekForwardInterval(media), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var tagType = (t.isVideo ? 'video' : 'audio'),
capsTagName = tagType.substring(0,1).toUpperCase() + tagType.substring(1);
if (t.options[tagType + 'Width'] > 0 || t.options[tagType + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagType + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagType + 'Height'] > 0 || t.options[tagType + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagType + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%') {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
if ( newHeight != 0 ) {
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.isVideo) {
if (t.media.setVideoSize) {
t.media.setVideoSize(parentWidth, newHeight);
}
}
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
}
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media, e.keyCode);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType === 'flash') {
t.media.remove();
} else if (t.media.pluginType === 'native') {
t.$media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
var target = null;
if (mejs.MediaFeatures.hasMozNativeFullScreen) {
target = $(document);
} else {
target = player.container;
}
target.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
//console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
$.ajax({
url: track.src,
dataType: "text",
success: function(d) {
// parse the loaded file
if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
track.entries = mejs.TrackFormatParser.dfxp.parse(d);
} else {
track.entries = mejs.TrackFormatParser.webvvt.parse(d);
}
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
webvvt: {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function(trackText) {
var
i = 0,
lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
},
// Thanks to Justin Capella: https://github.com/johndyer/mediaelement/pull/420
dfxp: {
parse: function(trackText) {
trackText = $(trackText).filter("tt");
var
i = 0,
container = trackText.children("div").eq(0),
lines = container.find("p"),
styleNode = trackText.find("#" + container.attr("style")),
styles,
begin,
end,
text,
entries = {text:[], times:[]};
if (styleNode.length) {
var attributes = styleNode.removeAttr("id").get(0).attributes;
if (attributes.length) {
styles = {};
for (i = 0; i < attributes.length; i++) {
styles[attributes[i].name.split(":")[1]] = attributes[i].value;
}
}
}
for(i = 0; i<lines.length; i++) {
var style;
var _temp_times = {
start: null,
stop: null,
style: null
};
if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
if (styles) {
style = "";
for (var _style in styles) {
style += _style + ":" + styles[_style] + ";";
}
}
if (style) _temp_times.style = style;
if (_temp_times.start == 0) _temp_times.start = 0.200;
entries.times.push(_temp_times);
text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
entries.text.push(text);
if (entries.times.start == 0) entries.times.start = 2;
}
return entries;
}
},
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| JavaScript |
$(function() {
$("#slider").draggable({
axis: 'x',
containment: 'parent',
drag: function(event, ui) {
if (ui.position.left > 550) {
$("#well").fadeOut();
} else {
// Apparently Safari isn't allowing partial opacity on text with background clip? Not sure.
// $("h2 span").css("opacity", 100 - (ui.position.left / 5))
}
},
stop: function(event, ui) {
if (ui.position.left < 551) {
$(this).animate({
left: 0
})
}
}
});
// The following credit: http://www.evanblack.com/blog/touch-slide-to-unlock/
$('#slider')[0].addEventListener('touchmove', function(event) {
event.preventDefault();
var el = event.target;
var touch = event.touches[0];
curX = touch.pageX - this.offsetLeft - 73;
if(curX <= 0) return;
if(curX > 550){
$('#well').fadeOut();
}
el.style.webkitTransform = 'translateX(' + curX + 'px)';
}, false);
$('#slider')[0].addEventListener('touchend', function(event) {
this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
this.style.webkitTransform = 'translateX(0px)';
}, false);
}); | JavaScript |
window.onload = init;
var langElements = new Array();
function init() {
var els = document.getElementsByTagName( 'pre' );
var elsLen = els.length;
var pattern = new RegExp('(^|\\s)(cs|vb|mc|js)(\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
//els[i].style.background = "#fcc";
langElements[j] = els[i];
j++;
}
}
var lang = getCookie( "lang" );
if ( lang == null ) lang = "cs";
showLang(lang);
}
function getCookie(name) {
var cname = name + "=";
var dc = document.cookie;
if ( dc.length > 0 ) {
begin = dc.indexOf(cname);
if ( begin != -1 ) {
begin += cname.length;
end = dc.indexOf(";",begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end) );
}
}
}
function setCookie(name,value,expires) {
document.cookie = name + "=" + escape(value) + "; path=/" +
((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function showLang(lang) {
var pattern = new RegExp('(^|\\s)'+lang+'(\\s|$)');
var elsLen = langElements.length;
for (i = 0; i < elsLen; i++ )
{
var el = langElements[i];
if ( pattern.test( el.className ) )
el.style.display = "";
else
el.style.display = "none";
}
setCookie("lang",lang);
}
function Show( id ) {
document.getElementById(id).style.display = "";
}
function Hide( id ) {
document.getElementById(id).style.display = "none";
}
function ShowCS() {
showLang('cs');
}
function ShowVB() {
showLang('vb');
}
function ShowMC() {
showLang('mc');
}
function ShowJS() {
showLang('js');
}
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/css',
'text!dat/gui/saveDialogue.html',
'text!dat/gui/style.css',
'dat/controllers/factory',
'dat/controllers/Controller',
'dat/controllers/BooleanController',
'dat/controllers/FunctionController',
'dat/controllers/NumberControllerBox',
'dat/controllers/NumberControllerSlider',
'dat/controllers/OptionController',
'dat/controllers/ColorController',
'dat/utils/requestAnimationFrame',
'dat/dom/CenteredDiv',
'dat/dom/dom',
'dat/utils/common'
], function(css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) {
css.inject(styleSheet);
/** Outer-most className for GUI's */
var CSS_NAMESPACE = 'dg';
var HIDE_KEY_CODE = 72;
/** The only value shared between the JS and SCSS. Use caution. */
var CLOSE_BUTTON_HEIGHT = 20;
var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
var SUPPORTS_LOCAL_STORAGE = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
var SAVE_DIALOGUE;
/** Have we yet to create an autoPlace GUI? */
var auto_place_virgin = true;
/** Fixed position div that auto place GUI's go inside */
var auto_place_container;
/** Are we hiding the GUI's ? */
var hide = false;
/** GUI's which should be hidden */
var hideable_guis = [];
/**
* A lightweight controller library for JavaScript. It allows you to easily
* manipulate variables and fire functions on the fly.
* @class
*
* @member dat.gui
*
* @param {Object} [params]
* @param {String} [params.name] The name of this GUI.
* @param {Object} [params.load] JSON object representing the saved state of
* this GUI.
* @param {Boolean} [params.auto=true]
* @param {dat.gui.GUI} [params.parent] The GUI I'm nested in.
* @param {Boolean} [params.closed] If true, starts closed
*/
var GUI = function(params) {
var _this = this;
/**
* Outermost DOM Element
* @type DOMElement
*/
this.domElement = document.createElement('div');
this.__ul = document.createElement('ul');
this.domElement.appendChild(this.__ul);
dom.addClass(this.domElement, CSS_NAMESPACE);
/**
* Nested GUI's by name
* @ignore
*/
this.__folders = {};
this.__controllers = [];
/**
* List of objects I'm remembering for save, only used in top level GUI
* @ignore
*/
this.__rememberedObjects = [];
/**
* Maps the index of remembered objects to a map of controllers, only used
* in top level GUI.
*
* @private
* @ignore
*
* @example
* [
* {
* propertyName: Controller,
* anotherPropertyName: Controller
* },
* {
* propertyName: Controller
* }
* ]
*/
this.__rememberedObjectIndecesToControllers = [];
this.__listening = [];
params = params || {};
// Default parameters
params = common.defaults(params, {
autoPlace: true,
width: GUI.DEFAULT_WIDTH
});
params = common.defaults(params, {
resizable: params.autoPlace,
hideable: params.autoPlace
});
if (!common.isUndefined(params.load)) {
// Explicit preset
if (params.preset) params.load.preset = params.preset;
} else {
params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME };
}
if (common.isUndefined(params.parent) && params.hideable) {
hideable_guis.push(this);
}
// Only root level GUI's are resizable.
params.resizable = common.isUndefined(params.parent) && params.resizable;
if (params.autoPlace && common.isUndefined(params.scrollable)) {
params.scrollable = true;
}
// params.scrollable = common.isUndefined(params.parent) && params.scrollable === true;
// Not part of params because I don't want people passing this in via
// constructor. Should be a 'remembered' value.
var use_local_storage =
SUPPORTS_LOCAL_STORAGE &&
localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
Object.defineProperties(this,
/** @lends dat.gui.GUI.prototype */
{
/**
* The parent <code>GUI</code>
* @type dat.gui.GUI
*/
parent: {
get: function() {
return params.parent;
}
},
scrollable: {
get: function() {
return params.scrollable;
}
},
/**
* Handles <code>GUI</code>'s element placement for you
* @type Boolean
*/
autoPlace: {
get: function() {
return params.autoPlace;
}
},
/**
* The identifier for a set of saved values
* @type String
*/
preset: {
get: function() {
if (_this.parent) {
return _this.getRoot().preset;
} else {
return params.load.preset;
}
},
set: function(v) {
if (_this.parent) {
_this.getRoot().preset = v;
} else {
params.load.preset = v;
}
setPresetSelectIndex(this);
_this.revert();
}
},
/**
* The width of <code>GUI</code> element
* @type Number
*/
width: {
get: function() {
return params.width;
},
set: function(v) {
params.width = v;
setWidth(_this, v);
}
},
/**
* The name of <code>GUI</code>. Used for folders. i.e
* a folder's name
* @type String
*/
name: {
get: function() {
return params.name;
},
set: function(v) {
// TODO Check for collisions among sibling folders
params.name = v;
if (title_row_name) {
title_row_name.innerHTML = params.name;
}
}
},
/**
* Whether the <code>GUI</code> is collapsed or not
* @type Boolean
*/
closed: {
get: function() {
return params.closed;
},
set: function(v) {
params.closed = v;
if (params.closed) {
dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
} else {
dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
}
// For browsers that aren't going to respect the CSS transition,
// Lets just check our height against the window height right off
// the bat.
this.onResize();
if (_this.__closeButton) {
_this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
}
}
},
/**
* Contains all presets
* @type Object
*/
load: {
get: function() {
return params.load;
}
},
/**
* Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for
* <code>remember</code>ing
* @type Boolean
*/
useLocalStorage: {
get: function() {
return use_local_storage;
},
set: function(bool) {
if (SUPPORTS_LOCAL_STORAGE) {
use_local_storage = bool;
if (bool) {
dom.bind(window, 'unload', saveToLocalStorage);
} else {
dom.unbind(window, 'unload', saveToLocalStorage);
}
localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
}
}
}
});
// Are we a root level GUI?
if (common.isUndefined(params.parent)) {
params.closed = false;
dom.addClass(this.domElement, GUI.CLASS_MAIN);
dom.makeSelectable(this.domElement, false);
// Are we supposed to be loading locally?
if (SUPPORTS_LOCAL_STORAGE) {
if (use_local_storage) {
_this.useLocalStorage = true;
var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
if (saved_gui) {
params.load = JSON.parse(saved_gui);
}
}
}
this.__closeButton = document.createElement('div');
this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
this.domElement.appendChild(this.__closeButton);
dom.bind(this.__closeButton, 'click', function() {
_this.closed = !_this.closed;
});
// Oh, you're a nested GUI!
} else {
if (params.closed === undefined) {
params.closed = true;
}
var title_row_name = document.createTextNode(params.name);
dom.addClass(title_row_name, 'controller-name');
var title_row = addRow(_this, title_row_name);
var on_click_title = function(e) {
e.preventDefault();
_this.closed = !_this.closed;
return false;
};
dom.addClass(this.__ul, GUI.CLASS_CLOSED);
dom.addClass(title_row, 'title');
dom.bind(title_row, 'click', on_click_title);
if (!params.closed) {
this.closed = false;
}
}
if (params.autoPlace) {
if (common.isUndefined(params.parent)) {
if (auto_place_virgin) {
auto_place_container = document.createElement('div');
dom.addClass(auto_place_container, CSS_NAMESPACE);
dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER);
document.body.appendChild(auto_place_container);
auto_place_virgin = false;
}
// Put it in the dom for you.
auto_place_container.appendChild(this.domElement);
// Apply the auto styles
dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
}
// Make it not elastic.
if (!this.parent) setWidth(_this, params.width);
}
dom.bind(window, 'resize', function() { _this.onResize() });
dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); });
dom.bind(this.__ul, 'transitionend', function() { _this.onResize() });
dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() });
this.onResize();
if (params.resizable) {
addResizeHandle(this);
}
function saveToLocalStorage() {
localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
}
var root = _this.getRoot();
function resetWidth() {
var root = _this.getRoot();
root.width += 1;
common.defer(function() {
root.width -= 1;
});
}
if (!params.parent) {
resetWidth();
}
};
GUI.toggleHide = function() {
hide = !hide;
common.each(hideable_guis, function(gui) {
gui.domElement.style.zIndex = hide ? -999 : 999;
gui.domElement.style.opacity = hide ? 0 : 1;
});
};
GUI.CLASS_AUTO_PLACE = 'a';
GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
GUI.CLASS_MAIN = 'main';
GUI.CLASS_CONTROLLER_ROW = 'cr';
GUI.CLASS_TOO_TALL = 'taller-than-window';
GUI.CLASS_CLOSED = 'closed';
GUI.CLASS_CLOSE_BUTTON = 'close-button';
GUI.CLASS_DRAG = 'drag';
GUI.DEFAULT_WIDTH = 245;
GUI.TEXT_CLOSED = 'Close Controls';
GUI.TEXT_OPEN = 'Open Controls';
dom.bind(window, 'keydown', function(e) {
if (document.activeElement.type !== 'text' &&
(e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) {
GUI.toggleHide();
}
}, false);
common.extend(
GUI.prototype,
/** @lends dat.gui.GUI */
{
/**
* @param object
* @param property
* @returns {dat.controllers.Controller} The new controller that was added.
* @instance
*/
add: function(object, property) {
return add(
this,
object,
property,
{
factoryArgs: Array.prototype.slice.call(arguments, 2)
}
);
},
/**
* @param object
* @param property
* @returns {dat.controllers.ColorController} The new controller that was added.
* @instance
*/
addColor: function(object, property) {
return add(
this,
object,
property,
{
color: true
}
);
},
/**
* @param controller
* @instance
*/
remove: function(controller) {
// TODO listening?
this.__ul.removeChild(controller.__li);
this.__controllers.slice(this.__controllers.indexOf(controller), 1);
var _this = this;
common.defer(function() {
_this.onResize();
});
},
destroy: function() {
if (this.autoPlace) {
auto_place_container.removeChild(this.domElement);
}
},
/**
* @param name
* @returns {dat.gui.GUI} The new folder.
* @throws {Error} if this GUI already has a folder by the specified
* name
* @instance
*/
addFolder: function(name) {
// We have to prevent collisions on names in order to have a key
// by which to remember saved values
if (this.__folders[name] !== undefined) {
throw new Error('You already have a folder in this GUI by the' +
' name "' + name + '"');
}
var new_gui_params = { name: name, parent: this };
// We need to pass down the autoPlace trait so that we can
// attach event listeners to open/close folder actions to
// ensure that a scrollbar appears if the window is too short.
new_gui_params.autoPlace = this.autoPlace;
// Do we have saved appearance data for this folder?
if (this.load && // Anything loaded?
this.load.folders && // Was my parent a dead-end?
this.load.folders[name]) { // Did daddy remember me?
// Start me closed if I was closed
new_gui_params.closed = this.load.folders[name].closed;
// Pass down the loaded data
new_gui_params.load = this.load.folders[name];
}
var gui = new GUI(new_gui_params);
this.__folders[name] = gui;
var li = addRow(this, gui.domElement);
dom.addClass(li, 'folder');
return gui;
},
open: function() {
this.closed = false;
},
close: function() {
this.closed = true;
},
onResize: function() {
var root = this.getRoot();
if (root.scrollable) {
var top = dom.getOffset(root.__ul).top;
var h = 0;
common.each(root.__ul.childNodes, function(node) {
if (! (root.autoPlace && node === root.__save_row))
h += dom.getHeight(node);
});
if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
} else {
dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = 'auto';
}
}
if (root.__resize_handle) {
common.defer(function() {
root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
});
}
if (root.__closeButton) {
root.__closeButton.style.width = root.width + 'px';
}
},
/**
* Mark objects for saving. The order of these objects cannot change as
* the GUI grows. When remembering new objects, append them to the end
* of the list.
*
* @param {Object...} objects
* @throws {Error} if not called on a top level GUI.
* @instance
*/
remember: function() {
if (common.isUndefined(SAVE_DIALOGUE)) {
SAVE_DIALOGUE = new CenteredDiv();
SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents;
}
if (this.parent) {
throw new Error("You can only call remember on a top level GUI.");
}
var _this = this;
common.each(Array.prototype.slice.call(arguments), function(object) {
if (_this.__rememberedObjects.length == 0) {
addSaveMenu(_this);
}
if (_this.__rememberedObjects.indexOf(object) == -1) {
_this.__rememberedObjects.push(object);
}
});
if (this.autoPlace) {
// Set save row width
setWidth(this, this.width);
}
},
/**
* @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI.
* @instance
*/
getRoot: function() {
var gui = this;
while (gui.parent) {
gui = gui.parent;
}
return gui;
},
/**
* @returns {Object} a JSON object representing the current state of
* this GUI as well as its remembered properties.
* @instance
*/
getSaveObject: function() {
var toReturn = this.load;
toReturn.closed = this.closed;
// Am I remembering any values?
if (this.__rememberedObjects.length > 0) {
toReturn.preset = this.preset;
if (!toReturn.remembered) {
toReturn.remembered = {};
}
toReturn.remembered[this.preset] = getCurrentPreset(this);
}
toReturn.folders = {};
common.each(this.__folders, function(element, key) {
toReturn.folders[key] = element.getSaveObject();
});
return toReturn;
},
save: function() {
if (!this.load.remembered) {
this.load.remembered = {};
}
this.load.remembered[this.preset] = getCurrentPreset(this);
markPresetModified(this, false);
},
saveAs: function(presetName) {
if (!this.load.remembered) {
// Retain default values upon first save
this.load.remembered = {};
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
}
this.load.remembered[presetName] = getCurrentPreset(this);
this.preset = presetName;
addPresetOption(this, presetName, true);
},
revert: function(gui) {
common.each(this.__controllers, function(controller) {
// Make revert work on Default.
if (!this.getRoot().load.remembered) {
controller.setValue(controller.initialValue);
} else {
recallSavedValue(gui || this.getRoot(), controller);
}
}, this);
common.each(this.__folders, function(folder) {
folder.revert(folder);
});
if (!gui) {
markPresetModified(this.getRoot(), false);
}
},
listen: function(controller) {
var init = this.__listening.length == 0;
this.__listening.push(controller);
if (init) updateDisplays(this.__listening);
}
}
);
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error("Object " + object + " has no property \"" + property + "\"");
}
var controller;
if (params.color) {
controller = new ColorController(object, property);
} else {
var factoryArgs = [object,property].concat(params.factoryArgs);
controller = controllerFactory.apply(gui, factoryArgs);
}
if (params.before instanceof Controller) {
params.before = params.before.__li;
}
recallSavedValue(gui, controller);
dom.addClass(controller.domElement, 'c');
var name = document.createElement('span');
dom.addClass(name, 'property-name');
name.innerHTML = controller.property;
var container = document.createElement('div');
container.appendChild(name);
container.appendChild(controller.domElement);
var li = addRow(gui, container, params.before);
dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
dom.addClass(li, typeof controller.getValue());
augmentController(gui, li, controller);
gui.__controllers.push(controller);
return controller;
}
/**
* Add a row to the end of the GUI or before another row.
*
* @param gui
* @param [dom] If specified, inserts the dom content in the new row
* @param [liBefore] If specified, places the new row before another row
*/
function addRow(gui, dom, liBefore) {
var li = document.createElement('li');
if (dom) li.appendChild(dom);
if (liBefore) {
gui.__ul.insertBefore(li, params.before);
} else {
gui.__ul.appendChild(li);
}
gui.onResize();
return li;
}
function augmentController(gui, li, controller) {
controller.__li = li;
controller.__gui = gui;
common.extend(controller, {
options: function(options) {
if (arguments.length > 1) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [common.toArray(arguments)]
}
);
}
if (common.isArray(options) || common.isObject(options)) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [options]
}
);
}
},
name: function(v) {
controller.__li.firstElementChild.firstElementChild.innerHTML = v;
return controller;
},
listen: function() {
controller.__gui.listen(controller);
return controller;
},
remove: function() {
controller.__gui.remove(controller);
return controller;
}
});
// All sliders should be accompanied by a box.
if (controller instanceof NumberControllerSlider) {
var box = new NumberControllerBox(controller.object, controller.property,
{ min: controller.__min, max: controller.__max, step: controller.__step });
common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) {
var pc = controller[method];
var pb = box[method];
controller[method] = box[method] = function() {
var args = Array.prototype.slice.call(arguments);
pc.apply(controller, args);
return pb.apply(box, args);
}
});
dom.addClass(li, 'has-slider');
controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
}
else if (controller instanceof NumberControllerBox) {
var r = function(returned) {
// Have we defined both boundaries?
if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) {
// Well, then lets just replace this with a slider.
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [controller.__min, controller.__max, controller.__step]
});
}
return returned;
};
controller.min = common.compose(r, controller.min);
controller.max = common.compose(r, controller.max);
}
else if (controller instanceof BooleanController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__checkbox, 'click');
});
dom.bind(controller.__checkbox, 'click', function(e) {
e.stopPropagation(); // Prevents double-toggle
})
}
else if (controller instanceof FunctionController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__button, 'click');
});
dom.bind(li, 'mouseover', function() {
dom.addClass(controller.__button, 'hover');
});
dom.bind(li, 'mouseout', function() {
dom.removeClass(controller.__button, 'hover');
});
}
else if (controller instanceof ColorController) {
dom.addClass(li, 'color');
controller.updateDisplay = common.compose(function(r) {
li.style.borderLeftColor = controller.__color.toString();
return r;
}, controller.updateDisplay);
controller.updateDisplay();
}
controller.setValue = common.compose(function(r) {
if (gui.getRoot().__preset_select && controller.isModified()) {
markPresetModified(gui.getRoot(), true);
}
return r;
}, controller.setValue);
}
function recallSavedValue(gui, controller) {
// Find the topmost GUI, that's where remembered objects live.
var root = gui.getRoot();
// Does the object we're controlling match anything we've been told to
// remember?
var matched_index = root.__rememberedObjects.indexOf(controller.object);
// Why yes, it does!
if (matched_index != -1) {
// Let me fetch a map of controllers for thcommon.isObject.
var controller_map =
root.__rememberedObjectIndecesToControllers[matched_index];
// Ohp, I believe this is the first controller we've created for this
// object. Lets make the map fresh.
if (controller_map === undefined) {
controller_map = {};
root.__rememberedObjectIndecesToControllers[matched_index] =
controller_map;
}
// Keep track of this controller
controller_map[controller.property] = controller;
// Okay, now have we saved any values for this controller?
if (root.load && root.load.remembered) {
var preset_map = root.load.remembered;
// Which preset are we trying to load?
var preset;
if (preset_map[gui.preset]) {
preset = preset_map[gui.preset];
} else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) {
// Uhh, you can have the default instead?
preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME];
} else {
// Nada.
return;
}
// Did the loaded object remember thcommon.isObject?
if (preset[matched_index] &&
// Did we remember this particular property?
preset[matched_index][controller.property] !== undefined) {
// We did remember something for this guy ...
var value = preset[matched_index][controller.property];
// And that's what it is.
controller.initialValue = value;
controller.setValue(value);
}
}
}
}
function getLocalStorageHash(gui, key) {
// TODO how does this deal with multiple GUI's?
return document.location.href + '.' + key;
}
function addSaveMenu(gui) {
var div = gui.__save_row = document.createElement('li');
dom.addClass(gui.domElement, 'has-save');
gui.__ul.insertBefore(div, gui.__ul.firstChild);
dom.addClass(div, 'save-row');
var gears = document.createElement('span');
gears.innerHTML = ' ';
dom.addClass(gears, 'button gears');
// TODO replace with FunctionController
var button = document.createElement('span');
button.innerHTML = 'Save';
dom.addClass(button, 'button');
dom.addClass(button, 'save');
var button2 = document.createElement('span');
button2.innerHTML = 'New';
dom.addClass(button2, 'button');
dom.addClass(button2, 'save-as');
var button3 = document.createElement('span');
button3.innerHTML = 'Revert';
dom.addClass(button3, 'button');
dom.addClass(button3, 'revert');
var select = gui.__preset_select = document.createElement('select');
if (gui.load && gui.load.remembered) {
common.each(gui.load.remembered, function(value, key) {
addPresetOption(gui, key, key == gui.preset);
});
} else {
addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
}
dom.bind(select, 'change', function() {
for (var index = 0; index < gui.__preset_select.length; index++) {
gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
}
gui.preset = this.value;
});
div.appendChild(select);
div.appendChild(gears);
div.appendChild(button);
div.appendChild(button2);
div.appendChild(button3);
if (SUPPORTS_LOCAL_STORAGE) {
var saveLocally = document.getElementById('dg-save-locally');
var explain = document.getElementById('dg-local-explain');
saveLocally.style.display = 'block';
var localStorageCheckBox = document.getElementById('dg-local-storage');
if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
localStorageCheckBox.setAttribute('checked', 'checked');
}
function showHideExplain() {
explain.style.display = gui.useLocalStorage ? 'block' : 'none';
}
showHideExplain();
// TODO: Use a boolean controller, fool!
dom.bind(localStorageCheckBox, 'change', function() {
gui.useLocalStorage = !gui.useLocalStorage;
showHideExplain();
});
}
var newConstructorTextArea = document.getElementById('dg-new-constructor');
dom.bind(newConstructorTextArea, 'keydown', function(e) {
if (e.metaKey && (e.which === 67 || e.keyCode == 67)) {
SAVE_DIALOGUE.hide();
}
});
dom.bind(gears, 'click', function() {
newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
SAVE_DIALOGUE.show();
newConstructorTextArea.focus();
newConstructorTextArea.select();
});
dom.bind(button, 'click', function() {
gui.save();
});
dom.bind(button2, 'click', function() {
var presetName = prompt('Enter a new preset name.');
if (presetName) gui.saveAs(presetName);
});
dom.bind(button3, 'click', function() {
gui.revert();
});
// div.appendChild(button2);
}
function addResizeHandle(gui) {
gui.__resize_handle = document.createElement('div');
common.extend(gui.__resize_handle.style, {
width: '6px',
marginLeft: '-3px',
height: '200px',
cursor: 'ew-resize',
position: 'absolute'
// border: '1px solid blue'
});
var pmouseX;
dom.bind(gui.__resize_handle, 'mousedown', dragStart);
dom.bind(gui.__closeButton, 'mousedown', dragStart);
gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
function dragStart(e) {
e.preventDefault();
pmouseX = e.clientX;
dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.bind(window, 'mousemove', drag);
dom.bind(window, 'mouseup', dragStop);
return false;
}
function drag(e) {
e.preventDefault();
gui.width += pmouseX - e.clientX;
gui.onResize();
pmouseX = e.clientX;
return false;
}
function dragStop() {
dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.unbind(window, 'mousemove', drag);
dom.unbind(window, 'mouseup', dragStop);
}
}
function setWidth(gui, w) {
gui.domElement.style.width = w + 'px';
// Auto placed save-rows are position fixed, so we have to
// set the width manually if we want it to bleed to the edge
if (gui.__save_row && gui.autoPlace) {
gui.__save_row.style.width = w + 'px';
}if (gui.__closeButton) {
gui.__closeButton.style.width = w + 'px';
}
}
function getCurrentPreset(gui, useInitialValues) {
var toReturn = {};
// For each object I'm remembering
common.each(gui.__rememberedObjects, function(val, index) {
var saved_values = {};
// The controllers I've made for thcommon.isObject by property
var controller_map =
gui.__rememberedObjectIndecesToControllers[index];
// Remember each value for each property
common.each(controller_map, function(controller, property) {
saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue();
});
// Save the values for thcommon.isObject
toReturn[index] = saved_values;
});
return toReturn;
}
function addPresetOption(gui, name, setSelected) {
var opt = document.createElement('option');
opt.innerHTML = name;
opt.value = name;
gui.__preset_select.appendChild(opt);
if (setSelected) {
gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
}
}
function setPresetSelectIndex(gui) {
for (var index = 0; index < gui.__preset_select.length; index++) {
if (gui.__preset_select[index].value == gui.preset) {
gui.__preset_select.selectedIndex = index;
}
}
}
function markPresetModified(gui, modified) {
var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
// console.log('mark', modified, opt);
if (modified) {
opt.innerHTML = opt.value + "*";
} else {
opt.innerHTML = opt.value;
}
}
function updateDisplays(controllerArray) {
if (controllerArray.length != 0) {
requestAnimationFrame(function() {
updateDisplays(controllerArray);
});
}
common.each(controllerArray, function(c) {
c.updateDisplay();
});
}
return GUI;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a GUI interface to fire a specified method, a property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var FunctionController = function(object, property, text) {
FunctionController.superclass.call(this, object, property);
var _this = this;
this.__button = document.createElement('div');
this.__button.innerHTML = text === undefined ? 'Fire' : text;
dom.bind(this.__button, 'click', function(e) {
e.preventDefault();
_this.fire();
return false;
});
dom.addClass(this.__button, 'button');
this.domElement.appendChild(this.__button);
};
FunctionController.superclass = Controller;
common.extend(
FunctionController.prototype,
Controller.prototype,
{
fire: function() {
if (this.__onChange) {
this.__onChange.call(this);
}
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.getValue().call(this.object);
}
}
);
return FunctionController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/utils/common'
], function(Controller, common) {
/**
* @class Represents a given property of an object that is a number.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberController = function(object, property, params) {
NumberController.superclass.call(this, object, property);
params = params || {};
this.__min = params.min;
this.__max = params.max;
this.__step = params.step;
if (common.isUndefined(this.__step)) {
if (this.initialValue == 0) {
this.__impliedStep = 1; // What are we, psychics?
} else {
// Hey Doug, check this out.
this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10;
}
} else {
this.__impliedStep = this.__step;
}
this.__precision = numDecimals(this.__impliedStep);
};
NumberController.superclass = Controller;
common.extend(
NumberController.prototype,
Controller.prototype,
/** @lends dat.controllers.NumberController.prototype */
{
setValue: function(v) {
if (this.__min !== undefined && v < this.__min) {
v = this.__min;
} else if (this.__max !== undefined && v > this.__max) {
v = this.__max;
}
if (this.__step !== undefined && v % this.__step != 0) {
v = Math.round(v / this.__step) * this.__step;
}
return NumberController.superclass.prototype.setValue.call(this, v);
},
/**
* Specify a minimum value for <code>object[property]</code>.
*
* @param {Number} minValue The minimum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
min: function(v) {
this.__min = v;
return this;
},
/**
* Specify a maximum value for <code>object[property]</code>.
*
* @param {Number} maxValue The maximum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
max: function(v) {
this.__max = v;
return this;
},
/**
* Specify a step value that dat.controllers.NumberController
* increments by.
*
* @param {Number} stepValue The step value for
* dat.controllers.NumberController
* @default if minimum and maximum specified increment is 1% of the
* difference otherwise stepValue is 1
* @returns {dat.controllers.NumberController} this
*/
step: function(v) {
this.__step = v;
return this;
}
}
);
function numDecimals(x) {
x = x.toString();
if (x.indexOf('.') > -1) {
return x.length - x.indexOf('.') - 1;
} else {
return 0;
}
}
return NumberController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a text input to alter the string property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var StringController = function(object, property) {
StringController.superclass.call(this, object, property);
var _this = this;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
dom.bind(this.__input, 'keyup', onChange);
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) {
this.blur();
}
});
function onChange() {
_this.setValue(_this.__input.value);
}
function onBlur() {
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
StringController.superclass = Controller;
common.extend(
StringController.prototype,
Controller.prototype,
{
updateDisplay: function() {
// Stops the caret from moving on account of:
// keyup -> setValue -> updateDisplay
if (!dom.isActive(this.__input)) {
this.__input.value = this.getValue();
}
return StringController.superclass.prototype.updateDisplay.call(this);
}
}
);
return StringController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
/**
* @class An "abstract" class that represents a given property of an object.
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var Controller = function(object, property) {
this.initialValue = object[property];
/**
* Those who extend this class will put their DOM elements in here.
* @type {DOMElement}
*/
this.domElement = document.createElement('div');
/**
* The object to manipulate
* @type {Object}
*/
this.object = object;
/**
* The name of the property to manipulate
* @type {String}
*/
this.property = property;
/**
* The function to be called on change.
* @type {Function}
* @ignore
*/
this.__onChange = undefined;
/**
* The function to be called on finishing change.
* @type {Function}
* @ignore
*/
this.__onFinishChange = undefined;
};
common.extend(
Controller.prototype,
/** @lends dat.controllers.Controller.prototype */
{
/**
* Specify that a function fire every time someone changes the value with
* this Controller.
*
* @param {Function} fnc This function will be called whenever the value
* is modified via this Controller.
* @returns {dat.controllers.Controller} this
*/
onChange: function(fnc) {
this.__onChange = fnc;
return this;
},
/**
* Specify that a function fire every time someone "finishes" changing
* the value wih this Controller. Useful for values that change
* incrementally like numbers or strings.
*
* @param {Function} fnc This function will be called whenever
* someone "finishes" changing the value via this Controller.
* @returns {dat.controllers.Controller} this
*/
onFinishChange: function(fnc) {
this.__onFinishChange = fnc;
return this;
},
/**
* Change the value of <code>object[property]</code>
*
* @param {Object} newValue The new value of <code>object[property]</code>
*/
setValue: function(newValue) {
this.object[this.property] = newValue;
if (this.__onChange) {
this.__onChange.call(this, newValue);
}
this.updateDisplay();
return this;
},
/**
* Gets the value of <code>object[property]</code>
*
* @returns {Object} The current value of <code>object[property]</code>
*/
getValue: function() {
return this.object[this.property];
},
/**
* Refreshes the visual display of a Controller in order to keep sync
* with the object's current value.
* @returns {dat.controllers.Controller} this
*/
updateDisplay: function() {
return this;
},
/**
* @returns {Boolean} true if the value has deviated from initialValue
*/
isModified: function() {
return this.initialValue !== this.getValue()
}
}
);
return Controller;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/NumberController',
'dat/dom/dom',
'dat/utils/common'
], function(NumberController, dom, common) {
/**
* @class Represents a given property of an object that is a number and
* provides an input element with which to manipulate it.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerBox = function(object, property, params) {
this.__truncationSuspended = false;
NumberControllerBox.superclass.call(this, object, property, params);
var _this = this;
/**
* {Number} Previous mouse y position
* @ignore
*/
var prev_y;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
// Makes it so manually specified values are not truncated.
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'mousedown', onMouseDown);
dom.bind(this.__input, 'keydown', function(e) {
// When pressing entire, you can be as precise as you want.
if (e.keyCode === 13) {
_this.__truncationSuspended = true;
this.blur();
_this.__truncationSuspended = false;
}
});
function onChange() {
var attempted = parseFloat(_this.__input.value);
if (!common.isNaN(attempted)) _this.setValue(attempted);
}
function onBlur() {
onChange();
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
prev_y = e.clientY;
}
function onMouseDrag(e) {
var diff = prev_y - e.clientY;
_this.setValue(_this.getValue() + diff * _this.__impliedStep);
prev_y = e.clientY;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
NumberControllerBox.superclass = NumberController;
common.extend(
NumberControllerBox.prototype,
NumberController.prototype,
{
updateDisplay: function() {
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
return NumberControllerBox.superclass.prototype.updateDisplay.call(this);
}
}
);
function roundToDecimal(value, decimals) {
var tenTo = Math.pow(10, decimals);
return Math.round(value * tenTo) / tenTo;
}
return NumberControllerBox;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
],
function(Controller, dom, common) {
/**
* @class Provides a select input to alter the property of an object, using a
* list of accepted values.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object|string[]} options A map of labels to acceptable values, or
* a list of acceptable string values.
*
* @member dat.controllers
*/
var OptionController = function(object, property, options) {
OptionController.superclass.call(this, object, property);
var _this = this;
/**
* The drop down menu
* @ignore
*/
this.__select = document.createElement('select');
if (common.isArray(options)) {
var map = {};
common.each(options, function(element) {
map[element] = element;
});
options = map;
}
common.each(options, function(value, key) {
var opt = document.createElement('option');
opt.innerHTML = key;
opt.setAttribute('value', value);
_this.__select.appendChild(opt);
});
// Acknowledge original value
this.updateDisplay();
dom.bind(this.__select, 'change', function() {
var desiredValue = this.options[this.selectedIndex].value;
_this.setValue(desiredValue);
});
this.domElement.appendChild(this.__select);
};
OptionController.superclass = Controller;
common.extend(
OptionController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = OptionController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
return toReturn;
},
updateDisplay: function() {
this.__select.value = this.getValue();
return OptionController.superclass.prototype.updateDisplay.call(this);
}
}
);
return OptionController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/color/Color',
'dat/color/interpret',
'dat/utils/common'
], function(Controller, dom, Color, interpret, common) {
var ColorController = function(object, property) {
ColorController.superclass.call(this, object, property);
this.__color = new Color(this.getValue());
this.__temp = new Color(0);
var _this = this;
this.domElement = document.createElement('div');
dom.makeSelectable(this.domElement, false);
this.__selector = document.createElement('div');
this.__selector.className = 'selector';
this.__saturation_field = document.createElement('div');
this.__saturation_field.className = 'saturation-field';
this.__field_knob = document.createElement('div');
this.__field_knob.className = 'field-knob';
this.__field_knob_border = '2px solid ';
this.__hue_knob = document.createElement('div');
this.__hue_knob.className = 'hue-knob';
this.__hue_field = document.createElement('div');
this.__hue_field.className = 'hue-field';
this.__input = document.createElement('input');
this.__input.type = 'text';
this.__input_textShadow = '0 1px 1px ';
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) { // on enter
onBlur.call(this);
}
});
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__selector, 'mousedown', function(e) {
dom
.addClass(this, 'drag')
.bind(window, 'mouseup', function(e) {
dom.removeClass(_this.__selector, 'drag');
});
});
var value_field = document.createElement('div');
common.extend(this.__selector.style, {
width: '122px',
height: '102px',
padding: '3px',
backgroundColor: '#222',
boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
});
common.extend(this.__field_knob.style, {
position: 'absolute',
width: '12px',
height: '12px',
border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'),
boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
borderRadius: '12px',
zIndex: 1
});
common.extend(this.__hue_knob.style, {
position: 'absolute',
width: '15px',
height: '2px',
borderRight: '4px solid #fff',
zIndex: 1
});
common.extend(this.__saturation_field.style, {
width: '100px',
height: '100px',
border: '1px solid #555',
marginRight: '3px',
display: 'inline-block',
cursor: 'pointer'
});
common.extend(value_field.style, {
width: '100%',
height: '100%',
background: 'none'
});
linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000');
common.extend(this.__hue_field.style, {
width: '15px',
height: '100px',
display: 'inline-block',
border: '1px solid #555',
cursor: 'ns-resize'
});
hueGradient(this.__hue_field);
common.extend(this.__input.style, {
outline: 'none',
// width: '120px',
textAlign: 'center',
// padding: '4px',
// marginBottom: '6px',
color: '#fff',
border: 0,
fontWeight: 'bold',
textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
});
dom.bind(this.__saturation_field, 'mousedown', fieldDown);
dom.bind(this.__field_knob, 'mousedown', fieldDown);
dom.bind(this.__hue_field, 'mousedown', function(e) {
setH(e);
dom.bind(window, 'mousemove', setH);
dom.bind(window, 'mouseup', unbindH);
});
function fieldDown(e) {
setSV(e);
// document.body.style.cursor = 'none';
dom.bind(window, 'mousemove', setSV);
dom.bind(window, 'mouseup', unbindSV);
}
function unbindSV() {
dom.unbind(window, 'mousemove', setSV);
dom.unbind(window, 'mouseup', unbindSV);
// document.body.style.cursor = 'default';
}
function onBlur() {
var i = interpret(this.value);
if (i !== false) {
_this.__color.__state = i;
_this.setValue(_this.__color.toOriginal());
} else {
this.value = _this.__color.toString();
}
}
function unbindH() {
dom.unbind(window, 'mousemove', setH);
dom.unbind(window, 'mouseup', unbindH);
}
this.__saturation_field.appendChild(value_field);
this.__selector.appendChild(this.__field_knob);
this.__selector.appendChild(this.__saturation_field);
this.__selector.appendChild(this.__hue_field);
this.__hue_field.appendChild(this.__hue_knob);
this.domElement.appendChild(this.__input);
this.domElement.appendChild(this.__selector);
this.updateDisplay();
function setSV(e) {
e.preventDefault();
var w = dom.getWidth(_this.__saturation_field);
var o = dom.getOffset(_this.__saturation_field);
var s = (e.clientX - o.left + document.body.scrollLeft) / w;
var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;
if (v > 1) v = 1;
else if (v < 0) v = 0;
if (s > 1) s = 1;
else if (s < 0) s = 0;
_this.__color.v = v;
_this.__color.s = s;
_this.setValue(_this.__color.toOriginal());
return false;
}
function setH(e) {
e.preventDefault();
var s = dom.getHeight(_this.__hue_field);
var o = dom.getOffset(_this.__hue_field);
var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;
if (h > 1) h = 1;
else if (h < 0) h = 0;
_this.__color.h = h * 360;
_this.setValue(_this.__color.toOriginal());
return false;
}
};
ColorController.superclass = Controller;
common.extend(
ColorController.prototype,
Controller.prototype,
{
updateDisplay: function() {
var i = interpret(this.getValue());
if (i !== false) {
var mismatch = false;
// Check for mismatch on the interpreted value.
common.each(Color.COMPONENTS, function(component) {
if (!common.isUndefined(i[component]) &&
!common.isUndefined(this.__color.__state[component]) &&
i[component] !== this.__color.__state[component]) {
mismatch = true;
return {}; // break
}
}, this);
// If nothing diverges, we keep our previous values
// for statefulness, otherwise we recalculate fresh
if (mismatch) {
common.extend(this.__color.__state, i);
}
}
common.extend(this.__temp.__state, this.__color.__state);
this.__temp.a = 1;
var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0;
var _flip = 255 - flip;
common.extend(this.__field_knob.style, {
marginLeft: 100 * this.__color.s - 7 + 'px',
marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
backgroundColor: this.__temp.toString(),
border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')'
});
this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'
this.__temp.s = 1;
this.__temp.v = 1;
linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());
common.extend(this.__input.style, {
backgroundColor: this.__input.value = this.__color.toString(),
color: 'rgb(' + flip + ',' + flip + ',' + flip +')',
textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)'
});
}
}
);
var vendors = ['-moz-','-o-','-webkit-','-ms-',''];
function linearGradient(elem, x, a, b) {
elem.style.background = '';
common.each(vendors, function(vendor) {
elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); ';
});
}
function hueGradient(elem) {
elem.style.background = '';
elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'
elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
}
return ColorController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a checkbox input to alter the boolean property of an object.
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var BooleanController = function(object, property) {
BooleanController.superclass.call(this, object, property);
var _this = this;
this.__prev = this.getValue();
this.__checkbox = document.createElement('input');
this.__checkbox.setAttribute('type', 'checkbox');
dom.bind(this.__checkbox, 'change', onChange, false);
this.domElement.appendChild(this.__checkbox);
// Match original value
this.updateDisplay();
function onChange() {
_this.setValue(!_this.__prev);
}
};
BooleanController.superclass = Controller;
common.extend(
BooleanController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = BooleanController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.__prev = this.getValue();
return toReturn;
},
updateDisplay: function() {
if (this.getValue() === true) {
this.__checkbox.setAttribute('checked', 'checked');
this.__checkbox.checked = true;
} else {
this.__checkbox.checked = false;
}
return BooleanController.superclass.prototype.updateDisplay.call(this);
}
}
);
return BooleanController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/OptionController',
'dat/controllers/NumberControllerBox',
'dat/controllers/NumberControllerSlider',
'dat/controllers/StringController',
'dat/controllers/FunctionController',
'dat/controllers/BooleanController',
'dat/utils/common'
],
function(OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {
return function(object, property) {
var initialValue = object[property];
// Providing options?
if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
return new OptionController(object, property, arguments[2]);
}
// Providing a map?
if (common.isNumber(initialValue)) {
if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {
// Has min and max.
return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
} else {
return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });
}
}
if (common.isString(initialValue)) {
return new StringController(object, property);
}
if (common.isFunction(initialValue)) {
return new FunctionController(object, property, '');
}
if (common.isBoolean(initialValue)) {
return new BooleanController(object, property);
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/NumberController',
'dat/dom/dom',
'dat/utils/css',
'dat/utils/common',
'text!dat/controllers/NumberControllerSlider.css'
],
function(NumberController, dom, css, common, styleSheet) {
/**
* @class Represents a given property of an object that is a number, contains
* a minimum and maximum, and provides a slider element with which to
* manipulate it. It should be noted that the slider element is made up of
* <code><div></code> tags, <strong>not</strong> the html5
* <code><slider></code> element.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Number} minValue Minimum allowed value
* @param {Number} maxValue Maximum allowed value
* @param {Number} stepValue Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerSlider = function(object, property, min, max, step) {
NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step });
var _this = this;
this.__background = document.createElement('div');
this.__foreground = document.createElement('div');
dom.bind(this.__background, 'mousedown', onMouseDown);
dom.addClass(this.__background, 'slider');
dom.addClass(this.__foreground, 'slider-fg');
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
onMouseDrag(e);
}
function onMouseDrag(e) {
e.preventDefault();
var offset = dom.getOffset(_this.__background);
var width = dom.getWidth(_this.__background);
_this.setValue(
map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max)
);
return false;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.__background.appendChild(this.__foreground);
this.domElement.appendChild(this.__background);
};
NumberControllerSlider.superclass = NumberController;
/**
* Injects default stylesheet for slider elements.
*/
NumberControllerSlider.useDefaultStyles = function() {
css.inject(styleSheet);
};
common.extend(
NumberControllerSlider.prototype,
NumberController.prototype,
{
updateDisplay: function() {
var pct = (this.getValue() - this.__min)/(this.__max - this.__min);
this.__foreground.style.width = pct*100+'%';
return NumberControllerSlider.superclass.prototype.updateDisplay.call(this);
}
}
);
function map(v, i1, i2, o1, o2) {
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
}
return NumberControllerSlider;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/dom/dom',
'dat/utils/common'
], function(dom, common) {
var CenteredDiv = function() {
this.backgroundElement = document.createElement('div');
common.extend(this.backgroundElement.style, {
backgroundColor: 'rgba(0,0,0,0.8)',
top: 0,
left: 0,
display: 'none',
zIndex: '1000',
opacity: 0,
WebkitTransition: 'opacity 0.2s linear'
});
dom.makeFullscreen(this.backgroundElement);
this.backgroundElement.style.position = 'fixed';
this.domElement = document.createElement('div');
common.extend(this.domElement.style, {
position: 'fixed',
display: 'none',
zIndex: '1001',
opacity: 0,
WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear'
});
document.body.appendChild(this.backgroundElement);
document.body.appendChild(this.domElement);
var _this = this;
dom.bind(this.backgroundElement, 'click', function() {
_this.hide();
});
};
CenteredDiv.prototype.show = function() {
var _this = this;
this.backgroundElement.style.display = 'block';
this.domElement.style.display = 'block';
this.domElement.style.opacity = 0;
// this.domElement.style.top = '52%';
this.domElement.style.webkitTransform = 'scale(1.1)';
this.layout();
common.defer(function() {
_this.backgroundElement.style.opacity = 1;
_this.domElement.style.opacity = 1;
_this.domElement.style.webkitTransform = 'scale(1)';
});
};
CenteredDiv.prototype.hide = function() {
var _this = this;
var hide = function() {
_this.domElement.style.display = 'none';
_this.backgroundElement.style.display = 'none';
dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
dom.unbind(_this.domElement, 'transitionend', hide);
dom.unbind(_this.domElement, 'oTransitionEnd', hide);
};
dom.bind(this.domElement, 'webkitTransitionEnd', hide);
dom.bind(this.domElement, 'transitionend', hide);
dom.bind(this.domElement, 'oTransitionEnd', hide);
this.backgroundElement.style.opacity = 0;
// this.domElement.style.top = '48%';
this.domElement.style.opacity = 0;
this.domElement.style.webkitTransform = 'scale(1.1)';
};
CenteredDiv.prototype.layout = function() {
this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px';
this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px';
};
function lockScroll(e) {
console.log(e);
}
return CenteredDiv;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
var EVENT_MAP = {
'HTMLEvents': ['change'],
'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'],
'KeyboardEvents': ['keydown']
};
var EVENT_MAP_INV = {};
common.each(EVENT_MAP, function(v, k) {
common.each(v, function(e) {
EVENT_MAP_INV[e] = k;
});
});
var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
function cssValueToPixels(val) {
if (val === '0' || common.isUndefined(val)) return 0;
var match = val.match(CSS_VALUE_PIXELS);
if (!common.isNull(match)) {
return parseFloat(match[1]);
}
// TODO ...ems? %?
return 0;
}
/**
* @namespace
* @member dat.dom
*/
var dom = {
/**
*
* @param elem
* @param selectable
*/
makeSelectable: function(elem, selectable) {
if (elem === undefined || elem.style === undefined) return;
elem.onselectstart = selectable ? function() {
return false;
} : function() {
};
elem.style.MozUserSelect = selectable ? 'auto' : 'none';
elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
elem.unselectable = selectable ? 'on' : 'off';
},
/**
*
* @param elem
* @param horizontal
* @param vertical
*/
makeFullscreen: function(elem, horizontal, vertical) {
if (common.isUndefined(horizontal)) horizontal = true;
if (common.isUndefined(vertical)) vertical = true;
elem.style.position = 'absolute';
if (horizontal) {
elem.style.left = 0;
elem.style.right = 0;
}
if (vertical) {
elem.style.top = 0;
elem.style.bottom = 0;
}
},
/**
*
* @param elem
* @param eventType
* @param params
*/
fakeEvent: function(elem, eventType, params, aux) {
params = params || {};
var className = EVENT_MAP_INV[eventType];
if (!className) {
throw new Error('Event type ' + eventType + ' not supported.');
}
var evt = document.createEvent(className);
switch (className) {
case 'MouseEvents':
var clientX = params.x || params.clientX || 0;
var clientY = params.y || params.clientY || 0;
evt.initMouseEvent(eventType, params.bubbles || false,
params.cancelable || true, window, params.clickCount || 1,
0, //screen X
0, //screen Y
clientX, //client X
clientY, //client Y
false, false, false, false, 0, null);
break;
case 'KeyboardEvents':
var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz
common.defaults(params, {
cancelable: true,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: undefined,
charCode: undefined
});
init(eventType, params.bubbles || false,
params.cancelable, window,
params.ctrlKey, params.altKey,
params.shiftKey, params.metaKey,
params.keyCode, params.charCode);
break;
default:
evt.initEvent(eventType, params.bubbles || false,
params.cancelable || true);
break;
}
common.defaults(evt, aux);
elem.dispatchEvent(evt);
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
bind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.addEventListener)
elem.addEventListener(event, func, bool);
else if (elem.attachEvent)
elem.attachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
unbind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.removeEventListener)
elem.removeEventListener(event, func, bool);
else if (elem.detachEvent)
elem.detachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param className
*/
addClass: function(elem, className) {
if (elem.className === undefined) {
elem.className = className;
} else if (elem.className !== className) {
var classes = elem.className.split(/ +/);
if (classes.indexOf(className) == -1) {
classes.push(className);
elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
}
}
return dom;
},
/**
*
* @param elem
* @param className
*/
removeClass: function(elem, className) {
if (className) {
if (elem.className === undefined) {
// elem.className = className;
} else if (elem.className === className) {
elem.removeAttribute('class');
} else {
var classes = elem.className.split(/ +/);
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1);
elem.className = classes.join(' ');
}
}
} else {
elem.className = undefined;
}
return dom;
},
hasClass: function(elem, className) {
return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
},
/**
*
* @param elem
*/
getWidth: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-left-width']) +
cssValueToPixels(style['border-right-width']) +
cssValueToPixels(style['padding-left']) +
cssValueToPixels(style['padding-right']) +
cssValueToPixels(style['width']);
},
/**
*
* @param elem
*/
getHeight: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-top-width']) +
cssValueToPixels(style['border-bottom-width']) +
cssValueToPixels(style['padding-top']) +
cssValueToPixels(style['padding-bottom']) +
cssValueToPixels(style['height']);
},
/**
*
* @param elem
*/
getOffset: function(elem) {
var offset = {left: 0, top:0};
if (elem.offsetParent) {
do {
offset.left += elem.offsetLeft;
offset.top += elem.offsetTop;
} while (elem = elem.offsetParent);
}
return offset;
},
// http://stackoverflow.com/posts/2684561/revisions
/**
*
* @param elem
*/
isActive: function(elem) {
return elem === document.activeElement && ( elem.type || elem.href );
}
};
return dom;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/color/interpret',
'dat/color/math',
'dat/color/toString',
'dat/utils/common'
], function(interpret, math, toString, common) {
var Color = function() {
this.__state = interpret.apply(this, arguments);
if (this.__state === false) {
throw 'Failed to interpret color arguments';
}
this.__state.a = this.__state.a || 1;
};
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a'];
common.extend(Color.prototype, {
toString: function() {
return toString(this);
},
toOriginal: function() {
return this.__state.conversion.write(this);
}
});
defineRGBComponent(Color.prototype, 'r', 2);
defineRGBComponent(Color.prototype, 'g', 1);
defineRGBComponent(Color.prototype, 'b', 0);
defineHSVComponent(Color.prototype, 'h');
defineHSVComponent(Color.prototype, 's');
defineHSVComponent(Color.prototype, 'v');
Object.defineProperty(Color.prototype, 'a', {
get: function() {
return this.__state.a;
},
set: function(v) {
this.__state.a = v;
}
});
Object.defineProperty(Color.prototype, 'hex', {
get: function() {
if (!this.__state.space !== 'HEX') {
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b);
}
return this.__state.hex;
},
set: function(v) {
this.__state.space = 'HEX';
this.__state.hex = v;
}
});
function defineRGBComponent(target, component, componentHexIndex) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'RGB') {
return this.__state[component];
}
recalculateRGB(this, component, componentHexIndex);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'RGB') {
recalculateRGB(this, component, componentHexIndex);
this.__state.space = 'RGB';
}
this.__state[component] = v;
}
});
}
function defineHSVComponent(target, component) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'HSV')
return this.__state[component];
recalculateHSV(this);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'HSV') {
recalculateHSV(this);
this.__state.space = 'HSV';
}
this.__state[component] = v;
}
});
}
function recalculateRGB(color, component, componentHexIndex) {
if (color.__state.space === 'HEX') {
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex);
} else if (color.__state.space === 'HSV') {
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
} else {
throw 'Corrupted color state';
}
}
function recalculateHSV(color) {
var result = math.rgb_to_hsv(color.r, color.g, color.b);
common.extend(color.__state,
{
s: result.s,
v: result.v
}
);
if (!common.isNaN(result.h)) {
color.__state.h = result.h;
} else if (common.isUndefined(color.__state.h)) {
color.__state.h = 0;
}
}
return Color;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
return function(color) {
if (color.a == 1 || common.isUndefined(color.a)) {
var s = color.hex.toString(16);
while (s.length < 6) {
s = '0' + s;
}
return '#' + s;
} else {
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')';
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/color/toString',
'dat/utils/common'
], function(toString, common) {
var result, toReturn;
var interpret = function() {
toReturn = false;
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0];
common.each(INTERPRETATIONS, function(family) {
if (family.litmus(original)) {
common.each(family.conversions, function(conversion, conversionName) {
result = conversion.read(original);
if (toReturn === false && result !== false) {
toReturn = result;
result.conversionName = conversionName;
result.conversion = conversion;
return common.BREAK;
}
});
return common.BREAK;
}
});
return toReturn;
};
var INTERPRETATIONS = [
// Strings
{
litmus: common.isString,
conversions: {
THREE_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt(
'0x' +
test[1].toString() + test[1].toString() +
test[2].toString() + test[2].toString() +
test[3].toString() + test[3].toString())
};
},
write: toString
},
SIX_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9]{6})$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt('0x' + test[1].toString())
};
},
write: toString
},
CSS_RGB: {
read: function(original) {
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3])
};
},
write: toString
},
CSS_RGBA: {
read: function(original) {
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3]),
a: parseFloat(test[4])
};
},
write: toString
}
}
},
// Numbers
{
litmus: common.isNumber,
conversions: {
HEX: {
read: function(original) {
return {
space: 'HEX',
hex: original,
conversionName: 'HEX'
}
},
write: function(color) {
return color.hex;
}
}
}
},
// Arrays
{
litmus: common.isArray,
conversions: {
RGB_ARRAY: {
read: function(original) {
if (original.length != 3) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2]
};
},
write: function(color) {
return [color.r, color.g, color.b];
}
},
RGBA_ARRAY: {
read: function(original) {
if (original.length != 4) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2],
a: original[3]
};
},
write: function(color) {
return [color.r, color.g, color.b, color.a];
}
}
}
},
// Objects
{
litmus: common.isObject,
conversions: {
RGBA_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b) &&
common.isNumber(original.a)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b,
a: original.a
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: color.a
}
}
},
RGB_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b
}
}
},
HSVA_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v) &&
common.isNumber(original.a)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v,
a: original.a
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v,
a: color.a
}
}
},
HSV_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v
}
}
}
}
}
];
return interpret;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
var tmpComponent;
return {
hsv_to_rgb: function(h, s, v) {
var hi = Math.floor(h / 60) % 6;
var f = h / 60 - Math.floor(h / 60);
var p = v * (1.0 - s);
var q = v * (1.0 - (f * s));
var t = v * (1.0 - ((1.0 - f) * s));
var c = [
[v, t, p],
[q, v, p],
[p, v, t],
[p, q, v],
[t, p, v],
[v, p, q]
][hi];
return {
r: c[0] * 255,
g: c[1] * 255,
b: c[2] * 255
};
},
rgb_to_hsv: function(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s;
if (max != 0) {
s = delta / max;
} else {
return {
h: NaN,
s: 0,
v: 0
};
}
if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h /= 6;
if (h < 0) {
h += 1;
}
return {
h: h * 360,
s: s,
v: max / 255
};
},
rgb_to_hex: function(r, g, b) {
var hex = this.hex_with_component(0, 2, r);
hex = this.hex_with_component(hex, 1, g);
hex = this.hex_with_component(hex, 0, b);
return hex;
},
component_from_hex: function(hex, componentIndex) {
return (hex >> (componentIndex * 8)) & 0xFF;
},
hex_with_component: function(hex, componentIndex, value) {
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent));
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
/**
* requirejs version of Paul Irish's RequestAnimationFrame
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60);
};
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([],
function() {
return {
load: function (url, doc) {
doc = doc || document;
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
doc.getElementsByTagName('head')[0].appendChild(link);
},
inject: function(css, doc) {
doc = doc || document;
var injected = document.createElement('style');
injected.type = 'text/css';
injected.innerHTML = css;
doc.getElementsByTagName('head')[0].appendChild(injected);
}
}
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
var ARR_EACH = Array.prototype.forEach;
var ARR_SLICE = Array.prototype.slice;
/**
* Band-aid methods for things that should be a lot easier in JavaScript.
* Implementation and structure inspired by underscore.js
* http://documentcloud.github.com/underscore/
*/
return {
BREAK: {},
extend: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (!this.isUndefined(obj[key]))
target[key] = obj[key];
}, this);
return target;
},
defaults: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (this.isUndefined(target[key]))
target[key] = obj[key];
}, this);
return target;
},
compose: function() {
var toCall = ARR_SLICE.call(arguments);
return function() {
var args = ARR_SLICE.call(arguments);
for (var i = toCall.length -1; i >= 0; i--) {
args = [toCall[i].apply(this, args)];
}
return args[0];
}
},
each: function(obj, itr, scope) {
if (ARR_EACH && obj.forEach === ARR_EACH) {
obj.forEach(itr, scope);
} else if (obj.length === obj.length + 0) { // Is number but not NaN
for (var key = 0, l = obj.length; key < l; key++)
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK)
return;
} else {
for (var key in obj)
if (itr.call(scope, obj[key], key) === this.BREAK)
return;
}
},
defer: function(fnc) {
setTimeout(fnc, 0);
},
toArray: function(obj) {
if (obj.toArray) return obj.toArray();
return ARR_SLICE.call(obj);
},
isUndefined: function(obj) {
return obj === undefined;
},
isNull: function(obj) {
return obj === null;
},
isNaN: function(obj) {
return obj !== obj;
},
isArray: Array.isArray || function(obj) {
return obj.constructor === Array;
},
isObject: function(obj) {
return obj === Object(obj);
},
isNumber: function(obj) {
return obj === obj+0;
},
isString: function(obj) {
return obj === obj+'';
},
isBoolean: function(obj) {
return obj === false || obj === true;
},
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
};
}); | JavaScript |
/**
* QUnit 1.2.0pre - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2011 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var defined = {
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
try {
return !!sessionStorage.getItem;
} catch(e) {
return false;
}
})()
};
var testId = 0,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
this.name = name;
this.testName = testName;
this.expected = expected;
this.testEnvironmentArg = testEnvironmentArg;
this.async = async;
this.callback = callback;
this.assertions = [];
};
Test.prototype = {
init: function() {
var tests = id("qunit-tests");
if (tests) {
var b = document.createElement("strong");
b.innerHTML = "Running " + this.name;
var li = document.createElement("li");
li.appendChild( b );
li.className = "running";
li.id = this.id = "test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (this.module != config.previousModule) {
if ( config.previousModule ) {
runLoggingCallbacks('moduleDone', QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment);
if (this.testEnvironmentArg) {
extend(this.testEnvironment, this.testEnvironmentArg);
}
runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName,
module: this.module
});
// allow utility functions to access the current test environment
// TODO why??
QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) {
saveGlobal();
}
this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
}
},
run: function() {
config.current = this;
if ( this.async ) {
QUnit.stop();
}
if ( config.notrycatch ) {
this.callback.call(this.testEnvironment);
return;
}
try {
this.callback.call(this.testEnvironment);
} catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
try {
this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
}
},
finish: function() {
config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if (bad) {
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
} else {
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
}
}
if (bad == 0) {
ol.style.display = "none";
}
var b = document.createElement("strong");
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
var a = document.createElement("a");
a.innerHTML = "Rerun";
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
addEvent(b, "click", function() {
var next = b.nextSibling.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() == "span" || target.nodeName.toLowerCase() == "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
}
});
var li = id(this.id);
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
li.appendChild( b );
li.appendChild( a );
li.appendChild( ol );
} else {
for ( var i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length
} );
},
queue: function() {
var test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// defer when previous test run passed, if storage is available
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
};
}
};
var QUnit = {
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
config.currentModuleTestEnviroment = testEnvironment;
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + testName + '</span>', 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 = '<span class="module-name">' + config.currentModule + "</span>: " + name;
}
if ( !validTest(config.currentModule + ": " + testName) ) {
return;
}
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue();
},
/**
* 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.current.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.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) {
QUnit.push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
QUnit.push(expected != actual, actual, expected, message);
},
deepEqual: function(actual, expected, message) {
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function(actual, expected, message) {
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
},
strictEqual: function(actual, expected, message) {
QUnit.push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
QUnit.push(expected !== actual, actual, expected, message);
},
raises: function(block, expected, message) {
var actual, ok = false;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}
QUnit.ok(ok, message);
},
start: function(count) {
config.semaphore -= count || 1;
if (config.semaphore > 0) {
// don't start until equal number of stop-calls
return;
}
if (config.semaphore < 0) {
// ignore if start is called more often then stop
config.semaphore = 0;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
window.setTimeout(function() {
if (config.semaphore > 0) {
return;
}
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process(true);
}, 13);
} else {
config.blocking = false;
process(true);
}
},
stop: function(count) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout(config.timeout);
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout);
}
}
};
//We want access to the constructor's prototype
(function() {
function F(){};
F.prototype = QUnit;
QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
})();
// 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,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
urlConfig: ['noglobals', 'notrycatch'],
//logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {},
current;
if ( params[ 0 ] ) {
for ( var i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
QUnit.urlParams = urlParams;
config.filter = urlParams.filter;
// 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;
}
// define these after exposing globals to keep them in these QUnit namespace only
extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
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 );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*/
reset: function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.innerHTML = config.fixture;
}
}
},
/**
* 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 QUnit.objectType( obj ) == type;
},
objectType: function( obj ) {
if (typeof obj === "undefined") {
return "undefined";
// consider: typeof null === object
}
if (obj === null) {
return "null";
}
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
switch (type) {
case 'Number':
if (isNaN(obj)) {
return "nan";
} else {
return "number";
}
case 'String':
case 'Boolean':
case 'Array':
case 'Date':
case 'RegExp':
case 'Function':
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
},
push: function(result, actual, expected, message) {
var details = {
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>";
expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual));
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
}
if (!result) {
var source = sourceFromStacktrace();
if (source) {
details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
}
}
output += "</table>";
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?",
key;
for ( key in params ) {
if ( !hasOwn.call( params, key ) ) {
continue;
}
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
return window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent
});
//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
//Doing this allows us to tell if the following methods have been overwritten on the actual
//QUnit object, which is a deprecated way of using the callbacks.
extend(QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback('begin'),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback('done'),
// log: { result, actual, expected, message }
log: registerLoggingCallback('log'),
// testStart: { name }
testStart: registerLoggingCallback('testStart'),
// testDone: { name, failed, passed, total }
testDone: registerLoggingCallback('testDone'),
// moduleStart: { name }
moduleStart: registerLoggingCallback('moduleStart'),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback('moduleDone')
});
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( 'begin', QUnit, {} );
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
}
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var banner = id("qunit-header");
if ( banner ) {
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
addEvent( banner, "change", function( event ) {
var params = {};
params[ event.target.name ] = event.target.checked ? true : undefined;
window.location = QUnit.url( params );
});
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var ol = document.getElementById("qunit-tests");
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace(/ hidepass /, " ");
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem("qunit-filter-passed-tests", "true");
} else {
sessionStorage.removeItem("qunit-filter-passed-tests");
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
filter.checked = true;
var ol = document.getElementById("qunit-tests");
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
}
var main = id('qunit-fixture');
if ( main ) {
config.fixture = main.innerHTML;
}
if (config.autostart) {
QUnit.start();
}
};
addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line );
} else {
test( "global failure", function() {
ok( false, message + ", " + file + ":" + line );
});
}
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
runLoggingCallbacks( 'moduleDone', QUnit, {
name: config.currentModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
runtime = +new Date - config.started,
passed = config.stats.all - config.stats.bad,
html = [
'Tests completed in ',
runtime,
' milliseconds.<br/>',
'<span class="passed">',
passed,
'</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 ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && typeof document !== "undefined" && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
(config.stats.bad ? "\u2716" : "\u2714"),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
} );
}
function validTest( name ) {
var filter = config.filter,
run = false;
if ( !filter ) {
return true;
}
var not = filter.charAt( 0 ) === "!";
if ( not ) {
filter = filter.slice( 1 );
}
if ( name.indexOf( filter ) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
return run;
}
// so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace() {
try {
throw new Error();
} catch ( e ) {
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[6];
} else if (e.stack) {
// Firefox, Chrome
return e.stack.split("\n")[4];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
}
}
function escapeInnerText(s) {
if (!s) {
return "";
}
s = s + "";
return s.replace(/[\&<>]/g, function(s) {
switch(s) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
default: return s;
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process(last);
}
}
function process( last ) {
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( function(){
process( last );
}, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( !hasOwn.call( window, key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
}
var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// 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 ) {
if ( b[prop] === undefined ) {
delete a[prop];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
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 );
}
function registerLoggingCallback(key){
return function(callback){
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(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 QUnit.objectType(b) === "date"
&& a.valueOf() === b.valueOf();
},
"regexp" : function(b, a) {
return QUnit.objectType(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, j, loop;
var len;
// b could be an object literal here
if (!(QUnit.objectType(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) {
loop = true;// dont rewalk array
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object" : function(b, a) {
var i, j, loop;
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);
// track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty
// and go deep
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i])
loop = true; // don't go down the same path
// twice
}
aProperties.push(i); // collect a's properties
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
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"
|| QUnit.objectType(a) !== QUnit.objectType(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, stack ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] , undefined , stack);
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
stack = stack || [ ];
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
var inStack = inArray(obj, stack);
if (inStack != -1) {
return 'recursion('+(inStack - stack.length)+')';
}
//else
if (type == 'function') {
stack.push(obj);
var res = parser.call( this, obj, stack );
stack.pop();
return res;
}
// else
return (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 (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
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,' ');
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, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map, stack ) {
var ret = [ ];
QUnit.jsDump.up();
for ( var key in map ) {
var val = map[key];
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
}
QUnit.jsDump.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = QUnit.jsDump.HTML ? '<' : '<',
close = QUnit.jsDump.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + QUnit.jsDump.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:false,//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;
})();
// from Sizzle.js
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
};
//from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
function diff(o, n) {
var ns = {};
var os = {};
for (var i = 0; i < n.length; i++) {
if (ns[n[i]] == null)
ns[n[i]] = {
rows: [],
o: null
};
ns[n[i]].rows.push(i);
}
for (var i = 0; i < o.length; i++) {
if (os[o[i]] == null)
os[o[i]] = {
rows: [],
n: null
};
os[o[i]].rows.push(i);
}
for (var i in ns) {
if ( !hasOwn.call( ns, i ) ) {
continue;
}
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
n[ns[i].rows[0]] = {
text: n[ns[i].rows[0]],
row: os[i].rows[0]
};
o[os[i].rows[0]] = {
text: o[os[i].rows[0]],
row: ns[i].rows[0]
};
}
}
for (var i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = {
text: n[i + 1],
row: n[i].row + 1
};
o[n[i].row + 1] = {
text: o[n[i].row + 1],
row: i + 1
};
}
}
for (var i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = {
text: n[i - 1],
row: n[i].row - 1
};
o[n[i].row - 1] = {
text: o[n[i].row - 1],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function(o, n) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = [" "];
}
else {
oSpace.push(" ");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = [" "];
}
else {
nSpace.push(" ");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
}
else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
})();
})(this);
| JavaScript |
require('./builder.js').build({
"baseUrl": "../src/",
"main": "dat/gui/GUI",
"out": "../build/dat.gui.js",
"minify": false,
"shortcut": "dat.GUI",
"paths": {}
}); | JavaScript |
require('./builder.js').build({
"baseUrl": "../src/",
"main": "dat/color/Color",
"out": "../build/dat.color.js",
"minify": false,
"shortcut": "dat.Color",
"paths": {}
}); | JavaScript |
/// # Google Closure Compiler Service #
/// https://github.com/weaver/scribbles/blob/master/node/google-closure/lib/closure.js
/// Compress javascript with Node.js using the Closure Compiler
/// Service.
var sys = require('sys');
exports.compile = compile;
// Use the Google Closure Compiler Service to compress Javascript
// code.
//
// + code - String of javascript to compress
// + next - Function callback that accepts.
//
// This method will POST the `code` to the compiler service. If an
// error occurs, `next()` will be called with an `Error` object as the
// first argument. Otherwise, the `next()` will be called with `null`
// as the first argument and a String of compressed javascript as the
// second argument.
//
// compile('... javascript ...', function(err, result) {
// if (err) throw err;
//
// ... do something with result ...
// });
//
// Returns nothing.
function compile(code, next) {
try {
var qs = require('querystring'),
http = require('http'),
host = 'closure-compiler.appspot.com',
body = qs.stringify({
js_code: code.toString('utf-8'),
compilation_level: 'SIMPLE_OPTIMIZATIONS',
output_format: 'json',
output_info: 'compiled_code'
}),
client = http.createClient(80, host).on('error', next),
req = client.request('POST', '/compile', {
'Host': host,
'Content-Length': body.length,
'Content-Type': 'application/x-www-form-urlencoded'
});
req.on('error', next).end(body);
req.on('response', function(res) {
if (res.statusCode != 200)
next(new Error('Unexpected HTTP response: ' + res.statusCode));
else
capture(res, 'utf-8', parseResponse);
});
function parseResponse(err, data) {
err ? next(err) : loadJSON(data, function(err, obj) {
var error;
if (err)
next(err);
else if ((error = obj.errors || obj.serverErrors || obj.warnings))
next(new Error('Failed to compile: ' + sys.inspect(error)));
else
next(null, obj.compiledCode);
});
}
} catch (err) {
next(err);
}
}
// Convert a Stream to a String.
//
// + input - Stream object
// + encoding - String input encoding
// + next - Function error/success callback
//
// Returns nothing.
function capture(input, encoding, next) {
var buffer = '';
input.on('data', function(chunk) {
buffer += chunk.toString(encoding);
});
input.on('end', function() {
next(null, buffer);
});
input.on('error', next);
}
// Convert JSON.load() to callback-style.
//
// + data - String value to load
// + next - Function error/success callback
//
// Returns nothing.
function loadJSON(data, next) {
var err, obj;
try {
obj = JSON.parse(data);
} catch (x) {
err = x;
}
next(err, obj);
} | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
var fs = require('fs'),
closure = require('./closure'),
params,
defined,
third_party,
request_counts,
namespaces,
next_load = '',
next_path = '';
exports.build = build;
exports.file_exists = file_exists;
exports.read_file = read_file;
exports.tab = tab;
exports.license = read_file('license.txt');
function build(_params) {
params = _params;
defined = {};
third_party = {};
request_counts = {};
namespaces = {};
var deps = [];
load_module(params.baseUrl + params.main + '.js', params.main);
for (var i in defined) {
if (params.verbose) console.log('Loaded: ' + defined[i].path);
deps.push(defined[i].path);
if (defined[i].module) {
var namespace = i.substr(0, i.lastIndexOf('/'));
namespaces[namespace] = true;
}
}
var to_write = '';
var ensured = {};
for (var name in params.paths) {
var path = params.baseUrl + params.paths[name] + '.js';
var str = read_file(path);
if (str === false) {
console.log('Failed to locate dependency \'' + name + '\' at ' + path);
fail();
}
third_party[name] = str;
to_write += third_party[name] + "\n\n";
if (params.verbose) console.log('Loaded: ' + path);
//deps.push(path);
}
// Ensure namespaces
for (i in namespaces) {
var split = i.split('/');
for (var j = 0; j < split.length; j++) {
var cur = [];
if (j == 0 && !ensured[split[j]]) {
to_write += '/** @namespace */\n';
to_write += 'var ' + split[j] + ' = ' + split[j] + ' || {};\n\n';
ensured[split[j]] = true;
} else {
for (var k = 0; k <= j; k++) {
cur.push(split[k]);
}
var curn = cur.join('.');
if (!ensured[curn]) {
to_write += '/** @namespace */\n';
to_write += curn + ' = ' + curn + ' || {};\n\n';
}
ensured[curn] = true;
}
}
}
var shared_count = 0;
for (i in request_counts) {
var count = request_counts[i];
if (count > 1) {
if (i in defined) {
var new_shared = i.replace(/\//g, '.');
var v = new_shared + ' = ' + defined[i].getClosure() + ';\n';
to_write += v + "\n\n";
defined[i].shared = new_shared;
shared_count++;
}
}
}
to_write += params.shortcut + ' = ' + params.main.replace(/\//g, '.') + ' = ' + defined[params.main].getClosure() + ';';
if (params.verbose) console.log('Exported: ' + params.main + ' to window.' + params.shortcut);
if (params.minify) {
console.log('Compiling minified source ...');
closure.compile(to_write, function(error, code) {
if (error) {
console.log(error);
} else {
write(exports.license + code);
}
if (params.on_compile) {
params.on_compile();
}
});
} else {
write(exports.license + "\n" + to_write);
}
return deps;
}
function define(deps, callback) {
this.name = next_load;
this.path = next_path;
this.shared = false;
defined[this.name] = this;
if (Array.isArray(deps)) {
this.deps = deps;
this.callback = callback.toString();
this.module = true;
// Simple define call, just an object
} else if (typeof deps === 'object') {
var props = [];
for (var i in deps) {
props.push(i + ':' + deps[i].toString())
}
this.callback = '{' + props.join(',') + '}';
this.module = true;
} else {
this.deps = deps;
this.callback = callback;
}
this.getClosure = function() {
if (this.shared) return this.shared;
if (!this.deps || this.text) return this.callback;
var arg_string = '(';
var args = [];
for (var i in this.deps) {
var dep = this.deps[i];
if (dep in defined) {
var closure = defined[dep].getClosure();
if (!defined[dep].shared && !defined[dep].text) {
closure = defined[dep].name.replace(/\//g, '.') + ' = ' + closure;
}
args.push(closure);
}
}
arg_string += args.join(',\n');
arg_string += ')';
return '(' + this.callback + ')' + arg_string;
};
this.recurseDeps = function() {
if (!this.deps) return;
for (var i in this.deps) {
var dep = this.deps[i];
if (dep in params.paths) continue;
var path = params.baseUrl + dep;
// Define module?
if (file_exists(path + '.js')) {
load_module(path + '.js', dep);
// Text module?
} else if (path.match(/text!/) != null) {
load_text(path.replace('text!', ''), dep);
}
// up the request count
if (dep in request_counts) {
request_counts[dep]++
} else {
request_counts[dep] = 1;
}
}
};
this.recurseDeps();
}
function file_exists(path) {
try {
var stats = fs.lstatSync(path)
return stats.isFile();
} catch (e) {
return false;
}
}
function read_file(path) {
try {
return fs.readFileSync(path).toString();
} catch (e) {
return false;
}
}
function load_module(path, name) {
name = name || path;
if (name in defined) return;
next_load = name;
next_path = path;
eval('new ' + read_file(path));
}
function load_text(path, name) {
name = name || path;
if (name in defined) return;
var text = read_file(path);
text = text.replace(/\r/g, "\\r");
text = text.replace(/\n/g, "\\n");
text = text.replace(/"/g, "\\\"");
next_load = name;
next_path = path;
var d = new define([], '"' + text + '"');
d.text = true;
d.module = false;
}
function tab(str, tabs) {
var lines = str.split("\n");
for (var i in lines) {
lines[i] = tabs + lines[i];
}
return lines.join("\n");
}
function write(str) {
fs.writeFile(params.out, str);
console.log('Saved to ' + params.out);
}
function fail() {
console.log('Build failed.');
process.exit(0);
} | JavaScript |
/*
* jQuery Form Plugin
* version: 2.02 (12/16/2007)
* @requires jQuery v1.1 or later
*
* Examples at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*/
(function($) {
/**
* ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.
*
* ajaxSubmit accepts a single argument which can be either a success callback function
* or an options Object. If a function is provided it will be invoked upon successful
* completion of the submit and will be passed the response from the server.
* If an options Object is provided, the following attributes are supported:
*
* target: Identifies the element(s) in the page to be updated with the server response.
* This value may be specified as a jQuery selection string, a jQuery object,
* or a DOM element.
* default value: null
*
* url: URL to which the form data will be submitted.
* default value: value of form's 'action' attribute
*
* type: The method in which the form data should be submitted, 'GET' or 'POST'.
* default value: value of form's 'method' attribute (or 'GET' if none found)
*
* data: Additional data to add to the request, specified as key/value pairs (see $.ajax).
*
* beforeSubmit: Callback method to be invoked before the form is submitted.
* default value: null
*
* success: Callback method to be invoked after the form has been successfully submitted
* and the response has been returned from the server
* default value: null
*
* dataType: Expected dataType of the response. One of: null, 'xml', 'script', or 'json'
* default value: null
*
* semantic: Boolean flag indicating whether data must be submitted in semantic order (slower).
* default value: false
*
* resetForm: Boolean flag indicating whether the form should be reset if the submit is successful
*
* clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful
*
*
* The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for
* validating the form data. If the 'beforeSubmit' callback returns false then the form will
* not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data
* in array format, the jQuery object, and the options object passed into ajaxSubmit.
* The form data array takes the following form:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* If a 'success' callback method is provided it is invoked after the response has been returned
* from the server. It is passed the responseText or responseXML value (depending on dataType).
* See jQuery.ajax for further details.
*
*
* The dataType option provides a means for specifying how the server response should be handled.
* This maps directly to the jQuery.httpData method. The following values are supported:
*
* 'xml': if dataType == 'xml' the server response is treated as XML and the 'success'
* callback method, if specified, will be passed the responseXML value
* 'json': if dataType == 'json' the server response will be evaluted and passed to
* the 'success' callback, if specified
* 'script': if dataType == 'script' the server response is evaluated in the global context
*
*
* Note that it does not make sense to use both the 'target' and 'dataType' options. If both
* are provided the target will be ignored.
*
* The semantic argument can be used to force form serialization in semantic order.
* This is normally true anyway, unless the form contains input elements of type='image'.
* If your form must be submitted with name/value pairs in semantic order and your form
* contains an input of type='image" then pass true for this arg, otherwise pass false
* (or nothing) to avoid the overhead for this logic.
*
*
* When used on its own, ajaxSubmit() is typically bound to a form's submit event like this:
*
* $("#form-id").submit(function() {
* $(this).ajaxSubmit(options);
* return false; // cancel conventional submit
* });
*
* When using ajaxForm(), however, this is done for you.
*
* @example
* $('#myForm').ajaxSubmit(function(data) {
* alert('Form submit succeeded! Server returned: ' + data);
* });
* @desc Submit form and alert server response
*
*
* @example
* var options = {
* target: '#myTargetDiv'
* };
* $('#myForm').ajaxSubmit(options);
* @desc Submit form and update page element with server response
*
*
* @example
* var options = {
* success: function(responseText) {
* alert(responseText);
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc Submit form and alert the server response
*
*
* @example
* var options = {
* beforeSubmit: function(formArray, jqForm) {
* if (formArray.length == 0) {
* alert('Please enter data.');
* return false;
* }
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc Pre-submit validation which aborts the submit operation if form data is empty
*
*
* @example
* var options = {
* url: myJsonUrl.php,
* dataType: 'json',
* success: function(data) {
* // 'data' is an object representing the the evaluated json data
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc json data returned and evaluated
*
*
* @example
* var options = {
* url: myXmlUrl.php,
* dataType: 'xml',
* success: function(responseXML) {
* // responseXML is XML document object
* var data = $('myElement', responseXML).text();
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc XML data returned from server
*
*
* @example
* var options = {
* resetForm: true
* };
* $('#myForm').ajaxSubmit(options);
* @desc submit form and reset it if successful
*
* @example
* $('#myForm).submit(function() {
* $(this).ajaxSubmit();
* return false;
* });
* @desc Bind form's submit event to use ajaxSubmit
*
*
* @name ajaxSubmit
* @type jQuery
* @param options object literal containing options which control the form submission process
* @cat Plugins/Form
* @return jQuery
*/
$.fn.ajaxSubmit = function(options) {
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
$.event.trigger('form.pre.serialize', [this, options, veto]);
if (veto.veto) return this;
var a = this.formToArray(options.semantic);
if (options.data) {
for (var n in options.data)
a.push( { name: n, value: options.data[n] } );
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this;
// fire vetoable 'validate' event
$.event.trigger('form.submit.validate', [a, this, options, veto]);
if (veto.veto) return this;
var q = $.param(a);//.replace(/%20/g,'+');
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else
options.data = q; // data is the query string for 'post'
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
if (this.evalScripts)
$(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, arguments);
else // jQuery v1.1.4
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i](data, status, $form);
};
// are there files to upload?
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
// options.iframe allows user to force iframe mode
if (options.iframe || found) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
// fire 'notify' event
$.event.trigger('form.submit.notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
var opts = $.extend({}, $.ajaxSettings, options);
var id = 'jqFormIO' + $.fn.ajaxSubmit.counter++;
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
var op8 = $.browser.opera && window.opera.version() < 9;
if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {}
};
var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
var cbInvoked = 0;
var timedOut = 0;
// take a breath so that pending repaints get some cpu time before the upload starts
setTimeout(function() {
// make sure form attrs are set
var encAttr = form.encoding ? 'encoding' : 'enctype';
var t = $form.attr('target');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
form[encAttr] = 'multipart/form-data';
// support timout
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
$form.attr('target', t); // reset target
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var ok = true;
try {
if (timedOut) throw 'timeout';
// extract the server response from the iframe
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
data = ta ? ta.value : xhr.responseText;
if (opts.dataType == 'json')
eval("data = " + data);
else
$.globalEval(data);
}
else if (opts.dataType == 'xml') {
data = xhr.responseXML;
if (!data && xhr.responseText != null)
data = toXml(xhr.responseText);
}
else {
data = xhr.responseText;
}
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxSubmit.counter = 0; // used to create unique iframe ids
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* Note that for accurate x/y coordinates of image submit elements in all browsers
* you need to also use the "dimensions" plugin (this method will auto-detect its presence).
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself. See ajaxSubmit for a full description of the options argument.
*
*
* @example
* var options = {
* target: '#myTargetDiv'
* };
* $('#myForm').ajaxSForm(options);
* @desc Bind form's submit event so that 'myTargetDiv' is updated with the server response
* when the form is submitted.
*
*
* @example
* var options = {
* success: function(responseText) {
* alert(responseText);
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc Bind form's submit event so that server response is alerted after the form is submitted.
*
*
* @example
* var options = {
* beforeSubmit: function(formArray, jqForm) {
* if (formArray.length == 0) {
* alert('Please enter data.');
* return false;
* }
* }
* };
* $('#myForm').ajaxSubmit(options);
* @desc Bind form's submit event so that pre-submit callback is invoked before the form
* is submitted.
*
*
* @name ajaxForm
* @param options object literal containing options which control the form submission process
* @return jQuery
* @cat Plugins/Form
* @type jQuery
*/
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().submit(submitHandler).each(function() {
// store options in hash
this.formPluginId = $.fn.ajaxForm.counter++;
$.fn.ajaxForm.optionHash[this.formPluginId] = options;
$(":submit,input:image", this).click(clickHandler);
});
};
$.fn.ajaxForm.counter = 1;
$.fn.ajaxForm.optionHash = {};
function clickHandler(e) {
var $form = this.form;
$form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
$form.clk_x = e.offsetX;
$form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
$form.clk_x = e.pageX - offset.left;
$form.clk_y = e.pageY - offset.top;
} else {
$form.clk_x = e.pageX - this.offsetLeft;
$form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
};
function submitHandler() {
// retrieve options from hash
var id = this.formPluginId;
var options = $.fn.ajaxForm.optionHash[id];
$(this).ajaxSubmit(options);
return false;
};
/**
* ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
*
* @name ajaxFormUnbind
* @return jQuery
* @cat Plugins/Form
* @type jQuery
*/
$.fn.ajaxFormUnbind = function() {
this.unbind('submit', submitHandler);
return this.each(function() {
$(":submit,input:image", this).unbind('click', clickHandler);
});
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*
* The semantic argument can be used to force form serialization in semantic order.
* This is normally true anyway, unless the form contains input elements of type='image'.
* If your form must be submitted with name/value pairs in semantic order and your form
* contains an input of type='image" then pass true for this arg, otherwise pass false
* (or nothing) to avoid the overhead for this logic.
*
* @example var data = $("#myForm").formToArray();
* $.post( "myscript.cgi", data );
* @desc Collect all the data from a form and submit it to the server.
*
* @name formToArray
* @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
* @type Array<Object>
* @cat Plugins/Form
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*
* The semantic argument can be used to force form serialization in semantic order.
* If your form must be submitted with name/value pairs in semantic order then pass
* true for this arg, otherwise pass false (or nothing) to avoid the overhead for
* this logic (which can be significant for very large forms).
*
* @example var data = $("#myForm").formSerialize();
* $.ajax('POST', "myscript.cgi", data);
* @desc Collect all the data from a form into a single string
*
* @name formSerialize
* @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
* @type String
* @cat Plugins/Form
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*
* The successful argument controls whether or not serialization is limited to
* 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true.
*
* @example var data = $("input").formSerialize();
* @desc Collect the data from all successful input elements into a query string
*
* @example var data = $(":radio").formSerialize();
* @desc Collect the data from all successful radio input elements into a query string
*
* @example var data = $("#myForm :checkbox").formSerialize();
* @desc Collect the data from all successful checkbox input elements in myForm into a query string
*
* @example var data = $("#myForm :checkbox").formSerialize(false);
* @desc Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string
*
* @example var data = $(":input").formSerialize();
* @desc Collect the data from all successful input, select, textarea and button elements into a query string
*
* @name fieldSerialize
* @param successful true if only successful controls should be serialized (default is true)
* @type String
* @cat Plugins/Form
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*
* @example var data = $("#myPasswordElement").fieldValue();
* alert(data[0]);
* @desc Alerts the current value of the myPasswordElement element
*
* @example var data = $("#myForm :input").fieldValue();
* @desc Get the value(s) of the form elements in myForm
*
* @example var data = $("#myForm :checkbox").fieldValue();
* @desc Get the value(s) for the successful checkbox element(s) in the jQuery object.
*
* @example var data = $("#mySingleSelect").fieldValue();
* @desc Get the value(s) of the select control
*
* @example var data = $(':text').fieldValue();
* @desc Get the value(s) of the text input or textarea elements
*
* @example var data = $("#myMultiSelect").fieldValue();
* @desc Get the values for the select-multiple control
*
* @name fieldValue
* @param Boolean successful true if only the values for successful controls should be returned (default is true)
* @type Array<String>
* @cat Plugins/Form
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If the given element is not
* successful and the successful arg is not false then the returned value will be null.
*
* Note: If the successful flag is true (default) but the element is not successful, the return will be null
* Note: The value returned for a successful select-multiple element will always be an array.
* Note: If the element has no value the return value will be undefined.
*
* @example var data = jQuery.fieldValue($("#myPasswordElement")[0]);
* @desc Gets the current value of the myPasswordElement element
*
* @name fieldValue
* @param Element el The DOM element for which the value will be returned
* @param Boolean successful true if value returned must be for a successful controls (default is true)
* @type String or Array<String> or null or undefined
* @cat Plugins/Form
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
// extra pain for IE...
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*
* @example $('form').clearForm();
* @desc Clears all forms on the page.
*
* @name clearForm
* @type jQuery
* @cat Plugins/Form
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements. Takes the following actions on the matched elements:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*
* @example $('.myInputs').clearFields();
* @desc Clears all inputs with class myInputs
*
* @name clearFields
* @type jQuery
* @cat Plugins/Form
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*
* @example $('form').resetForm();
* @desc Resets all forms on the page.
*
* @name resetForm
* @type jQuery
* @cat Plugins/Form
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
/**
* Enables or disables any matching elements.
*
* @example $(':radio').enabled(false);
* @desc Disables all radio buttons
*
* @name select
* @type jQuery
* @cat Plugins/Form
*/
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*
* @example $(':checkbox').selected();
* @desc Checks all checkboxes
*
* @name select
* @type jQuery
* @cat Plugins/Form
*/
$.fn.select = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').select(false);
}
this.selected = select;
}
});
};
})(jQuery);
| JavaScript |
/* Croatian i18n for the jQuery UI date picker plugin. */
/* Written by Vjekoslav Nesek. */
jQuery(function($){
$.datepicker.regional['hr'] = {
clearText: 'izbriši', clearStatus: 'Izbriši trenutni datum',
closeText: 'Zatvori', closeStatus: 'Zatvori kalendar',
prevText: '<', prevStatus: 'Prikaži prethodni mjesec',
prevBigText: '<<', prevBigStatus: '',
nextText: '>', nextStatus: 'Prikaži slijedeći mjesec',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Danas', currentStatus: 'Današnji datum',
monthNames: ['Siječanj','Veljača','Ožujak','Travanj','Svibanj','Lipani',
'Srpanj','Kolovoz','Rujan','Listopad','Studeni','Prosinac'],
monthNamesShort: ['Sij','Velj','Ožu','Tra','Svi','Lip',
'Srp','Kol','Ruj','Lis','Stu','Pro'],
monthStatus: 'Prikaži mjesece', yearStatus: 'Prikaži godine',
weekHeader: 'Tje', weekStatus: 'Tjedan',
dayNames: ['Nedjalja','Ponedjeljak','Utorak','Srijeda','Četvrtak','Petak','Subota'],
dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
dayStatus: 'Odaber DD za prvi dan tjedna', dateStatus: '\'Datum\' D, M d',
dateFormat: 'dd.mm.yy.', firstDay: 1,
initStatus: 'Odaberi datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hr']);
}); | JavaScript |
/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Cloudream (cloudream@gmail.com). */
jQuery(function($){
$.datepicker.regional['zh-CN'] = {
clearText: '清除', clearStatus: '清除已选日期',
closeText: '关闭', closeStatus: '不改变当前选择',
prevText: '<上月', prevStatus: '显示上月',
prevBigText: '<<', prevBigStatus: '显示上一年',
nextText: '下月>', nextStatus: '显示下月',
nextBigText: '>>', nextBigStatus: '显示下一年',
currentText: '今天', currentStatus: '显示本月',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
monthStatus: '选择月份', yearStatus: '选择年份',
weekHeader: '周', weekStatus: '年内周次',
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
dayStatus: '设置 DD 为一周起始', dateStatus: '选择 m月 d日, DD',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '请选择日期', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});
| JavaScript |
/* Hebrew initialisation for the UI Datepicker extension. */
/* Written by Amir Hardon (ahardon at gmail dot com). */
jQuery(function($){
$.datepicker.regional['he'] = {
clearText: 'נקה', clearStatus: '',
closeText: 'סגור', closeStatus: '',
prevText: '<הקודם', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'הבא>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'היום', currentStatus: '',
monthNames: ['ינואר','פברואר','מרץ','אפריל','מאי','יוני',
'יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'],
monthNamesShort: ['1','2','3','4','5','6',
'7','8','9','10','11','12'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
dayStatus: 'DD', dateStatus: 'DD, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: true};
$.datepicker.setDefaults($.datepicker.regional['he']);
});
| JavaScript |
/* Norwegian initialisation for the jQuery UI date picker plugin. */
/* Written by Naimdjon Takhirov (naimdjon@gmail.com). */
jQuery(function($){
$.datepicker.regional['no'] = {
clearText: 'Tøm', clearStatus: '',
closeText: 'Lukk', closeStatus: '',
prevText: '«Forrige', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Neste»', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'I dag', currentStatus: '',
monthNames: ['Januar','Februar','Mars','April','Mai','Juni',
'Juli','August','September','Oktober','November','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Des'],
monthStatus: '', yearStatus: '',
weekHeader: 'Uke', weekStatus: '',
dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['no']);
});
| JavaScript |
/* Thai initialisation for the jQuery UI date picker plugin. */
/* Written by pipo (pipo@sixhead.com). */
jQuery(function($){
$.datepicker.regional['th'] = {
clearText: 'ลบ', clearStatus: '',
closeText: 'ปิด', closeStatus: '',
prevText: '« ย้อน', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'ถัดไป »', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'วันนี้', currentStatus: '',
monthNames: ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน',
'กรกฏาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'],
monthNamesShort: ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.',
'ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'],
dayNamesShort: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
dayNamesMin: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['th']);
}); | JavaScript |
/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Ressol (ressol@gmail.com). */
jQuery(function($){
$.datepicker.regional['zh-TW'] = {
clearText: '清除', clearStatus: '清除已選日期',
closeText: '關閉', closeStatus: '不改變目前的選擇',
prevText: '<上月', prevStatus: '顯示上月',
prevBigText: '<<', prevBigStatus: '顯示上一年',
nextText: '下月>', nextStatus: '顯示下月',
nextBigText: '>>', nextBigStatus: '顯示下一年',
currentText: '今天', currentStatus: '顯示本月',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
monthStatus: '選擇月份', yearStatus: '選擇年份',
weekHeader: '周', weekStatus: '年內周次',
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
dayStatus: '設定 DD 為一周起始', dateStatus: '選擇 m月 d日, DD',
dateFormat: 'yy/mm/dd', firstDay: 1,
initStatus: '請選擇日期', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-TW']);
});
| JavaScript |
/* Brazilian initialisation for the jQuery UI date picker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function($){
$.datepicker.regional['pt-BR'] = {
clearText: 'Limpar', clearStatus: '',
closeText: 'Fechar', closeStatus: '',
prevText: '<Anterior', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Próximo>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Hoje', currentStatus: '',
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
'Jul','Ago','Set','Out','Nov','Dez'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
}); | JavaScript |
/* Romanian initialisation for the jQuery UI date picker plugin. */
/* Written by Edmond L. (ll_edmond@walla.com). */
jQuery(function($){
$.datepicker.regional['ro'] = {
clearText: 'Curat', clearStatus: 'Sterge data curenta',
closeText: 'Inchide', closeStatus: 'Inchide fara schimbare',
prevText: '<Anterior', prevStatus: 'Arata luna trecuta',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Urmator>', nextStatus: 'Arata luna urmatoare',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Azi', currentStatus: 'Arata luna curenta',
monthNames: ['Ianuarie','Februarie','Martie','Aprilie','Mai','Junie',
'Julie','August','Septembrie','Octobrie','Noiembrie','Decembrie'],
monthNamesShort: ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'],
monthStatus: 'Arata o luna diferita', yearStatus: 'Arat un an diferit',
weekHeader: 'Sapt', weekStatus: 'Saptamana anului',
dayNames: ['Duminica', 'Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata'],
dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sam'],
dayNamesMin: ['Du','Lu','Ma','Mi','Jo','Vi','Sa'],
dayStatus: 'Seteaza DD ca prima saptamana zi', dateStatus: 'Selecteaza D, M d',
dateFormat: 'mm/dd/yy', firstDay: 0,
initStatus: 'Selecteaza o data', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ro']);
});
| JavaScript |
/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by ??? */
jQuery(function($){
$.datepicker.regional['nl'] = {
clearText: 'Wissen', clearStatus: 'Wis de huidige datum',
closeText: 'Sluiten', closeStatus: 'Sluit zonder verandering',
prevText: '<Terug', prevStatus: 'Laat de voorgaande maand zien',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Volgende>', nextStatus: 'Laat de volgende maand zien',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Vandaag', currentStatus: 'Laat de huidige maand zien',
monthNames: ['Januari','Februari','Maart','April','Mei','Juni',
'Juli','Augustus','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mrt','Apr','Mei','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: 'Laat een andere maand zien', yearStatus: 'Laat een ander jaar zien',
weekHeader: 'Wk', weekStatus: 'Week van het jaar',
dayNames: ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag'],
dayNamesShort: ['Zon','Maa','Din','Woe','Don','Vri','Zat'],
dayNamesMin: ['Zo','Ma','Di','Wo','Do','Vr','Za'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Kies een datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['nl']);
}); | JavaScript |
/* Esperanto initialisation for the jQuery UI date picker plugin. */
/* Written by Olivier M. (olivierweb@ifrance.com). */
jQuery(function($){
$.datepicker.regional['eo'] = {
clearText: 'Vakigi', clearStatus: '',
closeText: 'Fermi', closeStatus: 'Fermi sen modifi',
prevText: '<Anta', prevStatus: 'Vidi la antaŭan monaton',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Sekv>', nextStatus: 'Vidi la sekvan monaton',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Nuna', currentStatus: 'Vidi la nunan monaton',
monthNames: ['Januaro','Februaro','Marto','Aprilo','Majo','Junio',
'Julio','Aŭgusto','Septembro','Oktobro','Novembro','Decembro'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aŭg','Sep','Okt','Nov','Dec'],
monthStatus: 'Vidi alian monaton', yearStatus: 'Vidi alian jaron',
weekHeader: 'Sb', weekStatus: '',
dayNames: ['Dimanĉo','Lundo','Mardo','Merkredo','Ĵaŭdo','Vendredo','Sabato'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Ĵaŭ','Ven','Sab'],
dayNamesMin: ['Di','Lu','Ma','Me','Ĵa','Ve','Sa'],
dayStatus: 'Uzi DD kiel unua tago de la semajno', dateStatus: 'Elekti DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Elekti la daton', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['eo']);
});
| JavaScript |
/* Slovenian initialisation for the jQuery UI date picker plugin. */
/* Written by Jaka Jancar (jaka@kubje.org). */
/* c = č, s = š z = ž C = Č S = Š Z = Ž */
jQuery(function($){
$.datepicker.regional['sl'] = {clearText: 'Izbriši', clearStatus: 'Izbriši trenutni datum',
closeText: 'Zapri', closeStatus: 'Zapri brez spreminjanja',
prevText: '<Prejšnji', prevStatus: 'Prikaži prejšnji mesec',
nextText: 'Naslednji>', nextStatus: 'Prikaži naslednji mesec',
currentText: 'Trenutni', currentStatus: 'Prikaži trenutni mesec',
monthNames: ['Januar','Februar','Marec','April','Maj','Junij',
'Julij','Avgust','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Avg','Sep','Okt','Nov','Dec'],
monthStatus: 'Prikaži drug mesec', yearStatus: 'Prikaži drugo leto',
weekHeader: 'Teden', weekStatus: 'Teden v letu',
dayNames: ['Nedelja','Ponedeljek','Torek','Sreda','Četrtek','Petek','Sobota'],
dayNamesShort: ['Ned','Pon','Tor','Sre','Čet','Pet','Sob'],
dayNamesMin: ['Ne','Po','To','Sr','Če','Pe','So'],
dayStatus: 'Nastavi DD za prvi dan v tednu', dateStatus: 'Izberi DD, d MM yy',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Izbira datuma', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sl']);
});
| JavaScript |
/* Slovak initialisation for the jQuery UI date picker plugin. */
/* Written by Vojtech Rinik (vojto@hmm.sk). */
jQuery(function($){
$.datepicker.regional['sk'] = {
clearText: 'Zmazať', clearStatus: '',
closeText: 'Zavrieť', closeStatus: '',
prevText: '<Predchádzajúci', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nasledujúci>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Dnes', currentStatus: '',
monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
'Júl','August','September','Október','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Máj','Jún',
'Júl','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Ty', weekStatus: '',
dayNames: ['Nedel\'a','Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota'],
dayNamesShort: ['Ned','Pon','Uto','Str','Štv','Pia','Sob'],
dayNamesMin: ['Ne','Po','Ut','St','Št','Pia','So'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sk']);
});
| JavaScript |
/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Andrew Stromnov (stromnov@gmail.com). */
jQuery(function($){
$.datepicker.regional['ru'] = {
clearText: 'Очистить', clearStatus: '',
closeText: 'Закрыть', closeStatus: '',
prevText: '<Пред', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'След>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Сегодня', currentStatus: '',
monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
'Июл','Авг','Сен','Окт','Ноя','Дек'],
monthStatus: '', yearStatus: '',
weekHeader: 'Не', weekStatus: '',
dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ru']);
}); | JavaScript |
/* Italian initialisation for the jQuery UI date picker plugin. */
/* Written by Apaella (apaella@gmail.com). */
jQuery(function($){
$.datepicker.regional['it'] = {
clearText: 'Svuota', clearStatus: 'Annulla',
closeText: 'Chiudi', closeStatus: 'Chiudere senza modificare',
prevText: '<Prec', prevStatus: 'Mese precedente',
prevBigText: '<<', prevBigStatus: 'Mostra l\'anno precedente',
nextText: 'Succ>', nextStatus: 'Mese successivo',
nextBigText: '>>', nextBigStatus: 'Mostra l\'anno successivo',
currentText: 'Oggi', currentStatus: 'Mese corrente',
monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
'Lug','Ago','Set','Ott','Nov','Dic'],
monthStatus: 'Seleziona un altro mese', yearStatus: 'Seleziona un altro anno',
weekHeader: 'Sm', weekStatus: 'Settimana dell\'anno',
dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'],
dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'],
dayStatus: 'Usa DD come primo giorno della settimana', dateStatus: 'Seleziona D, M d',
dateFormat: 'dd/mm/yy', firstDay: 1,
initStatus: 'Scegliere una data', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['it']);
});
| JavaScript |
/* Arabic Translation for jQuery UI date picker plugin. */
/* Khaled Al Horani -- koko.dw@gmail.com */
/* خالد الحوراني -- koko.dw@gmail.com */
/* NOTE: monthNames are the original months names and they are the Arabic names, not the new months name فبراير - يناير and there isn't any Arabic roots for these months */
jQuery(function($){
$.datepicker.regional['ar'] = {
clearText: 'مسح', clearStatus: 'امسح التاريخ الحالي',
closeText: 'إغلاق', closeStatus: 'إغلاق بدون حفظ',
prevText: '<السابق', prevStatus: 'عرض الشهر السابق',
prevBigText: '<<', prevBigStatus: '',
nextText: 'التالي>', nextStatus: 'عرض الشهر القادم',
nextBigText: '>>', nextBigStatus: '',
currentText: 'اليوم', currentStatus: 'عرض الشهر الحالي',
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران',
'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
monthStatus: 'عرض شهر آخر', yearStatus: 'عرض سنة آخرى',
weekHeader: 'أسبوع', weekStatus: 'أسبوع السنة',
dayNames: ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
dayNamesShort: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
dayNamesMin: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
dayStatus: 'اختر DD لليوم الأول من الأسبوع', dateStatus: 'اختر D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'اختر يوم', isRTL: true};
$.datepicker.setDefaults($.datepicker.regional['ar']);
}); | JavaScript |
/* Swedish initialisation for the jQuery UI date picker plugin. */
/* Written by Anders Ekdahl ( anders@nomadiz.se). */
jQuery(function($){
$.datepicker.regional['sv'] = {
clearText: 'Rensa', clearStatus: '',
closeText: 'Stäng', closeStatus: '',
prevText: '«Förra', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nästa»', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Idag', currentStatus: '',
monthNames: ['Januari','Februari','Mars','April','Maj','Juni',
'Juli','Augusti','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Ve', weekStatus: '',
dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sv']);
});
| JavaScript |
/* Japanese (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Milly. */
jQuery(function($){
$.datepicker.regional['ja'] = {
clearText: '削除', clearStatus: '',
closeText: '閉じる', closeStatus: '',
prevText: '<前月', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '次月>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: '今日', currentStatus: '',
monthNames: ['1月','2月','3月','4月','5月','6月',
'7月','8月','9月','10月','11月','12月'],
monthNamesShort: ['1月','2月','3月','4月','5月','6月',
'7月','8月','9月','10月','11月','12月'],
monthStatus: '', yearStatus: '',
weekHeader: 'Wk', weekStatus: '',
dayNames: ['日','月','火','水','木','金','土'],
dayNamesShort: ['日','月','火','水','木','金','土'],
dayNamesMin: ['日','月','火','水','木','金','土'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy/mm/dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ja']);
}); | JavaScript |
/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
$.datepicker.regional['de'] = {
clearText: 'löschen', clearStatus: 'aktuelles Datum löschen',
closeText: 'schließen', closeStatus: 'ohne Änderungen schließen',
prevText: '<zurück', prevStatus: 'letzten Monat zeigen',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Vor>', nextStatus: 'nächsten Monat zeigen',
nextBigText: '>>', nextBigStatus: '',
currentText: 'heute', currentStatus: '',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
weekHeader: 'Wo', weekStatus: 'Woche des Monats',
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Wähle ein Datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['de']);
});
| JavaScript |
/* Hungarian initialisation for the jQuery UI date picker plugin. */
/* Written by Istvan Karaszi (jquerycalendar@spam.raszi.hu). */
jQuery(function($){
$.datepicker.regional['hu'] = {
clearText: 'törlés', clearStatus: '',
closeText: 'bezárás', closeStatus: '',
prevText: '« vissza', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'előre »', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'ma', currentStatus: '',
monthNames: ['Január', 'Február', 'Március', 'Április', 'Május', 'Június',
'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Már', 'Ápr', 'Máj', 'Jún',
'Júl', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Hé', weekStatus: '',
dayNames: ['Vasámap', 'Hétfö', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat'],
dayNamesShort: ['Vas', 'Hét', 'Ked', 'Sze', 'Csü', 'Pén', 'Szo'],
dayNamesMin: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hu']);
});
| JavaScript |
/* Latvian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas.paleicikas@metasite.net> */
jQuery(function($){
$.datepicker.regional['lv'] = {
clearText: 'Notīrīt', clearStatus: '',
closeText: 'Aizvērt', closeStatus: '',
prevText: 'Iepr', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nāka', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Šodien', currentStatus: '',
monthNames: ['Janvāris','Februāris','Marts','Aprīlis','Maijs','Jūnijs',
'Jūlijs','Augusts','Septembris','Oktobris','Novembris','Decembris'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jūn',
'Jūl','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Nav', weekStatus: '',
dayNames: ['svētdiena','pirmdiena','otrdiena','trešdiena','ceturtdiena','piektdiena','sestdiena'],
dayNamesShort: ['svt','prm','otr','tre','ctr','pkt','sst'],
dayNamesMin: ['Sv','Pr','Ot','Tr','Ct','Pk','Ss'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd-mm-yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['lv']);
}); | JavaScript |
/* Danish initialisation for the jQuery UI date picker plugin. */
/* Written by Jan Christensen ( deletestuff@gmail.com). */
jQuery(function($){
$.datepicker.regional['da'] = {
clearText: 'Nulstil', clearStatus: 'Nulstil den aktuelle dato',
closeText: 'Luk', closeStatus: 'Luk uden ændringer',
prevText: '<Forrige', prevStatus: 'Vis forrige måned',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Næste>', nextStatus: 'Vis næste måned',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Idag', currentStatus: 'Vis aktuel måned',
monthNames: ['Januar','Februar','Marts','April','Maj','Juni',
'Juli','August','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: 'Vis en anden måned', yearStatus: 'Vis et andet år',
weekHeader: 'Uge', weekStatus: 'Årets uge',
dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
dayStatus: 'Sæt DD som første ugedag', dateStatus: 'Vælg D, M d',
dateFormat: 'dd-mm-yy', firstDay: 0,
initStatus: 'Vælg en dato', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['da']);
});
| JavaScript |
/* Armenian(UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Levon Zakaryan (levon.zakaryan@gmail.com)*/
jQuery(function($){
$.datepicker.regional['hy'] = {
clearText: 'Մաքրել', clearStatus: '',
closeText: 'Փակել', closeStatus: '',
prevText: '<Նախ.', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Հաջ.>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Այսօր', currentStatus: '',
monthNames: ['Հունվար','Փետրվար','Մարտ','Ապրիլ','Մայիս','Հունիս',
'Հուլիս','Օգոստոս','Սեպտեմբեր','Հոկտեմբեր','Նոյեմբեր','Դեկտեմբեր'],
monthNamesShort: ['Հունվ','Փետր','Մարտ','Ապր','Մայիս','Հունիս',
'Հուլ','Օգս','Սեպ','Հոկ','Նոյ','Դեկ'],
monthStatus: '', yearStatus: '',
weekHeader: 'ՇԲՏ', weekStatus: '',
dayNames: ['կիրակի','եկուշաբթի','երեքշաբթի','չորեքշաբթի','հինգշաբթի','ուրբաթ','շաբաթ'],
dayNamesShort: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
dayNamesMin: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hy']);
}); | JavaScript |
/* Polish initialisation for the jQuery UI date picker plugin. */
/* Written by Jacek Wysocki (jacek.wysocki@gmail.com). */
jQuery(function($){
$.datepicker.regional['pl'] = {
clearText: 'Wyczyść', clearStatus: 'Wyczyść obecną datę',
closeText: 'Zamknij', closeStatus: 'Zamknij bez zapisywania',
prevText: '<Poprzedni', prevStatus: 'Pokaż poprzedni miesiąc',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Następny>', nextStatus: 'Pokaż następny miesiąc',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Dziś', currentStatus: 'Pokaż aktualny miesiąc',
monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
'Lip','Sie','Wrz','Pa','Lis','Gru'],
monthStatus: 'Pokaż inny miesiąc', yearStatus: 'Pokaż inny rok',
weekHeader: 'Tydz', weekStatus: 'Tydzień roku',
dayNames: ['Niedziela','Poniedzialek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
dayStatus: 'Ustaw DD jako pierwszy dzień tygodnia', dateStatus: 'Wybierz D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: 'Wybierz datę', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['pl']);
});
| JavaScript |
/* Bulgarian initialisation for the jQuery UI date picker plugin. */
/* Written by Stoyan Kyosev (http://svest.org). */
jQuery(function($){
$.datepicker.regional['bg'] = {
clearText: 'изчисти', clearStatus: 'изчисти актуалната дата',
closeText: 'затвори', closeStatus: 'затвори без промени',
prevText: '<назад', prevStatus: 'покажи последния месец',
prevBigText: '<<', prevBigStatus: '',
nextText: 'напред>', nextStatus: 'покажи следващия месец',
nextBigText: '>>', nextBigStatus: '',
currentText: 'днес', currentStatus: '',
monthNames: ['Януари','Февруари','Март','Април','Май','Юни',
'Юли','Август','Септември','Октомври','Ноември','Декември'],
monthNamesShort: ['Яну','Фев','Мар','Апр','Май','Юни',
'Юли','Авг','Сеп','Окт','Нов','Дек'],
monthStatus: 'покажи друг месец', yearStatus: 'покажи друга година',
weekHeader: 'Wk', weekStatus: 'седмица от месеца',
dayNames: ['Неделя','Понеделник','Вторник','Сряда','Четвъртък','Петък','Събота'],
dayNamesShort: ['Нед','Пон','Вто','Сря','Чет','Пет','Съб'],
dayNamesMin: ['Не','По','Вт','Ср','Че','Пе','Съ'],
dayStatus: 'Сложи DD като първи ден от седмицата', dateStatus: 'Избери D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Избери дата', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['bg']);
});
| JavaScript |
/* Turkish initialisation for the jQuery UI date picker plugin. */
/* Written by Izzet Emre Erkan (kara@karalamalar.net). */
jQuery(function($){
$.datepicker.regional['tr'] = {
clearText: 'temizle', clearStatus: 'geçerli tarihi temizler',
closeText: 'kapat', closeStatus: 'sadece göstergeyi kapat',
prevText: '<geri', prevStatus: 'önceki ayı göster',
prevBigText: '<<', prevBigStatus: '',
nextText: 'ileri>', nextStatus: 'sonraki ayı göster',
nextBigText: '>>', nextBigStatus: '',
currentText: 'bugün', currentStatus: '',
monthNames: ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran',
'Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'],
monthNamesShort: ['Oca','Şub','Mar','Nis','May','Haz',
'Tem','Ağu','Eyl','Eki','Kas','Ara'],
monthStatus: 'başka ay', yearStatus: 'başka yıl',
weekHeader: 'Hf', weekStatus: 'Ayın haftaları',
dayNames: ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'],
dayNamesShort: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
dayNamesMin: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
dayStatus: 'Haftanın ilk gününü belirleyin', dateStatus: 'D, M d seçiniz',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Bir tarih seçiniz', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['tr']);
}); | JavaScript |
/* Czech initialisation for the jQuery UI date picker plugin. */
/* Written by Tomas Muller (tomas@tomas-muller.net). */
jQuery(function($){
$.datepicker.regional['cs'] = {
clearText: 'Vymazat', clearStatus: 'Vymaže zadané datum',
closeText: 'Zavřít', closeStatus: 'Zavře kalendář beze změny',
prevText: '<Dříve', prevStatus: 'Přejít na předchozí měsí',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Později>', nextStatus: 'Přejít na další měsíc',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Nyní', currentStatus: 'Přejde na aktuální měsíc',
monthNames: ['leden','únor','březen','duben','květen','červen',
'červenec','srpen','září','říjen','listopad','prosinec'],
monthNamesShort: ['led','úno','bře','dub','kvě','čer',
'čvc','srp','zář','říj','lis','pro'],
monthStatus: 'Přejít na jiný měsíc', yearStatus: 'Přejít na jiný rok',
weekHeader: 'Týd', weekStatus: 'Týden v roce',
dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
dayNamesMin: ['ne','po','út','st','čt','pá','so'],
dayStatus: 'Nastavit DD jako první den v týdnu', dateStatus: '\'Vyber\' DD, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Vyberte datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['cs']);
});
| JavaScript |
/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@virginbroadband.com.au) and Stéphane Nahmani (sholby@sholby.net). */
jQuery(function($){
$.datepicker.regional['fr'] = {
clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
}); | JavaScript |
/* Ukrainian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Maxim Drogobitskiy (maxdao@gmail.com). */
jQuery(function($){
$.datepicker.regional['uk'] = {
clearText: 'Очистити', clearStatus: '',
closeText: 'Закрити', closeStatus: '',
prevText: '<', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Сьогодні', currentStatus: '',
monthNames: ['Січень','Лютий','Березень','Квітень','Травень','Червень',
'Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'],
monthNamesShort: ['Січ','Лют','Бер','Кві','Тра','Чер',
'Лип','Сер','Вер','Жов','Лис','Гру'],
monthStatus: '', yearStatus: '',
weekHeader: 'Не', weekStatus: '',
dayNames: ['неділя','понеділок','вівторок','середа','четвер','пятниця','суббота'],
dayNamesShort: ['нед','пнд','вів','срд','чтв','птн','сбт'],
dayNamesMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['uk']);
}); | JavaScript |
/* Arabic Translation for jQuery UI date picker plugin. */
/* Khaled Al Horani -- koko.dw@gmail.com */
/* خالد الحوراني -- koko.dw@gmail.com */
/* NOTE: monthNames are the original months names and they are the Arabic names, not the new months name فبراير - يناير and there isn't any Arabic roots for these months */
jQuery(function($){
$.datepicker.regional['ar'] = {
clearText: 'مسح', clearStatus: 'امسح التاريخ الحالي',
closeText: 'إغلاق', closeStatus: 'إغلاق بدون حفظ',
prevText: '<السابق', prevStatus: 'عرض الشهر السابق',
prevBigText: '<<', prevBigStatus: '',
nextText: 'التالي>', nextStatus: 'عرض الشهر القادم',
nextBigText: '>>', nextBigStatus: '',
currentText: 'اليوم', currentStatus: 'عرض الشهر الحالي',
monthNames: ['كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران',
'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول'],
monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
monthStatus: 'عرض شهر آخر', yearStatus: 'عرض سنة آخرى',
weekHeader: 'أسبوع', weekStatus: 'أسبوع السنة',
dayNames: ['السبت', 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة'],
dayNamesShort: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
dayNamesMin: ['سبت', 'أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة'],
dayStatus: 'اختر DD لليوم الأول من الأسبوع', dateStatus: 'اختر D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'اختر يوم', isRTL: true};
$.datepicker.setDefaults($.datepicker.regional['ar']);
});/* Bulgarian initialisation for the jQuery UI date picker plugin. */
/* Written by Stoyan Kyosev (http://svest.org). */
jQuery(function($){
$.datepicker.regional['bg'] = {
clearText: 'изчисти', clearStatus: 'изчисти актуалната дата',
closeText: 'затвори', closeStatus: 'затвори без промени',
prevText: '<назад', prevStatus: 'покажи последния месец',
prevBigText: '<<', prevBigStatus: '',
nextText: 'напред>', nextStatus: 'покажи следващия месец',
nextBigText: '>>', nextBigStatus: '',
currentText: 'днес', currentStatus: '',
monthNames: ['Януари','Февруари','Март','Април','Май','Юни',
'Юли','Август','Септември','Октомври','Ноември','Декември'],
monthNamesShort: ['Яну','Фев','Мар','Апр','Май','Юни',
'Юли','Авг','Сеп','Окт','Нов','Дек'],
monthStatus: 'покажи друг месец', yearStatus: 'покажи друга година',
weekHeader: 'Wk', weekStatus: 'седмица от месеца',
dayNames: ['Неделя','Понеделник','Вторник','Сряда','Четвъртък','Петък','Събота'],
dayNamesShort: ['Нед','Пон','Вто','Сря','Чет','Пет','Съб'],
dayNamesMin: ['Не','По','Вт','Ср','Че','Пе','Съ'],
dayStatus: 'Сложи DD като първи ден от седмицата', dateStatus: 'Избери D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Избери дата', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['bg']);
});
/* Inicialitzaci� en catal� per a l'extenci� 'calendar' per jQuery. */
/* Writers: (joan.leon@gmail.com). */
jQuery(function($){
$.datepicker.regional['ca'] = {
clearText: 'Netejar', clearStatus: '',
closeText: 'Tancar', closeStatus: '',
prevText: '<Ant', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Seg>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Avui', currentStatus: '',
monthNames: ['Gener','Febrer','Març','Abril','Maig','Juny',
'Juliol','Agost','Setembre','Octubre','Novembre','Desembre'],
monthNamesShort: ['Gen','Feb','Mar','Abr','Mai','Jun',
'Jul','Ago','Set','Oct','Nov','Des'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Diumenge','Dilluns','Dimarts','Dimecres','Dijous','Divendres','Dissabte'],
dayNamesShort: ['Dug','Dln','Dmt','Dmc','Djs','Dvn','Dsb'],
dayNamesMin: ['Dg','Dl','Dt','Dc','Dj','Dv','Ds'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'mm/dd/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ca']);
});/* Czech initialisation for the jQuery UI date picker plugin. */
/* Written by Tomas Muller (tomas@tomas-muller.net). */
jQuery(function($){
$.datepicker.regional['cs'] = {
clearText: 'Vymazat', clearStatus: 'Vymaže zadané datum',
closeText: 'Zavřít', closeStatus: 'Zavře kalendář beze změny',
prevText: '<Dříve', prevStatus: 'Přejít na předchozí měsí',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Později>', nextStatus: 'Přejít na další měsíc',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Nyní', currentStatus: 'Přejde na aktuální měsíc',
monthNames: ['leden','únor','březen','duben','květen','červen',
'červenec','srpen','září','říjen','listopad','prosinec'],
monthNamesShort: ['led','úno','bře','dub','kvě','čer',
'čvc','srp','zář','říj','lis','pro'],
monthStatus: 'Přejít na jiný měsíc', yearStatus: 'Přejít na jiný rok',
weekHeader: 'Týd', weekStatus: 'Týden v roce',
dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
dayNamesMin: ['ne','po','út','st','čt','pá','so'],
dayStatus: 'Nastavit DD jako první den v týdnu', dateStatus: '\'Vyber\' DD, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Vyberte datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['cs']);
});
/* Danish initialisation for the jQuery UI date picker plugin. */
/* Written by Jan Christensen ( deletestuff@gmail.com). */
jQuery(function($){
$.datepicker.regional['da'] = {
clearText: 'Nulstil', clearStatus: 'Nulstil den aktuelle dato',
closeText: 'Luk', closeStatus: 'Luk uden ændringer',
prevText: '<Forrige', prevStatus: 'Vis forrige måned',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Næste>', nextStatus: 'Vis næste måned',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Idag', currentStatus: 'Vis aktuel måned',
monthNames: ['Januar','Februar','Marts','April','Maj','Juni',
'Juli','August','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: 'Vis en anden måned', yearStatus: 'Vis et andet år',
weekHeader: 'Uge', weekStatus: 'Årets uge',
dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
dayStatus: 'Sæt DD som første ugedag', dateStatus: 'Vælg D, M d',
dateFormat: 'dd-mm-yy', firstDay: 0,
initStatus: 'Vælg en dato', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['da']);
});
/* German initialisation for the jQuery UI date picker plugin. */
/* Written by Milian Wolff (mail@milianw.de). */
jQuery(function($){
$.datepicker.regional['de'] = {
clearText: 'löschen', clearStatus: 'aktuelles Datum löschen',
closeText: 'schließen', closeStatus: 'ohne Änderungen schließen',
prevText: '<zurück', prevStatus: 'letzten Monat zeigen',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Vor>', nextStatus: 'nächsten Monat zeigen',
nextBigText: '>>', nextBigStatus: '',
currentText: 'heute', currentStatus: '',
monthNames: ['Januar','Februar','März','April','Mai','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Dez'],
monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
weekHeader: 'Wo', weekStatus: 'Woche des Monats',
dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Wähle ein Datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['de']);
});
/* Esperanto initialisation for the jQuery UI date picker plugin. */
/* Written by Olivier M. (olivierweb@ifrance.com). */
jQuery(function($){
$.datepicker.regional['eo'] = {
clearText: 'Vakigi', clearStatus: '',
closeText: 'Fermi', closeStatus: 'Fermi sen modifi',
prevText: '<Anta', prevStatus: 'Vidi la antaŭan monaton',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Sekv>', nextStatus: 'Vidi la sekvan monaton',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Nuna', currentStatus: 'Vidi la nunan monaton',
monthNames: ['Januaro','Februaro','Marto','Aprilo','Majo','Junio',
'Julio','Aŭgusto','Septembro','Oktobro','Novembro','Decembro'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aŭg','Sep','Okt','Nov','Dec'],
monthStatus: 'Vidi alian monaton', yearStatus: 'Vidi alian jaron',
weekHeader: 'Sb', weekStatus: '',
dayNames: ['Dimanĉo','Lundo','Mardo','Merkredo','Ĵaŭdo','Vendredo','Sabato'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Ĵaŭ','Ven','Sab'],
dayNamesMin: ['Di','Lu','Ma','Me','Ĵa','Ve','Sa'],
dayStatus: 'Uzi DD kiel unua tago de la semajno', dateStatus: 'Elekti DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Elekti la daton', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['eo']);
});
/* Inicializaci�n en espa�ol para la extensi�n 'UI date picker' para jQuery. */
/* Traducido por Vester (xvester@gmail.com). */
jQuery(function($){
$.datepicker.regional['es'] = {
clearText: 'Limpiar', clearStatus: '',
closeText: 'Cerrar', closeStatus: '',
prevText: '<Ant', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Sig>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Hoy', currentStatus: '',
monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
'Jul','Ago','Sep','Oct','Nov','Dic'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sádabo'],
dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['es']);
});/* Finnish initialisation for the jQuery UI date picker plugin. */
/* Written by Harri Kilpi� (harrikilpio@gmail.com). */
jQuery(function($){
$.datepicker.regional['fi'] = {
clearText: 'Tyhjennä', clearStatus: '',
closeText: 'Sulje', closeStatus: '',
prevText: '«Edellinen', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Seuraava»', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Tänään', currentStatus: '',
monthNames: ['Tammikuu','Helmikuu','Maaliskuu','Huhtikuu','Toukokuu','Kesäkuu',
'Heinäkuu','Elokuu','Syyskuu','Lokakuu','Marraskuu','Joulukuu'],
monthNamesShort: ['Tammi','Helmi','Maalis','Huhti','Touko','Kesä',
'Heinä','Elo','Syys','Loka','Marras','Joulu'],
monthStatus: '', yearStatus: '',
weekHeader: 'Vk', weekStatus: '',
dayNamesShort: ['Su','Ma','Ti','Ke','To','Pe','Su'],
dayNames: ['Sunnuntai','Maanantai','Tiistai','Keskiviikko','Torstai','Perjantai','Lauantai'],
dayNamesMin: ['Su','Ma','Ti','Ke','To','Pe','La'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fi']);
});
/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood@virginbroadband.com.au) and Stéphane Nahmani (sholby@sholby.net). */
jQuery(function($){
$.datepicker.regional['fr'] = {
clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
});/* Hebrew initialisation for the UI Datepicker extension. */
/* Written by Amir Hardon (ahardon at gmail dot com). */
jQuery(function($){
$.datepicker.regional['he'] = {
clearText: 'נקה', clearStatus: '',
closeText: 'סגור', closeStatus: '',
prevText: '<הקודם', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'הבא>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'היום', currentStatus: '',
monthNames: ['ינואר','פברואר','מרץ','אפריל','מאי','יוני',
'יולי','אוגוסט','ספטמבר','אוקטובר','נובמבר','דצמבר'],
monthNamesShort: ['1','2','3','4','5','6',
'7','8','9','10','11','12'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
dayStatus: 'DD', dateStatus: 'DD, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: true};
$.datepicker.setDefaults($.datepicker.regional['he']);
});
/* Croatian i18n for the jQuery UI date picker plugin. */
/* Written by Vjekoslav Nesek. */
jQuery(function($){
$.datepicker.regional['hr'] = {
clearText: 'izbriši', clearStatus: 'Izbriši trenutni datum',
closeText: 'Zatvori', closeStatus: 'Zatvori kalendar',
prevText: '<', prevStatus: 'Prikaži prethodni mjesec',
prevBigText: '<<', prevBigStatus: '',
nextText: '>', nextStatus: 'Prikaži slijedeći mjesec',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Danas', currentStatus: 'Današnji datum',
monthNames: ['Siječanj','Veljača','Ožujak','Travanj','Svibanj','Lipani',
'Srpanj','Kolovoz','Rujan','Listopad','Studeni','Prosinac'],
monthNamesShort: ['Sij','Velj','Ožu','Tra','Svi','Lip',
'Srp','Kol','Ruj','Lis','Stu','Pro'],
monthStatus: 'Prikaži mjesece', yearStatus: 'Prikaži godine',
weekHeader: 'Tje', weekStatus: 'Tjedan',
dayNames: ['Nedjalja','Ponedjeljak','Utorak','Srijeda','Četvrtak','Petak','Subota'],
dayNamesShort: ['Ned','Pon','Uto','Sri','Čet','Pet','Sub'],
dayNamesMin: ['Ne','Po','Ut','Sr','Če','Pe','Su'],
dayStatus: 'Odaber DD za prvi dan tjedna', dateStatus: '\'Datum\' D, M d',
dateFormat: 'dd.mm.yy.', firstDay: 1,
initStatus: 'Odaberi datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hr']);
});/* Hungarian initialisation for the jQuery UI date picker plugin. */
/* Written by Istvan Karaszi (jquerycalendar@spam.raszi.hu). */
jQuery(function($){
$.datepicker.regional['hu'] = {
clearText: 'törlés', clearStatus: '',
closeText: 'bezárás', closeStatus: '',
prevText: '« vissza', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'előre »', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'ma', currentStatus: '',
monthNames: ['Január', 'Február', 'Március', 'Április', 'Május', 'Június',
'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Már', 'Ápr', 'Máj', 'Jún',
'Júl', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Hé', weekStatus: '',
dayNames: ['Vasámap', 'Hétfö', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat'],
dayNamesShort: ['Vas', 'Hét', 'Ked', 'Sze', 'Csü', 'Pén', 'Szo'],
dayNamesMin: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hu']);
});
/* Armenian(UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Levon Zakaryan (levon.zakaryan@gmail.com)*/
jQuery(function($){
$.datepicker.regional['hy'] = {
clearText: 'Մաքրել', clearStatus: '',
closeText: 'Փակել', closeStatus: '',
prevText: '<Նախ.', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Հաջ.>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Այսօր', currentStatus: '',
monthNames: ['Հունվար','Փետրվար','Մարտ','Ապրիլ','Մայիս','Հունիս',
'Հուլիս','Օգոստոս','Սեպտեմբեր','Հոկտեմբեր','Նոյեմբեր','Դեկտեմբեր'],
monthNamesShort: ['Հունվ','Փետր','Մարտ','Ապր','Մայիս','Հունիս',
'Հուլ','Օգս','Սեպ','Հոկ','Նոյ','Դեկ'],
monthStatus: '', yearStatus: '',
weekHeader: 'ՇԲՏ', weekStatus: '',
dayNames: ['կիրակի','եկուշաբթի','երեքշաբթի','չորեքշաբթի','հինգշաբթի','ուրբաթ','շաբաթ'],
dayNamesShort: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
dayNamesMin: ['կիր','երկ','երք','չրք','հնգ','ուրբ','շբթ'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['hy']);
});/* Indonesian initialisation for the jQuery UI date picker plugin. */
/* Written by Deden Fathurahman (dedenf@gmail.com). */
jQuery(function($){
$.datepicker.regional['id'] = {
clearText: 'kosongkan', clearStatus: 'bersihkan tanggal yang sekarang',
closeText: 'Tutup', closeStatus: 'Tutup tanpa mengubah',
prevText: '<mundur', prevStatus: 'Tampilkan bulan sebelumnya',
prevBigText: '<<', prevBigStatus: '',
nextText: 'maju>', nextStatus: 'Tampilkan bulan berikutnya',
nextBigText: '>>', nextBigStatus: '',
currentText: 'hari ini', currentStatus: 'Tampilkan bulan sekarang',
monthNames: ['Januari','Februari','Maret','April','Mei','Juni',
'Juli','Agustus','September','Oktober','Nopember','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun',
'Jul','Agus','Sep','Okt','Nop','Des'],
monthStatus: 'Tampilkan bulan yang berbeda', yearStatus: 'Tampilkan tahun yang berbeda',
weekHeader: 'Mg', weekStatus: 'Minggu dalam tahun',
dayNames: ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'],
dayNamesShort: ['Min','Sen','Sel','Rab','kam','Jum','Sab'],
dayNamesMin: ['Mg','Sn','Sl','Rb','Km','jm','Sb'],
dayStatus: 'gunakan DD sebagai awal hari dalam minggu', dateStatus: 'pilih le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Pilih Tanggal', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['id']);
});/* Icelandic initialisation for the jQuery UI date picker plugin. */
/* Written by Haukur H. Thorsson (haukur@eskill.is). */
jQuery(function($){
$.datepicker.regional['is'] = {
clearText: 'Hreinsa', clearStatus: '',
closeText: 'Loka', closeStatus: '',
prevText: '< Fyrri', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Næsti >', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Í dag', currentStatus: '',
monthNames: ['Janúar','Febrúar','Mars','Apríl','Maí','Júní',
'Júlí','Ágúst','September','Október','Nóvember','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maí','Jún',
'Júl','Ágú','Sep','Okt','Nóv','Des'],
monthStatus: '', yearStatus: '',
weekHeader: 'Vika', weekStatus: '',
dayNames: ['Sunnudagur','Mánudagur','Þriðjudagur','Miðvikudagur','Fimmtudagur','Föstudagur','Laugardagur'],
dayNamesShort: ['Sun','Mán','Þri','Mið','Fim','Fös','Lau'],
dayNamesMin: ['Su','Má','Þr','Mi','Fi','Fö','La'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['is']);
});/* Italian initialisation for the jQuery UI date picker plugin. */
/* Written by Apaella (apaella@gmail.com). */
jQuery(function($){
$.datepicker.regional['it'] = {
clearText: 'Svuota', clearStatus: 'Annulla',
closeText: 'Chiudi', closeStatus: 'Chiudere senza modificare',
prevText: '<Prec', prevStatus: 'Mese precedente',
prevBigText: '<<', prevBigStatus: 'Mostra l\'anno precedente',
nextText: 'Succ>', nextStatus: 'Mese successivo',
nextBigText: '>>', nextBigStatus: 'Mostra l\'anno successivo',
currentText: 'Oggi', currentStatus: 'Mese corrente',
monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
'Lug','Ago','Set','Ott','Nov','Dic'],
monthStatus: 'Seleziona un altro mese', yearStatus: 'Seleziona un altro anno',
weekHeader: 'Sm', weekStatus: 'Settimana dell\'anno',
dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'],
dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'],
dayStatus: 'Usa DD come primo giorno della settimana', dateStatus: 'Seleziona D, M d',
dateFormat: 'dd/mm/yy', firstDay: 1,
initStatus: 'Scegliere una data', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['it']);
});
/* Japanese (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Milly. */
jQuery(function($){
$.datepicker.regional['ja'] = {
clearText: '削除', clearStatus: '',
closeText: '閉じる', closeStatus: '',
prevText: '<前月', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '次月>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: '今日', currentStatus: '',
monthNames: ['1月','2月','3月','4月','5月','6月',
'7月','8月','9月','10月','11月','12月'],
monthNamesShort: ['1月','2月','3月','4月','5月','6月',
'7月','8月','9月','10月','11月','12月'],
monthStatus: '', yearStatus: '',
weekHeader: 'Wk', weekStatus: '',
dayNames: ['日','月','火','水','木','金','土'],
dayNamesShort: ['日','月','火','水','木','金','土'],
dayNamesMin: ['日','月','火','水','木','金','土'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy/mm/dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ja']);
});/* Korean initialisation for the jQuery calendar extension. */
/* Written by DaeKwon Kang (ncrash.dk@gmail.com). */
jQuery(function($){
$.datepicker.regional['ko'] = {
clearText: '지우기', clearStatus: '',
closeText: '닫기', closeStatus: '',
prevText: '이전달', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '다음달', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: '오늘', currentStatus: '',
monthNames: ['1월(JAN)','2월(FEB)','3월(MAR)','4월(APR)','5월(MAY)','6월(JUN)',
'7월(JUL)','8월(AUG)','9월(SEP)','10월(OCT)','11월(NOV)','12월(DEC)'],
monthNamesShort: ['1월(JAN)','2월(FEB)','3월(MAR)','4월(APR)','5월(MAY)','6월(JUN)',
'7월(JUL)','8월(AUG)','9월(SEP)','10월(OCT)','11월(NOV)','12월(DEC)'],
monthStatus: '', yearStatus: '',
weekHeader: 'Wk', weekStatus: '',
dayNames: ['일','월','화','수','목','금','토'],
dayNamesShort: ['일','월','화','수','목','금','토'],
dayNamesMin: ['일','월','화','수','목','금','토'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ko']);
});/* Lithuanian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas@avalon.lt> */
jQuery(function($){
$.datepicker.regional['lt'] = {
clearText: 'Išvalyti', clearStatus: '',
closeText: 'Uždaryti', closeStatus: '',
prevText: '<Atgal', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Pirmyn>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Šiandien', currentStatus: '',
monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis',
'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'],
monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir',
'Lie','Rugp','Rugs','Spa','Lap','Gru'],
monthStatus: '', yearStatus: '',
weekHeader: '', weekStatus: '',
dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'],
dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'],
dayNamesMin: ['Se','Pr','An','Tr','Ke','Pe','Še'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['lt']);
});/* Latvian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas.paleicikas@metasite.net> */
jQuery(function($){
$.datepicker.regional['lv'] = {
clearText: 'Notīrīt', clearStatus: '',
closeText: 'Aizvērt', closeStatus: '',
prevText: 'Iepr', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nāka', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Šodien', currentStatus: '',
monthNames: ['Janvāris','Februāris','Marts','Aprīlis','Maijs','Jūnijs',
'Jūlijs','Augusts','Septembris','Oktobris','Novembris','Decembris'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jūn',
'Jūl','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Nav', weekStatus: '',
dayNames: ['svētdiena','pirmdiena','otrdiena','trešdiena','ceturtdiena','piektdiena','sestdiena'],
dayNamesShort: ['svt','prm','otr','tre','ctr','pkt','sst'],
dayNamesMin: ['Sv','Pr','Ot','Tr','Ct','Pk','Ss'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd-mm-yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['lv']);
});/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by ??? */
jQuery(function($){
$.datepicker.regional['nl'] = {
clearText: 'Wissen', clearStatus: 'Wis de huidige datum',
closeText: 'Sluiten', closeStatus: 'Sluit zonder verandering',
prevText: '<Terug', prevStatus: 'Laat de voorgaande maand zien',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Volgende>', nextStatus: 'Laat de volgende maand zien',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Vandaag', currentStatus: 'Laat de huidige maand zien',
monthNames: ['Januari','Februari','Maart','April','Mei','Juni',
'Juli','Augustus','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mrt','Apr','Mei','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: 'Laat een andere maand zien', yearStatus: 'Laat een ander jaar zien',
weekHeader: 'Wk', weekStatus: 'Week van het jaar',
dayNames: ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag','Zaterdag'],
dayNamesShort: ['Zon','Maa','Din','Woe','Don','Vri','Zat'],
dayNamesMin: ['Zo','Ma','Di','Wo','Do','Vr','Za'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Kies een datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['nl']);
});/* Norwegian initialisation for the jQuery UI date picker plugin. */
/* Written by Naimdjon Takhirov (naimdjon@gmail.com). */
jQuery(function($){
$.datepicker.regional['no'] = {
clearText: 'Tøm', clearStatus: '',
closeText: 'Lukk', closeStatus: '',
prevText: '«Forrige', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Neste»', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'I dag', currentStatus: '',
monthNames: ['Januar','Februar','Mars','April','Mai','Juni',
'Juli','August','September','Oktober','November','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun',
'Jul','Aug','Sep','Okt','Nov','Des'],
monthStatus: '', yearStatus: '',
weekHeader: 'Uke', weekStatus: '',
dayNamesShort: ['Søn','Man','Tir','Ons','Tor','Fre','Lør'],
dayNames: ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'],
dayNamesMin: ['Sø','Ma','Ti','On','To','Fr','Lø'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['no']);
});
/* Polish initialisation for the jQuery UI date picker plugin. */
/* Written by Jacek Wysocki (jacek.wysocki@gmail.com). */
jQuery(function($){
$.datepicker.regional['pl'] = {
clearText: 'Wyczyść', clearStatus: 'Wyczyść obecną datę',
closeText: 'Zamknij', closeStatus: 'Zamknij bez zapisywania',
prevText: '<Poprzedni', prevStatus: 'Pokaż poprzedni miesiąc',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Następny>', nextStatus: 'Pokaż następny miesiąc',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Dziś', currentStatus: 'Pokaż aktualny miesiąc',
monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
'Lip','Sie','Wrz','Pa','Lis','Gru'],
monthStatus: 'Pokaż inny miesiąc', yearStatus: 'Pokaż inny rok',
weekHeader: 'Tydz', weekStatus: 'Tydzień roku',
dayNames: ['Niedziela','Poniedzialek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
dayStatus: 'Ustaw DD jako pierwszy dzień tygodnia', dateStatus: 'Wybierz D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: 'Wybierz datę', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['pl']);
});
/* Brazilian initialisation for the jQuery UI date picker plugin. */
/* Written by Leonildo Costa Silva (leocsilva@gmail.com). */
jQuery(function($){
$.datepicker.regional['pt-BR'] = {
clearText: 'Limpar', clearStatus: '',
closeText: 'Fechar', closeStatus: '',
prevText: '<Anterior', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Próximo>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Hoje', currentStatus: '',
monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho',
'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
'Jul','Ago','Set','Out','Nov','Dez'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['pt-BR']);
});/* Romanian initialisation for the jQuery UI date picker plugin. */
/* Written by Edmond L. (ll_edmond@walla.com). */
jQuery(function($){
$.datepicker.regional['ro'] = {
clearText: 'Curat', clearStatus: 'Sterge data curenta',
closeText: 'Inchide', closeStatus: 'Inchide fara schimbare',
prevText: '<Anterior', prevStatus: 'Arata luna trecuta',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Urmator>', nextStatus: 'Arata luna urmatoare',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Azi', currentStatus: 'Arata luna curenta',
monthNames: ['Ianuarie','Februarie','Martie','Aprilie','Mai','Junie',
'Julie','August','Septembrie','Octobrie','Noiembrie','Decembrie'],
monthNamesShort: ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'],
monthStatus: 'Arata o luna diferita', yearStatus: 'Arat un an diferit',
weekHeader: 'Sapt', weekStatus: 'Saptamana anului',
dayNames: ['Duminica', 'Luni', 'Marti', 'Miercuri', 'Joi', 'Vineri', 'Sambata'],
dayNamesShort: ['Dum', 'Lun', 'Mar', 'Mie', 'Joi', 'Vin', 'Sam'],
dayNamesMin: ['Du','Lu','Ma','Mi','Jo','Vi','Sa'],
dayStatus: 'Seteaza DD ca prima saptamana zi', dateStatus: 'Selecteaza D, M d',
dateFormat: 'mm/dd/yy', firstDay: 0,
initStatus: 'Selecteaza o data', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ro']);
});
/* Russian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Andrew Stromnov (stromnov@gmail.com). */
jQuery(function($){
$.datepicker.regional['ru'] = {
clearText: 'Очистить', clearStatus: '',
closeText: 'Закрыть', closeStatus: '',
prevText: '<Пред', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'След>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Сегодня', currentStatus: '',
monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
'Июл','Авг','Сен','Окт','Ноя','Дек'],
monthStatus: '', yearStatus: '',
weekHeader: 'Не', weekStatus: '',
dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ru']);
});/* Slovak initialisation for the jQuery UI date picker plugin. */
/* Written by Vojtech Rinik (vojto@hmm.sk). */
jQuery(function($){
$.datepicker.regional['sk'] = {
clearText: 'Zmazať', clearStatus: '',
closeText: 'Zavrieť', closeStatus: '',
prevText: '<Predchádzajúci', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nasledujúci>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Dnes', currentStatus: '',
monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
'Júl','August','September','Október','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Máj','Jún',
'Júl','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Ty', weekStatus: '',
dayNames: ['Nedel\'a','Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota'],
dayNamesShort: ['Ned','Pon','Uto','Str','Štv','Pia','Sob'],
dayNamesMin: ['Ne','Po','Ut','St','Št','Pia','So'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sk']);
});
/* Slovenian initialisation for the jQuery UI date picker plugin. */
/* Written by Jaka Jancar (jaka@kubje.org). */
/* c = č, s = š z = ž C = Č S = Š Z = Ž */
jQuery(function($){
$.datepicker.regional['sl'] = {clearText: 'Izbriši', clearStatus: 'Izbriši trenutni datum',
closeText: 'Zapri', closeStatus: 'Zapri brez spreminjanja',
prevText: '<Prejšnji', prevStatus: 'Prikaži prejšnji mesec',
nextText: 'Naslednji>', nextStatus: 'Prikaži naslednji mesec',
currentText: 'Trenutni', currentStatus: 'Prikaži trenutni mesec',
monthNames: ['Januar','Februar','Marec','April','Maj','Junij',
'Julij','Avgust','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Avg','Sep','Okt','Nov','Dec'],
monthStatus: 'Prikaži drug mesec', yearStatus: 'Prikaži drugo leto',
weekHeader: 'Teden', weekStatus: 'Teden v letu',
dayNames: ['Nedelja','Ponedeljek','Torek','Sreda','Četrtek','Petek','Sobota'],
dayNamesShort: ['Ned','Pon','Tor','Sre','Čet','Pet','Sob'],
dayNamesMin: ['Ne','Po','To','Sr','Če','Pe','So'],
dayStatus: 'Nastavi DD za prvi dan v tednu', dateStatus: 'Izberi DD, d MM yy',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Izbira datuma', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sl']);
});
/* Swedish initialisation for the jQuery UI date picker plugin. */
/* Written by Anders Ekdahl ( anders@nomadiz.se). */
jQuery(function($){
$.datepicker.regional['sv'] = {
clearText: 'Rensa', clearStatus: '',
closeText: 'Stäng', closeStatus: '',
prevText: '«Förra', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Nästa»', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Idag', currentStatus: '',
monthNames: ['Januari','Februari','Mars','April','Maj','Juni',
'Juli','Augusti','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Aug','Sep','Okt','Nov','Dec'],
monthStatus: '', yearStatus: '',
weekHeader: 'Ve', weekStatus: '',
dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['sv']);
});
/* Thai initialisation for the jQuery UI date picker plugin. */
/* Written by pipo (pipo@sixhead.com). */
jQuery(function($){
$.datepicker.regional['th'] = {
clearText: 'ลบ', clearStatus: '',
closeText: 'ปิด', closeStatus: '',
prevText: '« ย้อน', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'ถัดไป »', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'วันนี้', currentStatus: '',
monthNames: ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน',
'กรกฏาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'],
monthNamesShort: ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.',
'ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'],
monthStatus: '', yearStatus: '',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'],
dayNamesShort: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
dayNamesMin: ['อา.','จ.','อ.','พ.','พฤ.','ศ.','ส.'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['th']);
});/* Turkish initialisation for the jQuery UI date picker plugin. */
/* Written by Izzet Emre Erkan (kara@karalamalar.net). */
jQuery(function($){
$.datepicker.regional['tr'] = {
clearText: 'temizle', clearStatus: 'geçerli tarihi temizler',
closeText: 'kapat', closeStatus: 'sadece göstergeyi kapat',
prevText: '<geri', prevStatus: 'önceki ayı göster',
prevBigText: '<<', prevBigStatus: '',
nextText: 'ileri>', nextStatus: 'sonraki ayı göster',
nextBigText: '>>', nextBigStatus: '',
currentText: 'bugün', currentStatus: '',
monthNames: ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran',
'Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'],
monthNamesShort: ['Oca','Şub','Mar','Nis','May','Haz',
'Tem','Ağu','Eyl','Eki','Kas','Ara'],
monthStatus: 'başka ay', yearStatus: 'başka yıl',
weekHeader: 'Hf', weekStatus: 'Ayın haftaları',
dayNames: ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'],
dayNamesShort: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
dayNamesMin: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
dayStatus: 'Haftanın ilk gününü belirleyin', dateStatus: 'D, M d seçiniz',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: 'Bir tarih seçiniz', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['tr']);
});/* Ukrainian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Maxim Drogobitskiy (maxdao@gmail.com). */
jQuery(function($){
$.datepicker.regional['uk'] = {
clearText: 'Очистити', clearStatus: '',
closeText: 'Закрити', closeStatus: '',
prevText: '<', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Сьогодні', currentStatus: '',
monthNames: ['Січень','Лютий','Березень','Квітень','Травень','Червень',
'Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'],
monthNamesShort: ['Січ','Лют','Бер','Кві','Тра','Чер',
'Лип','Сер','Вер','Жов','Лис','Гру'],
monthStatus: '', yearStatus: '',
weekHeader: 'Не', weekStatus: '',
dayNames: ['неділя','понеділок','вівторок','середа','четвер','пятниця','суббота'],
dayNamesShort: ['нед','пнд','вів','срд','чтв','птн','сбт'],
dayNamesMin: ['Нд','Пн','Вт','Ср','Чт','Пт','Сб'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd.mm.yy', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['uk']);
});/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Cloudream (cloudream@gmail.com). */
jQuery(function($){
$.datepicker.regional['zh-CN'] = {
clearText: '清除', clearStatus: '清除已选日期',
closeText: '关闭', closeStatus: '不改变当前选择',
prevText: '<上月', prevStatus: '显示上月',
prevBigText: '<<', prevBigStatus: '显示上一年',
nextText: '下月>', nextStatus: '显示下月',
nextBigText: '>>', nextBigStatus: '显示下一年',
currentText: '今天', currentStatus: '显示本月',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
monthStatus: '选择月份', yearStatus: '选择年份',
weekHeader: '周', weekStatus: '年内周次',
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
dayStatus: '设置 DD 为一周起始', dateStatus: '选择 m月 d日, DD',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '请选择日期', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});
/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Ressol (ressol@gmail.com). */
jQuery(function($){
$.datepicker.regional['zh-TW'] = {
clearText: '清除', clearStatus: '清除已選日期',
closeText: '關閉', closeStatus: '不改變目前的選擇',
prevText: '<上月', prevStatus: '顯示上月',
prevBigText: '<<', prevBigStatus: '顯示上一年',
nextText: '下月>', nextStatus: '顯示下月',
nextBigText: '>>', nextBigStatus: '顯示下一年',
currentText: '今天', currentStatus: '顯示本月',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
monthStatus: '選擇月份', yearStatus: '選擇年份',
weekHeader: '周', weekStatus: '年內周次',
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
dayStatus: '設定 DD 為一周起始', dateStatus: '選擇 m月 d日, DD',
dateFormat: 'yy/mm/dd', firstDay: 1,
initStatus: '請選擇日期', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-TW']);
});
| JavaScript |
/* Indonesian initialisation for the jQuery UI date picker plugin. */
/* Written by Deden Fathurahman (dedenf@gmail.com). */
jQuery(function($){
$.datepicker.regional['id'] = {
clearText: 'kosongkan', clearStatus: 'bersihkan tanggal yang sekarang',
closeText: 'Tutup', closeStatus: 'Tutup tanpa mengubah',
prevText: '<mundur', prevStatus: 'Tampilkan bulan sebelumnya',
prevBigText: '<<', prevBigStatus: '',
nextText: 'maju>', nextStatus: 'Tampilkan bulan berikutnya',
nextBigText: '>>', nextBigStatus: '',
currentText: 'hari ini', currentStatus: 'Tampilkan bulan sekarang',
monthNames: ['Januari','Februari','Maret','April','Mei','Juni',
'Juli','Agustus','September','Oktober','Nopember','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun',
'Jul','Agus','Sep','Okt','Nop','Des'],
monthStatus: 'Tampilkan bulan yang berbeda', yearStatus: 'Tampilkan tahun yang berbeda',
weekHeader: 'Mg', weekStatus: 'Minggu dalam tahun',
dayNames: ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'],
dayNamesShort: ['Min','Sen','Sel','Rab','kam','Jum','Sab'],
dayNamesMin: ['Mg','Sn','Sl','Rb','Km','jm','Sb'],
dayStatus: 'gunakan DD sebagai awal hari dalam minggu', dateStatus: 'pilih le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Pilih Tanggal', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['id']);
}); | JavaScript |
/* Korean initialisation for the jQuery calendar extension. */
/* Written by DaeKwon Kang (ncrash.dk@gmail.com). */
jQuery(function($){
$.datepicker.regional['ko'] = {
clearText: '지우기', clearStatus: '',
closeText: '닫기', closeStatus: '',
prevText: '이전달', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: '다음달', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: '오늘', currentStatus: '',
monthNames: ['1월(JAN)','2월(FEB)','3월(MAR)','4월(APR)','5월(MAY)','6월(JUN)',
'7월(JUL)','8월(AUG)','9월(SEP)','10월(OCT)','11월(NOV)','12월(DEC)'],
monthNamesShort: ['1월(JAN)','2월(FEB)','3월(MAR)','4월(APR)','5월(MAY)','6월(JUN)',
'7월(JUL)','8월(AUG)','9월(SEP)','10월(OCT)','11월(NOV)','12월(DEC)'],
monthStatus: '', yearStatus: '',
weekHeader: 'Wk', weekStatus: '',
dayNames: ['일','월','화','수','목','금','토'],
dayNamesShort: ['일','월','화','수','목','금','토'],
dayNamesMin: ['일','월','화','수','목','금','토'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['ko']);
}); | JavaScript |
/* Icelandic initialisation for the jQuery UI date picker plugin. */
/* Written by Haukur H. Thorsson (haukur@eskill.is). */
jQuery(function($){
$.datepicker.regional['is'] = {
clearText: 'Hreinsa', clearStatus: '',
closeText: 'Loka', closeStatus: '',
prevText: '< Fyrri', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Næsti >', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Í dag', currentStatus: '',
monthNames: ['Janúar','Febrúar','Mars','Apríl','Maí','Júní',
'Júlí','Ágúst','September','Október','Nóvember','Desember'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maí','Jún',
'Júl','Ágú','Sep','Okt','Nóv','Des'],
monthStatus: '', yearStatus: '',
weekHeader: 'Vika', weekStatus: '',
dayNames: ['Sunnudagur','Mánudagur','Þriðjudagur','Miðvikudagur','Fimmtudagur','Föstudagur','Laugardagur'],
dayNamesShort: ['Sun','Mán','Þri','Mið','Fim','Fös','Lau'],
dayNamesMin: ['Su','Má','Þr','Mi','Fi','Fö','La'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['is']);
}); | JavaScript |
/* Lithuanian (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* @author Arturas Paleicikas <arturas@avalon.lt> */
jQuery(function($){
$.datepicker.regional['lt'] = {
clearText: 'Išvalyti', clearStatus: '',
closeText: 'Uždaryti', closeStatus: '',
prevText: '<Atgal', prevStatus: '',
prevBigText: '<<', prevBigStatus: '',
nextText: 'Pirmyn>', nextStatus: '',
nextBigText: '>>', nextBigStatus: '',
currentText: 'Šiandien', currentStatus: '',
monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis',
'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'],
monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir',
'Lie','Rugp','Rugs','Spa','Lap','Gru'],
monthStatus: '', yearStatus: '',
weekHeader: '', weekStatus: '',
dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'],
dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'],
dayNamesMin: ['Se','Pr','An','Tr','Ke','Pe','Še'],
dayStatus: 'DD', dateStatus: 'D, M d',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['lt']);
}); | JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines some constants used by the editor. These constants are also
* globally available in the page where the editor is placed.
*/
// Editor Instance Status.
var FCK_STATUS_NOTLOADED = window.parent.FCK_STATUS_NOTLOADED = 0 ;
var FCK_STATUS_ACTIVE = window.parent.FCK_STATUS_ACTIVE = 1 ;
var FCK_STATUS_COMPLETE = window.parent.FCK_STATUS_COMPLETE = 2 ;
// Tristate Operations.
var FCK_TRISTATE_OFF = window.parent.FCK_TRISTATE_OFF = 0 ;
var FCK_TRISTATE_ON = window.parent.FCK_TRISTATE_ON = 1 ;
var FCK_TRISTATE_DISABLED = window.parent.FCK_TRISTATE_DISABLED = -1 ;
// For unknown values.
var FCK_UNKNOWN = window.parent.FCK_UNKNOWN = -9 ;
// Toolbar Items Style.
var FCK_TOOLBARITEM_ONLYICON = window.parent.FCK_TOOLBARITEM_ONLYICON = 0 ;
var FCK_TOOLBARITEM_ONLYTEXT = window.parent.FCK_TOOLBARITEM_ONLYTEXT = 1 ;
var FCK_TOOLBARITEM_ICONTEXT = window.parent.FCK_TOOLBARITEM_ICONTEXT = 2 ;
// Edit Mode
var FCK_EDITMODE_WYSIWYG = window.parent.FCK_EDITMODE_WYSIWYG = 0 ;
var FCK_EDITMODE_SOURCE = window.parent.FCK_EDITMODE_SOURCE = 1 ;
var FCK_IMAGES_PATH = 'images/' ; // Check usage.
var FCK_SPACER_PATH = 'images/spacer.gif' ;
var CTRL = 1000 ;
var SHIFT = 2000 ;
var ALT = 4000 ;
var FCK_STYLE_BLOCK = 0 ;
var FCK_STYLE_INLINE = 1 ;
var FCK_STYLE_OBJECT = 2 ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Creation and initialization of the "FCK" object. This is the main
* object that represents an editor instance.
* (Gecko specific implementations)
*/
FCK.Description = "FCKeditor for Gecko Browsers" ;
FCK.InitializeBehaviors = function()
{
// When calling "SetData", the editing area IFRAME gets a fixed height. So we must recalculate it.
if ( window.onresize ) // Not for Safari/Opera.
window.onresize() ;
FCKFocusManager.AddWindow( this.EditorWindow ) ;
this.ExecOnSelectionChange = function()
{
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
this._ExecDrop = function( evt )
{
if ( FCK.MouseDownFlag )
{
FCK.MouseDownFlag = false ;
return ;
}
if ( FCKConfig.ForcePasteAsPlainText )
{
if ( evt.dataTransfer )
{
var text = evt.dataTransfer.getData( 'Text' ) ;
text = FCKTools.HTMLEncode( text ) ;
text = FCKTools.ProcessLineBreaks( window, FCKConfig, text ) ;
FCK.InsertHtml( text ) ;
}
else if ( FCKConfig.ShowDropDialog )
FCK.PasteAsPlainText() ;
evt.preventDefault() ;
evt.stopPropagation() ;
}
}
this._ExecCheckCaret = function( evt )
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
if ( evt.type == 'keypress' )
{
var keyCode = evt.keyCode ;
// ignore if positioning key is not pressed.
// left or up arrow keys need to be processed as well, since <a> links can be expanded in Gecko's editor
// when the caret moved left or up from another block element below.
if ( keyCode < 33 || keyCode > 40 )
return ;
}
var blockEmptyStop = function( node )
{
if ( node.nodeType != 1 )
return false ;
var tag = node.tagName.toLowerCase() ;
return ( FCKListsLib.BlockElements[tag] || FCKListsLib.EmptyElements[tag] ) ;
}
var moveCursor = function()
{
var selection = FCKSelection.GetSelection() ;
var range = selection.getRangeAt(0) ;
if ( ! range || ! range.collapsed )
return ;
var node = range.endContainer ;
// only perform the patched behavior if we're at the end of a text node.
if ( node.nodeType != 3 )
return ;
if ( node.nodeValue.length != range.endOffset )
return ;
// only perform the patched behavior if we're in an <a> tag, or the End key is pressed.
var parentTag = node.parentNode.tagName.toLowerCase() ;
if ( ! ( parentTag == 'a' || ( !FCKBrowserInfo.IsOpera && String(node.parentNode.contentEditable) == 'false' ) ||
( ! ( FCKListsLib.BlockElements[parentTag] || FCKListsLib.NonEmptyBlockElements[parentTag] )
&& keyCode == 35 ) ) )
return ;
// our caret has moved to just after the last character of a text node under an unknown tag, how to proceed?
// first, see if there are other text nodes by DFS walking from this text node.
// - if the DFS has scanned all nodes under my parent, then go the next step.
// - if there is a text node after me but still under my parent, then do nothing and return.
var nextTextNode = FCKTools.GetNextTextNode( node, node.parentNode, blockEmptyStop ) ;
if ( nextTextNode )
return ;
// we're pretty sure we need to move the caret forcefully from here.
range = FCK.EditorDocument.createRange() ;
nextTextNode = FCKTools.GetNextTextNode( node, node.parentNode.parentNode, blockEmptyStop ) ;
if ( nextTextNode )
{
// Opera thinks the dummy empty text node we append beyond the end of <a> nodes occupies a caret
// position. So if the user presses the left key and we reset the caret position here, the user
// wouldn't be able to go back.
if ( FCKBrowserInfo.IsOpera && keyCode == 37 )
return ;
// now we want to get out of our current parent node, adopt the next parent, and move the caret to
// the appropriate text node under our new parent.
// our new parent might be our current parent's siblings if we are lucky.
range.setStart( nextTextNode, 0 ) ;
range.setEnd( nextTextNode, 0 ) ;
}
else
{
// no suitable next siblings under our grandparent! what to do next?
while ( node.parentNode
&& node.parentNode != FCK.EditorDocument.body
&& node.parentNode != FCK.EditorDocument.documentElement
&& node == node.parentNode.lastChild
&& ( ! FCKListsLib.BlockElements[node.parentNode.tagName.toLowerCase()]
&& ! FCKListsLib.NonEmptyBlockElements[node.parentNode.tagName.toLowerCase()] ) )
node = node.parentNode ;
if ( FCKListsLib.BlockElements[ parentTag ]
|| FCKListsLib.EmptyElements[ parentTag ]
|| node == FCK.EditorDocument.body )
{
// if our parent is a block node, move to the end of our parent.
range.setStart( node, node.childNodes.length ) ;
range.setEnd( node, node.childNodes.length ) ;
}
else
{
// things are a little bit more interesting if our parent is not a block node
// due to the weired ways how Gecko's caret acts...
var stopNode = node.nextSibling ;
// find out the next block/empty element at our grandparent, we'll
// move the caret just before it.
while ( stopNode )
{
if ( stopNode.nodeType != 1 )
{
stopNode = stopNode.nextSibling ;
continue ;
}
var stopTag = stopNode.tagName.toLowerCase() ;
if ( FCKListsLib.BlockElements[stopTag] || FCKListsLib.EmptyElements[stopTag]
|| FCKListsLib.NonEmptyBlockElements[stopTag] )
break ;
stopNode = stopNode.nextSibling ;
}
// note that the dummy marker below is NEEDED, otherwise the caret's behavior will
// be broken in Gecko.
var marker = FCK.EditorDocument.createTextNode( '' ) ;
if ( stopNode )
node.parentNode.insertBefore( marker, stopNode ) ;
else
node.parentNode.appendChild( marker ) ;
range.setStart( marker, 0 ) ;
range.setEnd( marker, 0 ) ;
}
}
selection.removeAllRanges() ;
selection.addRange( range ) ;
FCK.Events.FireEvent( "OnSelectionChange" ) ;
}
setTimeout( moveCursor, 1 ) ;
}
this.ExecOnSelectionChangeTimer = function()
{
if ( FCK.LastOnChangeTimer )
window.clearTimeout( FCK.LastOnChangeTimer ) ;
FCK.LastOnChangeTimer = window.setTimeout( FCK.ExecOnSelectionChange, 100 ) ;
}
this.EditorDocument.addEventListener( 'mouseup', this.ExecOnSelectionChange, false ) ;
// On Gecko, firing the "OnSelectionChange" event on every key press started to be too much
// slow. So, a timer has been implemented to solve performance issues when typing to quickly.
this.EditorDocument.addEventListener( 'keyup', this.ExecOnSelectionChangeTimer, false ) ;
this._DblClickListener = function( e )
{
FCK.OnDoubleClick( e.target ) ;
e.stopPropagation() ;
}
this.EditorDocument.addEventListener( 'dblclick', this._DblClickListener, true ) ;
// Record changes for the undo system when there are key down events.
this.EditorDocument.addEventListener( 'keydown', this._KeyDownListener, false ) ;
// Hooks for data object drops
if ( FCKBrowserInfo.IsGecko )
{
this.EditorWindow.addEventListener( 'dragdrop', this._ExecDrop, true ) ;
}
else if ( FCKBrowserInfo.IsSafari )
{
this.EditorDocument.addEventListener( 'dragover', function ( evt )
{ if ( !FCK.MouseDownFlag && FCK.Config.ForcePasteAsPlainText ) evt.returnValue = false ; }, true ) ;
this.EditorDocument.addEventListener( 'drop', this._ExecDrop, true ) ;
this.EditorDocument.addEventListener( 'mousedown',
function( ev )
{
var element = ev.srcElement ;
if ( element.nodeName.IEquals( 'IMG', 'HR', 'INPUT', 'TEXTAREA', 'SELECT' ) )
{
FCKSelection.SelectNode( element ) ;
}
}, true ) ;
this.EditorDocument.addEventListener( 'mouseup',
function( ev )
{
if ( ev.srcElement.nodeName.IEquals( 'INPUT', 'TEXTAREA', 'SELECT' ) )
ev.preventDefault()
}, true ) ;
this.EditorDocument.addEventListener( 'click',
function( ev )
{
if ( ev.srcElement.nodeName.IEquals( 'INPUT', 'TEXTAREA', 'SELECT' ) )
ev.preventDefault()
}, true ) ;
}
// Kludge for buggy Gecko caret positioning logic (Bug #393 and #1056)
if ( FCKBrowserInfo.IsGecko || FCKBrowserInfo.IsOpera )
{
this.EditorDocument.addEventListener( 'keypress', this._ExecCheckCaret, false ) ;
this.EditorDocument.addEventListener( 'click', this._ExecCheckCaret, false ) ;
}
// Reset the context menu.
FCK.ContextMenu._InnerContextMenu.SetMouseClickWindow( FCK.EditorWindow ) ;
FCK.ContextMenu._InnerContextMenu.AttachToElement( FCK.EditorDocument ) ;
}
FCK.MakeEditable = function()
{
this.EditingArea.MakeEditable() ;
}
// Disable the context menu in the editor (outside the editing area).
function Document_OnContextMenu( e )
{
if ( !e.target._FCKShowContextMenu )
e.preventDefault() ;
}
document.oncontextmenu = Document_OnContextMenu ;
// GetNamedCommandState overload for Gecko.
FCK._BaseGetNamedCommandState = FCK.GetNamedCommandState ;
FCK.GetNamedCommandState = function( commandName )
{
switch ( commandName )
{
case 'Unlink' :
return FCKSelection.HasAncestorNode('A') ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ;
default :
return FCK._BaseGetNamedCommandState( commandName ) ;
}
}
// Named commands to be handled by this browsers specific implementation.
FCK.RedirectNamedCommands =
{
Print : true,
Paste : true
} ;
// ExecuteNamedCommand overload for Gecko.
FCK.ExecuteRedirectedNamedCommand = function( commandName, commandParameter )
{
switch ( commandName )
{
case 'Print' :
FCK.EditorWindow.print() ;
break ;
case 'Paste' :
try
{
// Force the paste dialog for Safari (#50).
if ( FCKBrowserInfo.IsSafari )
throw '' ;
if ( FCK.Paste() )
FCK.ExecuteNamedCommand( 'Paste', null, true ) ;
}
catch (e) {
if ( FCKConfig.ForcePasteAsPlainText )
FCK.PasteAsPlainText() ;
else
FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.Paste, 'dialog/fck_paste.html', 400, 330, 'Security' ) ;
}
break ;
default :
FCK.ExecuteNamedCommand( commandName, commandParameter ) ;
}
}
FCK._ExecPaste = function()
{
// Save a snapshot for undo before actually paste the text
FCKUndo.SaveUndoStep() ;
if ( FCKConfig.ForcePasteAsPlainText )
{
FCK.PasteAsPlainText() ;
return false ;
}
/* For now, the AutoDetectPasteFromWord feature is IE only. */
return true ;
}
//**
// FCK.InsertHtml: Inserts HTML at the current cursor location. Deletes the
// selected content if any.
FCK.InsertHtml = function( html )
{
var doc = FCK.EditorDocument,
range;
html = FCKConfig.ProtectedSource.Protect( html ) ;
html = FCK.ProtectEvents( html ) ;
html = FCK.ProtectUrls( html ) ;
html = FCK.ProtectTags( html ) ;
// Save an undo snapshot first.
FCKUndo.SaveUndoStep() ;
if ( FCKBrowserInfo.IsGecko )
{
html = html.replace( / $/, '$&<span _fcktemp="1"/>' ) ;
var docFrag = new FCKDocumentFragment( this.EditorDocument ) ;
docFrag.AppendHtml( html ) ;
var lastNode = docFrag.RootNode.lastChild ;
range = new FCKDomRange( this.EditorWindow ) ;
range.MoveToSelection() ;
range.DeleteContents() ;
range.InsertNode( docFrag.RootNode ) ;
range.MoveToPosition( lastNode, 4 ) ;
}
else
doc.execCommand( 'inserthtml', false, html ) ;
this.Focus() ;
// Save the caret position before calling document processor.
if ( !range )
{
range = new FCKDomRange( this.EditorWindow ) ;
range.MoveToSelection() ;
}
var bookmark = range.CreateBookmark() ;
FCKDocumentProcessor.Process( doc ) ;
// Restore caret position, ignore any errors in case the document
// processor removed the bookmark <span>s for some reason.
try
{
range.MoveToBookmark( bookmark ) ;
range.Select() ;
}
catch ( e ) {}
// For some strange reason the SaveUndoStep() call doesn't activate the undo button at the first InsertHtml() call.
this.Events.FireEvent( "OnSelectionChange" ) ;
}
FCK.PasteAsPlainText = function()
{
// TODO: Implement the "Paste as Plain Text" code.
// If the function is called immediately Firefox 2 does automatically paste the contents as soon as the new dialog is created
// so we run it in a Timeout and the paste event can be cancelled
FCKTools.RunFunction( FCKDialog.OpenDialog, FCKDialog, ['FCKDialog_Paste', FCKLang.PasteAsText, 'dialog/fck_paste.html', 400, 330, 'PlainText'] ) ;
/*
var sText = FCKTools.HTMLEncode( clipboardData.getData("Text") ) ;
sText = sText.replace( /\n/g, '<BR>' ) ;
this.InsertHtml( sText ) ;
*/
}
/*
FCK.PasteFromWord = function()
{
// TODO: Implement the "Paste as Plain Text" code.
FCKDialog.OpenDialog( 'FCKDialog_Paste', FCKLang.PasteFromWord, 'dialog/fck_paste.html', 400, 330, 'Word' ) ;
// FCK.CleanAndPaste( FCK.GetClipboardHTML() ) ;
}
*/
FCK.GetClipboardHTML = function()
{
return '' ;
}
FCK.CreateLink = function( url, noUndo )
{
// Creates the array that will be returned. It contains one or more created links (see #220).
var aCreatedLinks = new Array() ;
// Only for Safari, a collapsed selection may create a link. All other
// browser will have no links created. So, we check it here and return
// immediatelly, having the same cross browser behavior.
if ( FCKSelection.GetSelection().isCollapsed )
return aCreatedLinks ;
FCK.ExecuteNamedCommand( 'Unlink', null, false, !!noUndo ) ;
if ( url.length > 0 )
{
// Generate a temporary name for the link.
var sTempUrl = 'javascript:void(0);/*' + ( new Date().getTime() ) + '*/' ;
// Use the internal "CreateLink" command to create the link.
FCK.ExecuteNamedCommand( 'CreateLink', sTempUrl, false, !!noUndo ) ;
// Retrieve the just created links using XPath.
var oLinksInteractor = this.EditorDocument.evaluate("//a[@href='" + sTempUrl + "']", this.EditorDocument.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null) ;
// Add all links to the returning array.
for ( var i = 0 ; i < oLinksInteractor.snapshotLength ; i++ )
{
var oLink = oLinksInteractor.snapshotItem( i ) ;
oLink.href = url ;
aCreatedLinks.push( oLink ) ;
}
}
return aCreatedLinks ;
}
FCK._FillEmptyBlock = function( emptyBlockNode )
{
if ( ! emptyBlockNode || emptyBlockNode.nodeType != 1 )
return ;
var nodeTag = emptyBlockNode.tagName.toLowerCase() ;
if ( nodeTag != 'p' && nodeTag != 'div' )
return ;
if ( emptyBlockNode.firstChild )
return ;
FCKTools.AppendBogusBr( emptyBlockNode ) ;
}
FCK._ExecCheckEmptyBlock = function()
{
FCK._FillEmptyBlock( FCK.EditorDocument.body.firstChild ) ;
var sel = FCKSelection.GetSelection() ;
if ( !sel || sel.rangeCount < 1 )
return ;
var range = sel.getRangeAt( 0 );
FCK._FillEmptyBlock( range.startContainer ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Toolbar items definitions.
*/
var FCKToolbarItems = new Object() ;
FCKToolbarItems.LoadedItems = new Object() ;
FCKToolbarItems.RegisterItem = function( itemName, item )
{
this.LoadedItems[ itemName ] = item ;
}
FCKToolbarItems.GetItem = function( itemName )
{
var oItem = FCKToolbarItems.LoadedItems[ itemName ] ;
if ( oItem )
return oItem ;
switch ( itemName )
{
case 'Source' : oItem = new FCKToolbarButton( 'Source' , FCKLang.Source, null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ; break ;
case 'DocProps' : oItem = new FCKToolbarButton( 'DocProps' , FCKLang.DocProps, null, null, null, null, 2 ) ; break ;
case 'Save' : oItem = new FCKToolbarButton( 'Save' , FCKLang.Save, null, null, true, null, 3 ) ; break ;
case 'NewPage' : oItem = new FCKToolbarButton( 'NewPage' , FCKLang.NewPage, null, null, true, null, 4 ) ; break ;
case 'Preview' : oItem = new FCKToolbarButton( 'Preview' , FCKLang.Preview, null, null, true, null, 5 ) ; break ;
case 'Templates' : oItem = new FCKToolbarButton( 'Templates' , FCKLang.Templates, null, null, null, null, 6 ) ; break ;
case 'About' : oItem = new FCKToolbarButton( 'About' , FCKLang.About, null, null, true, null, 47 ) ; break ;
case 'Cut' : oItem = new FCKToolbarButton( 'Cut' , FCKLang.Cut, null, null, false, true, 7 ) ; break ;
case 'Copy' : oItem = new FCKToolbarButton( 'Copy' , FCKLang.Copy, null, null, false, true, 8 ) ; break ;
case 'Paste' : oItem = new FCKToolbarButton( 'Paste' , FCKLang.Paste, null, null, false, true, 9 ) ; break ;
case 'PasteText' : oItem = new FCKToolbarButton( 'PasteText' , FCKLang.PasteText, null, null, false, true, 10 ) ; break ;
case 'PasteWord' : oItem = new FCKToolbarButton( 'PasteWord' , FCKLang.PasteWord, null, null, false, true, 11 ) ; break ;
case 'Print' : oItem = new FCKToolbarButton( 'Print' , FCKLang.Print, null, null, false, true, 12 ) ; break ;
case 'SpellCheck' : oItem = new FCKToolbarButton( 'SpellCheck', FCKLang.SpellCheck, null, null, null, null, 13 ) ; break ;
case 'Undo' : oItem = new FCKToolbarButton( 'Undo' , FCKLang.Undo, null, null, false, true, 14 ) ; break ;
case 'Redo' : oItem = new FCKToolbarButton( 'Redo' , FCKLang.Redo, null, null, false, true, 15 ) ; break ;
case 'SelectAll' : oItem = new FCKToolbarButton( 'SelectAll' , FCKLang.SelectAll, null, null, true, null, 18 ) ; break ;
case 'RemoveFormat' : oItem = new FCKToolbarButton( 'RemoveFormat', FCKLang.RemoveFormat, null, null, false, true, 19 ) ; break ;
case 'FitWindow' : oItem = new FCKToolbarButton( 'FitWindow' , FCKLang.FitWindow, null, null, true, true, 66 ) ; break ;
case 'Bold' : oItem = new FCKToolbarButton( 'Bold' , FCKLang.Bold, null, null, false, true, 20 ) ; break ;
case 'Italic' : oItem = new FCKToolbarButton( 'Italic' , FCKLang.Italic, null, null, false, true, 21 ) ; break ;
case 'Underline' : oItem = new FCKToolbarButton( 'Underline' , FCKLang.Underline, null, null, false, true, 22 ) ; break ;
case 'StrikeThrough' : oItem = new FCKToolbarButton( 'StrikeThrough' , FCKLang.StrikeThrough, null, null, false, true, 23 ) ; break ;
case 'Subscript' : oItem = new FCKToolbarButton( 'Subscript' , FCKLang.Subscript, null, null, false, true, 24 ) ; break ;
case 'Superscript' : oItem = new FCKToolbarButton( 'Superscript' , FCKLang.Superscript, null, null, false, true, 25 ) ; break ;
case 'OrderedList' : oItem = new FCKToolbarButton( 'InsertOrderedList' , FCKLang.NumberedListLbl, FCKLang.NumberedList, null, false, true, 26 ) ; break ;
case 'UnorderedList' : oItem = new FCKToolbarButton( 'InsertUnorderedList' , FCKLang.BulletedListLbl, FCKLang.BulletedList, null, false, true, 27 ) ; break ;
case 'Outdent' : oItem = new FCKToolbarButton( 'Outdent' , FCKLang.DecreaseIndent, null, null, false, true, 28 ) ; break ;
case 'Indent' : oItem = new FCKToolbarButton( 'Indent' , FCKLang.IncreaseIndent, null, null, false, true, 29 ) ; break ;
case 'Blockquote' : oItem = new FCKToolbarButton( 'Blockquote' , FCKLang.Blockquote, null, null, false, true, 73 ) ; break ;
case 'CreateDiv' : oItem = new FCKToolbarButton( 'CreateDiv' , FCKLang.CreateDiv, null, null, false, true, 74 ) ; break ;
case 'Link' : oItem = new FCKToolbarButton( 'Link' , FCKLang.InsertLinkLbl, FCKLang.InsertLink, null, false, true, 34 ) ; break ;
case 'Unlink' : oItem = new FCKToolbarButton( 'Unlink' , FCKLang.RemoveLink, null, null, false, true, 35 ) ; break ;
case 'Anchor' : oItem = new FCKToolbarButton( 'Anchor' , FCKLang.Anchor, null, null, null, null, 36 ) ; break ;
case 'Image' : oItem = new FCKToolbarButton( 'Image' , FCKLang.InsertImageLbl, FCKLang.InsertImage, null, false, true, 37 ) ; break ;
case 'Flash' : oItem = new FCKToolbarButton( 'Flash' , FCKLang.InsertFlashLbl, FCKLang.InsertFlash, null, false, true, 38 ) ; break ;
case 'Table' : oItem = new FCKToolbarButton( 'Table' , FCKLang.InsertTableLbl, FCKLang.InsertTable, null, false, true, 39 ) ; break ;
case 'SpecialChar' : oItem = new FCKToolbarButton( 'SpecialChar' , FCKLang.InsertSpecialCharLbl, FCKLang.InsertSpecialChar, null, false, true, 42 ) ; break ;
case 'Smiley' : oItem = new FCKToolbarButton( 'Smiley' , FCKLang.InsertSmileyLbl, FCKLang.InsertSmiley, null, false, true, 41 ) ; break ;
case 'PageBreak' : oItem = new FCKToolbarButton( 'PageBreak' , FCKLang.PageBreakLbl, FCKLang.PageBreak, null, false, true, 43 ) ; break ;
case 'Rule' : oItem = new FCKToolbarButton( 'Rule' , FCKLang.InsertLineLbl, FCKLang.InsertLine, null, false, true, 40 ) ; break ;
case 'JustifyLeft' : oItem = new FCKToolbarButton( 'JustifyLeft' , FCKLang.LeftJustify, null, null, false, true, 30 ) ; break ;
case 'JustifyCenter' : oItem = new FCKToolbarButton( 'JustifyCenter' , FCKLang.CenterJustify, null, null, false, true, 31 ) ; break ;
case 'JustifyRight' : oItem = new FCKToolbarButton( 'JustifyRight' , FCKLang.RightJustify, null, null, false, true, 32 ) ; break ;
case 'JustifyFull' : oItem = new FCKToolbarButton( 'JustifyFull' , FCKLang.BlockJustify, null, null, false, true, 33 ) ; break ;
case 'Style' : oItem = new FCKToolbarStyleCombo() ; break ;
case 'FontName' : oItem = new FCKToolbarFontsCombo() ; break ;
case 'FontSize' : oItem = new FCKToolbarFontSizeCombo() ; break ;
case 'FontFormat' : oItem = new FCKToolbarFontFormatCombo() ; break ;
case 'TextColor' : oItem = new FCKToolbarPanelButton( 'TextColor', FCKLang.TextColor, null, null, 45 ) ; break ;
case 'BGColor' : oItem = new FCKToolbarPanelButton( 'BGColor' , FCKLang.BGColor, null, null, 46 ) ; break ;
case 'Find' : oItem = new FCKToolbarButton( 'Find' , FCKLang.Find, null, null, null, null, 16 ) ; break ;
case 'Replace' : oItem = new FCKToolbarButton( 'Replace' , FCKLang.Replace, null, null, null, null, 17 ) ; break ;
case 'Form' : oItem = new FCKToolbarButton( 'Form' , FCKLang.Form, null, null, null, null, 48 ) ; break ;
case 'Checkbox' : oItem = new FCKToolbarButton( 'Checkbox' , FCKLang.Checkbox, null, null, null, null, 49 ) ; break ;
case 'Radio' : oItem = new FCKToolbarButton( 'Radio' , FCKLang.RadioButton, null, null, null, null, 50 ) ; break ;
case 'TextField' : oItem = new FCKToolbarButton( 'TextField' , FCKLang.TextField, null, null, null, null, 51 ) ; break ;
case 'Textarea' : oItem = new FCKToolbarButton( 'Textarea' , FCKLang.Textarea, null, null, null, null, 52 ) ; break ;
case 'HiddenField' : oItem = new FCKToolbarButton( 'HiddenField' , FCKLang.HiddenField, null, null, null, null, 56 ) ; break ;
case 'Button' : oItem = new FCKToolbarButton( 'Button' , FCKLang.Button, null, null, null, null, 54 ) ; break ;
case 'Select' : oItem = new FCKToolbarButton( 'Select' , FCKLang.SelectionField, null, null, null, null, 53 ) ; break ;
case 'ImageButton' : oItem = new FCKToolbarButton( 'ImageButton' , FCKLang.ImageButton, null, null, null, null, 55 ) ; break ;
case 'ShowBlocks' : oItem = new FCKToolbarButton( 'ShowBlocks' , FCKLang.ShowBlocks, null, null, null, true, 72 ) ; break ;
default:
alert( FCKLang.UnknownToolbarItem.replace( /%1/g, itemName ) ) ;
return null ;
}
FCKToolbarItems.LoadedItems[ itemName ] = oItem ;
return oItem ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions.
*/
var FCKTools = new Object() ;
FCKTools.CreateBogusBR = function( targetDocument )
{
var eBR = targetDocument.createElement( 'br' ) ;
// eBR.setAttribute( '_moz_editor_bogus_node', 'TRUE' ) ;
eBR.setAttribute( 'type', '_moz' ) ;
return eBR ;
}
/**
* Fixes relative URL entries defined inside CSS styles by appending a prefix
* to them.
* @param (String) cssStyles The CSS styles definition possibly containing url()
* paths.
* @param (String) urlFixPrefix The prefix to append to relative URLs.
*/
FCKTools.FixCssUrls = function( urlFixPrefix, cssStyles )
{
if ( !urlFixPrefix || urlFixPrefix.length == 0 )
return cssStyles ;
return cssStyles.replace( /url\s*\(([\s'"]*)(.*?)([\s"']*)\)/g, function( match, opener, path, closer )
{
if ( /^\/|^\w?:/.test( path ) )
return match ;
else
return 'url(' + opener + urlFixPrefix + path + closer + ')' ;
} ) ;
}
FCKTools._GetUrlFixedCss = function( cssStyles, urlFixPrefix )
{
var match = cssStyles.match( /^([^|]+)\|([\s\S]*)/ ) ;
if ( match )
return FCKTools.FixCssUrls( match[1], match[2] ) ;
else
return cssStyles ;
}
/**
* Appends a <link css> or <style> element to the document.
* @param (Object) documentElement The DOM document object to which append the
* stylesheet.
* @param (Variant) cssFileOrDef A String pointing to the CSS file URL or an
* Array with many CSS file URLs or the CSS definitions for the <style>
* element.
* @return {Array} An array containing all elements created in the target
* document. It may include <link> or <style> elements, depending on the
* value passed with cssFileOrDef.
*/
FCKTools.AppendStyleSheet = function( domDocument, cssFileOrArrayOrDef )
{
if ( !cssFileOrArrayOrDef )
return [] ;
if ( typeof( cssFileOrArrayOrDef ) == 'string' )
{
// Test if the passed argument is an URL.
if ( /[\\\/\.][^{}]*$/.test( cssFileOrArrayOrDef ) )
{
// The string may have several URLs separated by comma.
return this.AppendStyleSheet( domDocument, cssFileOrArrayOrDef.split(',') ) ;
}
else
return [ this.AppendStyleString( domDocument, FCKTools._GetUrlFixedCss( cssFileOrArrayOrDef ) ) ] ;
}
else
{
var styles = [] ;
for ( var i = 0 ; i < cssFileOrArrayOrDef.length ; i++ )
styles.push( this._AppendStyleSheet( domDocument, cssFileOrArrayOrDef[i] ) ) ;
return styles ;
}
}
FCKTools.GetStyleHtml = (function()
{
var getStyle = function( styleDef, markTemp )
{
if ( styleDef.length == 0 )
return '' ;
var temp = markTemp ? ' _fcktemp="true"' : '' ;
return '<' + 'style type="text/css"' + temp + '>' + styleDef + '<' + '/style>' ;
}
var getLink = function( cssFileUrl, markTemp )
{
if ( cssFileUrl.length == 0 )
return '' ;
var temp = markTemp ? ' _fcktemp="true"' : '' ;
return '<' + 'link href="' + cssFileUrl + '" type="text/css" rel="stylesheet" ' + temp + '/>' ;
}
return function( cssFileOrArrayOrDef, markTemp )
{
if ( !cssFileOrArrayOrDef )
return '' ;
if ( typeof( cssFileOrArrayOrDef ) == 'string' )
{
// Test if the passed argument is an URL.
if ( /[\\\/\.][^{}]*$/.test( cssFileOrArrayOrDef ) )
{
// The string may have several URLs separated by comma.
return this.GetStyleHtml( cssFileOrArrayOrDef.split(','), markTemp ) ;
}
else
return getStyle( this._GetUrlFixedCss( cssFileOrArrayOrDef ), markTemp ) ;
}
else
{
var html = '' ;
for ( var i = 0 ; i < cssFileOrArrayOrDef.length ; i++ )
html += getLink( cssFileOrArrayOrDef[i], markTemp ) ;
return html ;
}
}
})() ;
FCKTools.GetElementDocument = function ( element )
{
return element.ownerDocument || element.document ;
}
// Get the window object where the element is placed in.
FCKTools.GetElementWindow = function( element )
{
return this.GetDocumentWindow( this.GetElementDocument( element ) ) ;
}
FCKTools.GetDocumentWindow = function( document )
{
// With Safari, there is not way to retrieve the window from the document, so we must fix it.
if ( FCKBrowserInfo.IsSafari && !document.parentWindow )
this.FixDocumentParentWindow( window.top ) ;
return document.parentWindow || document.defaultView ;
}
/*
This is a Safari specific function that fix the reference to the parent
window from the document object.
*/
FCKTools.FixDocumentParentWindow = function( targetWindow )
{
if ( targetWindow.document )
targetWindow.document.parentWindow = targetWindow ;
for ( var i = 0 ; i < targetWindow.frames.length ; i++ )
FCKTools.FixDocumentParentWindow( targetWindow.frames[i] ) ;
}
FCKTools.HTMLEncode = function( text )
{
if ( !text )
return '' ;
text = text.replace( /&/g, '&' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( />/g, '>' ) ;
return text ;
}
FCKTools.HTMLDecode = function( text )
{
if ( !text )
return '' ;
text = text.replace( />/g, '>' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( /&/g, '&' ) ;
return text ;
}
FCKTools._ProcessLineBreaksForPMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<p>" ;
var blockEndTag = "</p>" ;
var lineBreakTag = "<br />" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
// Are we currently inside a <p> tag now?
// If yes, close it at the next double line break.
while ( node && node != oEditor.FCK.EditorDocument.body )
{
if ( node.tagName.toLowerCase() == 'p' )
{
closeState = 1 ;
break;
}
node = node.parentNode ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
// Now we have encountered a line break.
// Check if the next character is also a line break.
var n = text.charAt( i + 1 ) ;
if ( n == '\r' )
{
i++ ;
n = text.charAt( i + 1 ) ;
}
if ( n == '\n' )
{
i++ ; // ignore next character - we have already processed it.
if ( closeState )
strArray.push( blockEndTag ) ;
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
else
strArray.push( lineBreakTag ) ;
}
}
FCKTools._ProcessLineBreaksForDivMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<div>" ;
var blockEndTag = "</div>" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
// Are we currently inside a <div> tag now?
// If yes, close it at the next double line break.
while ( node && node != oEditor.FCK.EditorDocument.body )
{
if ( node.tagName.toLowerCase() == 'div' )
{
closeState = 1 ;
break ;
}
node = node.parentNode ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
if ( closeState )
{
if ( strArray[ strArray.length - 1 ] == blockStartTag )
{
// A div tag must have some contents inside for it to be visible.
strArray.push( " " ) ;
}
strArray.push( blockEndTag ) ;
}
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
if ( closeState )
strArray.push( blockEndTag ) ;
}
FCKTools._ProcessLineBreaksForBrMode = function( oEditor, text, liState, node, strArray )
{
var closeState = 0 ;
var blockStartTag = "<br />" ;
var blockEndTag = "" ;
if ( liState )
{
blockStartTag = "<li>" ;
blockEndTag = "</li>" ;
closeState = 1 ;
}
for ( var i = 0 ; i < text.length ; i++ )
{
var c = text.charAt( i ) ;
if ( c == '\r' )
continue ;
if ( c != '\n' )
{
strArray.push( c ) ;
continue ;
}
if ( closeState && blockEndTag.length )
strArray.push ( blockEndTag ) ;
strArray.push( blockStartTag ) ;
closeState = 1 ;
}
}
FCKTools.ProcessLineBreaks = function( oEditor, oConfig, text )
{
var enterMode = oConfig.EnterMode.toLowerCase() ;
var strArray = [] ;
// Is the caret or selection inside an <li> tag now?
var liState = 0 ;
var range = new oEditor.FCKDomRange( oEditor.FCK.EditorWindow ) ;
range.MoveToSelection() ;
var node = range._Range.startContainer ;
while ( node && node.nodeType != 1 )
node = node.parentNode ;
if ( node && node.tagName.toLowerCase() == 'li' )
liState = 1 ;
if ( enterMode == 'p' )
this._ProcessLineBreaksForPMode( oEditor, text, liState, node, strArray ) ;
else if ( enterMode == 'div' )
this._ProcessLineBreaksForDivMode( oEditor, text, liState, node, strArray ) ;
else if ( enterMode == 'br' )
this._ProcessLineBreaksForBrMode( oEditor, text, liState, node, strArray ) ;
return strArray.join( "" ) ;
}
/**
* Adds an option to a SELECT element.
*/
FCKTools.AddSelectOption = function( selectElement, optionText, optionValue )
{
var oOption = FCKTools.GetElementDocument( selectElement ).createElement( "OPTION" ) ;
oOption.text = optionText ;
oOption.value = optionValue ;
selectElement.options.add(oOption) ;
return oOption ;
}
FCKTools.RunFunction = function( func, thisObject, paramsArray, timerWindow )
{
if ( func )
this.SetTimeout( func, 0, thisObject, paramsArray, timerWindow ) ;
}
FCKTools.SetTimeout = function( func, milliseconds, thisObject, paramsArray, timerWindow )
{
return ( timerWindow || window ).setTimeout(
function()
{
if ( paramsArray )
func.apply( thisObject, [].concat( paramsArray ) ) ;
else
func.apply( thisObject ) ;
},
milliseconds ) ;
}
FCKTools.SetInterval = function( func, milliseconds, thisObject, paramsArray, timerWindow )
{
return ( timerWindow || window ).setInterval(
function()
{
func.apply( thisObject, paramsArray || [] ) ;
},
milliseconds ) ;
}
FCKTools.ConvertStyleSizeToHtml = function( size )
{
return size.EndsWith( '%' ) ? size : parseInt( size, 10 ) ;
}
FCKTools.ConvertHtmlSizeToStyle = function( size )
{
return size.EndsWith( '%' ) ? size : ( size + 'px' ) ;
}
// START iCM MODIFICATIONS
// Amended to accept a list of one or more ascensor tag names
// Amended to check the element itself before working back up through the parent hierarchy
FCKTools.GetElementAscensor = function( element, ascensorTagNames )
{
// var e = element.parentNode ;
var e = element ;
var lstTags = "," + ascensorTagNames.toUpperCase() + "," ;
while ( e )
{
if ( lstTags.indexOf( "," + e.nodeName.toUpperCase() + "," ) != -1 )
return e ;
e = e.parentNode ;
}
return null ;
}
// END iCM MODIFICATIONS
FCKTools.CreateEventListener = function( func, params )
{
var f = function()
{
var aAllParams = [] ;
for ( var i = 0 ; i < arguments.length ; i++ )
aAllParams.push( arguments[i] ) ;
func.apply( this, aAllParams.concat( params ) ) ;
}
return f ;
}
FCKTools.IsStrictMode = function( document )
{
// There is no compatMode in Safari, but it seams that it always behave as
// CSS1Compat, so let's assume it as the default for that browser.
return ( 'CSS1Compat' == ( document.compatMode || ( FCKBrowserInfo.IsSafari ? 'CSS1Compat' : null ) ) ) ;
}
// Transforms a "arguments" object to an array.
FCKTools.ArgumentsToArray = function( args, startIndex, maxLength )
{
startIndex = startIndex || 0 ;
maxLength = maxLength || args.length ;
var argsArray = new Array() ;
for ( var i = startIndex ; i < startIndex + maxLength && i < args.length ; i++ )
argsArray.push( args[i] ) ;
return argsArray ;
}
FCKTools.CloneObject = function( sourceObject )
{
var fCloneCreator = function() {} ;
fCloneCreator.prototype = sourceObject ;
return new fCloneCreator ;
}
// Appends a bogus <br> at the end of the element, if not yet available.
FCKTools.AppendBogusBr = function( element )
{
if ( !element )
return ;
var eLastChild = this.GetLastItem( element.getElementsByTagName('br') ) ;
if ( !eLastChild || ( eLastChild.getAttribute( 'type', 2 ) != '_moz' && eLastChild.getAttribute( '_moz_dirty' ) == null ) )
{
var doc = this.GetElementDocument( element ) ;
if ( FCKBrowserInfo.IsOpera )
element.appendChild( doc.createTextNode('') ) ;
else
element.appendChild( this.CreateBogusBR( doc ) ) ;
}
}
FCKTools.GetLastItem = function( list )
{
if ( list.length > 0 )
return list[ list.length - 1 ] ;
return null ;
}
FCKTools.GetDocumentPosition = function( w, node )
{
var x = 0 ;
var y = 0 ;
var curNode = node ;
var prevNode = null ;
var curWindow = FCKTools.GetElementWindow( curNode ) ;
while ( curNode && !( curWindow == w && ( curNode == w.document.body || curNode == w.document.documentElement ) ) )
{
x += curNode.offsetLeft - curNode.scrollLeft ;
y += curNode.offsetTop - curNode.scrollTop ;
if ( ! FCKBrowserInfo.IsOpera )
{
var scrollNode = prevNode ;
while ( scrollNode && scrollNode != curNode )
{
x -= scrollNode.scrollLeft ;
y -= scrollNode.scrollTop ;
scrollNode = scrollNode.parentNode ;
}
}
prevNode = curNode ;
if ( curNode.offsetParent )
curNode = curNode.offsetParent ;
else
{
if ( curWindow != w )
{
curNode = curWindow.frameElement ;
prevNode = null ;
if ( curNode )
curWindow = curNode.contentWindow.parent ;
}
else
curNode = null ;
}
}
// document.body is a special case when it comes to offsetTop and offsetLeft values.
// 1. It matters if document.body itself is a positioned element;
// 2. It matters is when we're in IE and the element has no positioned ancestor.
// Otherwise the values should be ignored.
if ( FCKDomTools.GetCurrentElementStyle( w.document.body, 'position') != 'static'
|| ( FCKBrowserInfo.IsIE && FCKDomTools.GetPositionedAncestor( node ) == null ) )
{
x += w.document.body.offsetLeft ;
y += w.document.body.offsetTop ;
}
return { "x" : x, "y" : y } ;
}
FCKTools.GetWindowPosition = function( w, node )
{
var pos = this.GetDocumentPosition( w, node ) ;
var scroll = FCKTools.GetScrollPosition( w ) ;
pos.x -= scroll.X ;
pos.y -= scroll.Y ;
return pos ;
}
FCKTools.ProtectFormStyles = function( formNode )
{
if ( !formNode || formNode.nodeType != 1 || formNode.tagName.toLowerCase() != 'form' )
return [] ;
var hijackRecord = [] ;
var hijackNames = [ 'style', 'className' ] ;
for ( var i = 0 ; i < hijackNames.length ; i++ )
{
var name = hijackNames[i] ;
if ( formNode.elements.namedItem( name ) )
{
var hijackNode = formNode.elements.namedItem( name ) ;
hijackRecord.push( [ hijackNode, hijackNode.nextSibling ] ) ;
formNode.removeChild( hijackNode ) ;
}
}
return hijackRecord ;
}
FCKTools.RestoreFormStyles = function( formNode, hijackRecord )
{
if ( !formNode || formNode.nodeType != 1 || formNode.tagName.toLowerCase() != 'form' )
return ;
if ( hijackRecord.length > 0 )
{
for ( var i = hijackRecord.length - 1 ; i >= 0 ; i-- )
{
var node = hijackRecord[i][0] ;
var sibling = hijackRecord[i][1] ;
if ( sibling )
formNode.insertBefore( node, sibling ) ;
else
formNode.appendChild( node ) ;
}
}
}
// Perform a one-step DFS walk.
FCKTools.GetNextNode = function( node, limitNode )
{
if ( node.firstChild )
return node.firstChild ;
else if ( node.nextSibling )
return node.nextSibling ;
else
{
var ancestor = node.parentNode ;
while ( ancestor )
{
if ( ancestor == limitNode )
return null ;
if ( ancestor.nextSibling )
return ancestor.nextSibling ;
else
ancestor = ancestor.parentNode ;
}
}
return null ;
}
FCKTools.GetNextTextNode = function( textnode, limitNode, checkStop )
{
node = this.GetNextNode( textnode, limitNode ) ;
if ( checkStop && node && checkStop( node ) )
return null ;
while ( node && node.nodeType != 3 )
{
node = this.GetNextNode( node, limitNode ) ;
if ( checkStop && node && checkStop( node ) )
return null ;
}
return node ;
}
/**
* Merge all objects passed by argument into a single object.
*/
FCKTools.Merge = function()
{
var args = arguments ;
var o = args[0] ;
for ( var i = 1 ; i < args.length ; i++ )
{
var arg = args[i] ;
for ( var p in arg )
o[p] = arg[p] ;
}
return o ;
}
/**
* Check if the passed argument is a real Array. It may not working when
* calling it cross windows.
*/
FCKTools.IsArray = function( it )
{
return ( it instanceof Array ) ;
}
/**
* Appends a "length" property to an object, containing the number of
* properties available on it, excluded the append property itself.
*/
FCKTools.AppendLengthProperty = function( targetObject, propertyName )
{
var counter = 0 ;
for ( var n in targetObject )
counter++ ;
return targetObject[ propertyName || 'length' ] = counter ;
}
/**
* Gets the browser parsed version of a css text (style attribute value). On
* some cases, the browser makes changes to the css text, returning a different
* value. For example, hexadecimal colors get transformed to rgb().
*/
FCKTools.NormalizeCssText = function( unparsedCssText )
{
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var tempSpan = document.createElement( 'span' ) ;
tempSpan.style.cssText = unparsedCssText ;
return tempSpan.style.cssText ;
}
/**
* Binding the "this" reference to an object for a function.
*/
FCKTools.Bind = function( subject, func )
{
return function(){ return func.apply( subject, arguments ) ; } ;
}
/**
* Retrieve the correct "empty iframe" URL for the current browser, which
* causes the minimum fuzz (e.g. security warnings in HTTPS, DNS error in
* IE5.5, etc.) for that browser, making the iframe ready to DOM use whithout
* having to loading an external file.
*/
FCKTools.GetVoidUrl = function()
{
if ( FCK_IS_CUSTOM_DOMAIN )
return "javascript: void( function(){" +
"document.open();" +
"document.write('<html><head><title></title></head><body></body></html>');" +
"document.domain = '" + FCK_RUNTIME_DOMAIN + "';" +
"document.close();" +
"}() ) ;";
if ( FCKBrowserInfo.IsIE )
{
if ( FCKBrowserInfo.IsIE7 || !FCKBrowserInfo.IsIE6 )
return "" ; // IE7+ / IE5.5
else
return "javascript: '';" ; // IE6+
}
return "javascript: void(0);" ; // All other browsers.
}
FCKTools.ResetStyles = function( element )
{
element.style.cssText = 'margin:0;' +
'padding:0;' +
'border:0;' +
'background-color:transparent;' +
'background-image:none;' ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKPlugins object that is responsible for loading the Plugins.
*/
var FCKPlugins = FCK.Plugins = new Object() ;
FCKPlugins.ItemsCount = 0 ;
FCKPlugins.Items = new Object() ;
FCKPlugins.Load = function()
{
var oItems = FCKPlugins.Items ;
// build the plugins collection.
for ( var i = 0 ; i < FCKConfig.Plugins.Items.length ; i++ )
{
var oItem = FCKConfig.Plugins.Items[i] ;
var oPlugin = oItems[ oItem[0] ] = new FCKPlugin( oItem[0], oItem[1], oItem[2] ) ;
FCKPlugins.ItemsCount++ ;
}
// Load all items in the plugins collection.
for ( var s in oItems )
oItems[s].Load() ;
// This is a self destroyable function (must be called once).
FCKPlugins.Load = null ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Debug window control and operations (empty for the compressed files - #2043).
*/
var FCKDebug =
{
Output : function()
{},
OutputObject : function()
{}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Manage table operations.
*/
var FCKTableHandler = new Object() ;
FCKTableHandler.InsertRow = function( insertBefore )
{
// Get the row where the selection is placed in.
var oRow = FCKSelection.MoveToAncestorNode( 'TR' ) ;
if ( !oRow ) return ;
// Create a clone of the row.
var oNewRow = oRow.cloneNode( true ) ;
// Insert the new row (copy) before of it.
oRow.parentNode.insertBefore( oNewRow, oRow ) ;
// Clean one of the rows to produce the illusion of inserting an empty row before or after.
FCKTableHandler.ClearRow( insertBefore ? oNewRow : oRow ) ;
}
FCKTableHandler.DeleteRows = function( row )
{
// If no row has been passed as a parameter,
// then get the row( s ) containing the cells where the selection is placed in.
// If user selected multiple rows ( by selecting multiple cells ), walk
// the selected cell list and delete the rows containing the selected cells
if ( ! row )
{
var aCells = FCKTableHandler.GetSelectedCells() ;
var aRowsToDelete = new Array() ;
//queue up the rows -- it's possible ( and likely ) that we may get duplicates
for ( var i = 0; i < aCells.length; i++ )
{
var oRow = aCells[i].parentNode ;
aRowsToDelete[oRow.rowIndex] = oRow ;
}
for ( var i = aRowsToDelete.length; i >= 0; i-- )
{
if ( aRowsToDelete[i] )
FCKTableHandler.DeleteRows( aRowsToDelete[i] );
}
return ;
}
// Get the row's table.
var oTable = FCKTools.GetElementAscensor( row, 'TABLE' ) ;
// If just one row is available then delete the entire table.
if ( oTable.rows.length == 1 )
{
FCKTableHandler.DeleteTable( oTable ) ;
return ;
}
// Delete the row.
row.parentNode.removeChild( row ) ;
}
FCKTableHandler.DeleteTable = function( table )
{
// If no table has been passed as a parameter,
// then get the table where the selection is placed in.
if ( !table )
{
table = FCKSelection.GetSelectedElement() ;
if ( !table || table.tagName != 'TABLE' )
table = FCKSelection.MoveToAncestorNode( 'TABLE' ) ;
}
if ( !table ) return ;
// Delete the table.
FCKSelection.SelectNode( table ) ;
FCKSelection.Collapse();
// if the table is wrapped with a singleton <p> ( or something similar ), remove
// the surrounding tag -- which likely won't show after deletion anyway
if ( table.parentNode.childNodes.length == 1 )
table.parentNode.parentNode.removeChild( table.parentNode );
else
table.parentNode.removeChild( table ) ;
}
FCKTableHandler.InsertColumn = function( insertBefore )
{
// Get the cell where the selection is placed in.
var oCell = null ;
var nodes = this.GetSelectedCells() ;
if ( nodes && nodes.length )
oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ;
if ( ! oCell )
return ;
// Get the cell's table.
var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ;
var iIndex = oCell.cellIndex ;
// Loop through all rows available in the table.
for ( var i = 0 ; i < oTable.rows.length ; i++ )
{
// Get the row.
var oRow = oTable.rows[i] ;
// If the row doesn't have enough cells, ignore it.
if ( oRow.cells.length < ( iIndex + 1 ) )
continue ;
oCell = oRow.cells[iIndex].cloneNode(false) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( oCell ) ;
// Get back the currently selected cell.
var oBaseCell = oRow.cells[iIndex] ;
oRow.insertBefore( oCell, ( insertBefore ? oBaseCell : oBaseCell.nextSibling ) ) ;
}
}
FCKTableHandler.DeleteColumns = function( oCell )
{
// if user selected multiple cols ( by selecting multiple cells ), walk
// the selected cell list and delete the rows containing the selected cells
if ( !oCell )
{
var aColsToDelete = FCKTableHandler.GetSelectedCells();
for ( var i = aColsToDelete.length; i >= 0; i-- )
{
if ( aColsToDelete[i] )
FCKTableHandler.DeleteColumns( aColsToDelete[i] );
}
return;
}
if ( !oCell ) return ;
// Get the cell's table.
var oTable = FCKTools.GetElementAscensor( oCell, 'TABLE' ) ;
// Get the cell index.
var iIndex = oCell.cellIndex ;
// Loop throw all rows (from down to up, because it's possible that some
// rows will be deleted).
for ( var i = oTable.rows.length - 1 ; i >= 0 ; i-- )
{
// Get the row.
var oRow = oTable.rows[i] ;
// If the cell to be removed is the first one and the row has just one cell.
if ( iIndex == 0 && oRow.cells.length == 1 )
{
// Remove the entire row.
FCKTableHandler.DeleteRows( oRow ) ;
continue ;
}
// If the cell to be removed exists the delete it.
if ( oRow.cells[iIndex] )
oRow.removeChild( oRow.cells[iIndex] ) ;
}
}
FCKTableHandler.InsertCell = function( cell, insertBefore )
{
// Get the cell where the selection is placed in.
var oCell = null ;
var nodes = this.GetSelectedCells() ;
if ( nodes && nodes.length )
oCell = nodes[ insertBefore ? 0 : ( nodes.length - 1 ) ] ;
if ( ! oCell )
return null ;
// Create the new cell element to be added.
var oNewCell = FCK.EditorDocument.createElement( 'TD' ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( oNewCell ) ;
if ( !insertBefore && oCell.cellIndex == oCell.parentNode.cells.length - 1 )
oCell.parentNode.appendChild( oNewCell ) ;
else
oCell.parentNode.insertBefore( oNewCell, insertBefore ? oCell : oCell.nextSibling ) ;
return oNewCell ;
}
FCKTableHandler.DeleteCell = function( cell )
{
// If this is the last cell in the row.
if ( cell.parentNode.cells.length == 1 )
{
// Delete the entire row.
FCKTableHandler.DeleteRows( cell.parentNode ) ;
return ;
}
// Delete the cell from the row.
cell.parentNode.removeChild( cell ) ;
}
FCKTableHandler.DeleteCells = function()
{
var aCells = FCKTableHandler.GetSelectedCells() ;
for ( var i = aCells.length - 1 ; i >= 0 ; i-- )
{
FCKTableHandler.DeleteCell( aCells[i] ) ;
}
}
FCKTableHandler._MarkCells = function( cells, label )
{
for ( var i = 0 ; i < cells.length ; i++ )
cells[i][label] = true ;
}
FCKTableHandler._UnmarkCells = function( cells, label )
{
for ( var i = 0 ; i < cells.length ; i++ )
{
FCKDomTools.ClearElementJSProperty(cells[i], label ) ;
}
}
FCKTableHandler._ReplaceCellsByMarker = function( tableMap, marker, substitute )
{
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
if ( tableMap[i][j][marker] )
tableMap[i][j] = substitute ;
}
}
}
FCKTableHandler._GetMarkerGeometry = function( tableMap, rowIdx, colIdx, markerName )
{
var selectionWidth = 0 ;
var selectionHeight = 0 ;
var cellsLeft = 0 ;
var cellsUp = 0 ;
for ( var i = colIdx ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i++ )
selectionWidth++ ;
for ( var i = colIdx - 1 ; tableMap[rowIdx][i] && tableMap[rowIdx][i][markerName] ; i-- )
{
selectionWidth++ ;
cellsLeft++ ;
}
for ( var i = rowIdx ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i++ )
selectionHeight++ ;
for ( var i = rowIdx - 1 ; tableMap[i] && tableMap[i][colIdx] && tableMap[i][colIdx][markerName] ; i-- )
{
selectionHeight++ ;
cellsUp++ ;
}
return { 'width' : selectionWidth, 'height' : selectionHeight, 'x' : cellsLeft, 'y' : cellsUp } ;
}
FCKTableHandler.CheckIsSelectionRectangular = function()
{
// If every row and column in an area on a plane are of the same width and height,
// Then the area is a rectangle.
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length < 1 )
return false ;
// Check if the selected cells are all in the same table section (thead, tfoot or tbody)
for (var i = 0; i < cells.length; i++)
{
if ( cells[i].parentNode.parentNode != cells[0].parentNode.parentNode )
return false ;
}
this._MarkCells( cells, '_CellSelected' ) ;
var tableMap = this._CreateTableMap( cells[0] ) ;
var rowIdx = cells[0].parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, cells[0] ) ;
var geometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
var baseColIdx = colIdx - geometry.x ;
var baseRowIdx = rowIdx - geometry.y ;
if ( geometry.width >= geometry.height )
{
for ( colIdx = baseColIdx ; colIdx < baseColIdx + geometry.width ; colIdx++ )
{
rowIdx = baseRowIdx + ( colIdx - baseColIdx ) % geometry.height ;
if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
if ( g.width != geometry.width || g.height != geometry.height )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
}
}
else
{
for ( rowIdx = baseRowIdx ; rowIdx < baseRowIdx + geometry.height ; rowIdx++ )
{
colIdx = baseColIdx + ( rowIdx - baseRowIdx ) % geometry.width ;
if ( ! tableMap[rowIdx] || ! tableMap[rowIdx][colIdx] )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
var g = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_CellSelected' ) ;
if ( g.width != geometry.width || g.height != geometry.height )
{
this._UnmarkCells( cells, '_CellSelected' ) ;
return false ;
}
}
}
this._UnmarkCells( cells, '_CellSelected' ) ;
return true ;
}
FCKTableHandler.MergeCells = function()
{
// Get all selected cells.
var cells = this.GetSelectedCells() ;
if ( cells.length < 2 )
return ;
// Assume the selected cells are already in a rectangular geometry.
// Because the checking is already done by FCKTableCommand.
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
this._MarkCells( cells, '_SelectedCells' ) ;
var selectionGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SelectedCells' ) ;
var baseColIdx = colIdx - selectionGeometry.x ;
var baseRowIdx = rowIdx - selectionGeometry.y ;
var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ;
for ( var i = 0 ; i < selectionGeometry.height ; i++ )
{
var rowChildNodesCount = 0 ;
for ( var j = 0 ; j < selectionGeometry.width ; j++ )
{
var currentCell = tableMap[baseRowIdx + i][baseColIdx + j] ;
while ( currentCell.childNodes.length > 0 )
{
var node = currentCell.removeChild( currentCell.firstChild ) ;
if ( node.nodeType != 1
|| ( node.getAttribute( 'type', 2 ) != '_moz' && node.getAttribute( '_moz_dirty' ) != null ) )
{
cellContents.appendChild( node ) ;
rowChildNodesCount++ ;
}
}
}
if ( rowChildNodesCount > 0 )
cellContents.appendChild( FCK.EditorDocument.createElement( 'br' ) ) ;
}
this._ReplaceCellsByMarker( tableMap, '_SelectedCells', refCell ) ;
this._UnmarkCells( cells, '_SelectedCells' ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ;
refCell.appendChild( cellContents ) ;
if ( FCKBrowserInfo.IsGeckoLike && ( ! refCell.firstChild ) )
FCKTools.AppendBogusBr( refCell ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.MergeRight = function()
{
var target = this.GetMergeRightTarget() ;
if ( target == null )
return ;
var refCell = target.refCell ;
var tableMap = target.tableMap ;
var nextCell = target.nextCell ;
var cellContents = FCK.EditorDocument.createDocumentFragment() ;
while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 )
cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ;
nextCell.parentNode.removeChild( nextCell ) ;
refCell.appendChild( cellContents ) ;
this._MarkCells( [nextCell], '_Replace' ) ;
this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.MergeDown = function()
{
var target = this.GetMergeDownTarget() ;
if ( target == null )
return ;
var refCell = target.refCell ;
var tableMap = target.tableMap ;
var nextCell = target.nextCell ;
var cellContents = FCKTools.GetElementDocument( refCell ).createDocumentFragment() ;
while ( nextCell && nextCell.childNodes && nextCell.childNodes.length > 0 )
cellContents.appendChild( nextCell.removeChild( nextCell.firstChild ) ) ;
if ( cellContents.firstChild )
cellContents.insertBefore( FCK.EditorDocument.createElement( 'br' ), cellContents.firstChild ) ;
refCell.appendChild( cellContents ) ;
this._MarkCells( [nextCell], '_Replace' ) ;
this._ReplaceCellsByMarker( tableMap, '_Replace', refCell ) ;
this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ;
this._MoveCaretToCell( refCell, false ) ;
}
FCKTableHandler.HorizontalSplitCell = function()
{
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length != 1 )
return ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var cellSpan = isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ;
if ( cellSpan > 1 )
{
// Splitting a multi-column cell - original cell gets ceil(colSpan/2) columns,
// new cell gets floor(colSpan/2).
var newCellSpan = Math.ceil( cellSpan / 2 ) ;
var newCell = FCK.EditorDocument.createElement( refCell.nodeName ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
var startIdx = colIdx + newCellSpan ;
var endIdx = colIdx + cellSpan ;
var rowSpan = isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ;
for ( var r = rowIdx ; r < rowIdx + rowSpan ; r++ )
{
for ( var i = startIdx ; i < endIdx ; i++ )
tableMap[r][i] = newCell ;
}
}
else
{
// Splitting a single-column cell - add a new cell, and expand
// cells crossing the same column.
var newTableMap = [] ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
var newRow = tableMap[i].slice( 0, colIdx ) ;
if ( tableMap[i].length <= colIdx )
{
newTableMap.push( newRow ) ;
continue ;
}
if ( tableMap[i][colIdx] == refCell )
{
newRow.push( refCell ) ;
newRow.push( FCK.EditorDocument.createElement( refCell.nodeName ) ) ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newRow[newRow.length - 1] ) ;
}
else
{
newRow.push( tableMap[i][colIdx] ) ;
newRow.push( tableMap[i][colIdx] ) ;
}
for ( var j = colIdx + 1 ; j < tableMap[i].length ; j++ )
newRow.push( tableMap[i][j] ) ;
newTableMap.push( newRow ) ;
}
tableMap = newTableMap ;
}
this._InstallTableMap( tableMap, refCell.parentNode.parentNode.parentNode ) ;
}
FCKTableHandler.VerticalSplitCell = function()
{
var cells = FCKTableHandler.GetSelectedCells() ;
if ( cells.length != 1 )
return ;
var currentCell = cells[0] ;
var tableMap = this._CreateTableMap( currentCell ) ;
var currentRowIndex = currentCell.parentNode.rowIndex ;
var cellIndex = FCKTableHandler._GetCellIndexSpan( tableMap, currentRowIndex, currentCell ) ;
// Save current cell colSpan
var currentColSpan = isNaN( currentCell.colSpan ) ? 1 : currentCell.colSpan ;
var currentRowSpan = currentCell.rowSpan ;
if ( isNaN( currentRowSpan ) )
currentRowSpan = 1 ;
if ( currentRowSpan > 1 )
{
// 1. Set the current cell's rowSpan to 1.
currentCell.rowSpan = Math.ceil( currentRowSpan / 2 ) ;
// 2. Find the appropriate place to insert a new cell at the next row.
var newCellRowIndex = currentRowIndex + Math.ceil( currentRowSpan / 2 ) ;
var oRow = tableMap[newCellRowIndex] ;
var insertMarker = null ;
for ( var i = cellIndex+1 ; i < oRow.length ; i++ )
{
if ( oRow[i].parentNode.rowIndex == newCellRowIndex )
{
insertMarker = oRow[i] ;
break ;
}
}
// 3. Insert the new cell to the indicated place, with the appropriate rowSpan and colSpan, next row.
var newCell = FCK.EditorDocument.createElement( currentCell.nodeName ) ;
newCell.rowSpan = Math.floor( currentRowSpan / 2 ) ;
if ( currentColSpan > 1 )
newCell.colSpan = currentColSpan ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
currentCell.parentNode.parentNode.parentNode.rows[newCellRowIndex].insertBefore( newCell, insertMarker ) ;
}
else
{
// 1. Insert a new row.
var newSectionRowIdx = currentCell.parentNode.sectionRowIndex + 1 ;
var newRow = FCK.EditorDocument.createElement( 'tr' ) ;
var tSection = currentCell.parentNode.parentNode ;
if ( tSection.rows.length > newSectionRowIdx )
tSection.insertBefore( newRow, tSection.rows[newSectionRowIdx] ) ;
else
tSection.appendChild( newRow ) ;
// 2. +1 to rowSpan for all cells crossing currentCell's row.
for ( var i = 0 ; i < tableMap[currentRowIndex].length ; )
{
var colSpan = tableMap[currentRowIndex][i].colSpan ;
if ( isNaN( colSpan ) || colSpan < 1 )
colSpan = 1 ;
if ( i == cellIndex )
{
i += colSpan ;
continue ;
}
var rowSpan = tableMap[currentRowIndex][i].rowSpan ;
if ( isNaN( rowSpan ) )
rowSpan = 1 ;
tableMap[currentRowIndex][i].rowSpan = rowSpan + 1 ;
i += colSpan ;
}
// 3. Insert a new cell to new row. Set colSpan on the new cell.
var newCell = FCK.EditorDocument.createElement( currentCell.nodeName ) ;
if ( currentColSpan > 1 )
newCell.colSpan = currentColSpan ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( newCell ) ;
newRow.appendChild( newCell ) ;
}
}
// Get the cell index from a TableMap.
FCKTableHandler._GetCellIndexSpan = function( tableMap, rowIndex, cell )
{
if ( tableMap.length < rowIndex + 1 )
return null ;
var oRow = tableMap[ rowIndex ] ;
for ( var c = 0 ; c < oRow.length ; c++ )
{
if ( oRow[c] == cell )
return c ;
}
return null ;
}
// Get the cell location from a TableMap. Returns an array with an [x,y] location
FCKTableHandler._GetCellLocation = function( tableMap, cell )
{
for ( var i = 0 ; i < tableMap.length; i++ )
{
for ( var c = 0 ; c < tableMap[i].length ; c++ )
{
if ( tableMap[i][c] == cell ) return [i,c];
}
}
return null ;
}
// This function is quite hard to explain. It creates a matrix representing all cells in a table.
// The difference here is that the "spanned" cells (colSpan and rowSpan) are duplicated on the matrix
// cells that are "spanned". For example, a row with 3 cells where the second cell has colSpan=2 and rowSpan=3
// will produce a bi-dimensional matrix with the following values (representing the cells):
// Cell1, Cell2, Cell2, Cell3
// Cell4, Cell2, Cell2, Cell5
// Cell6, Cell2, Cell2, Cell7
FCKTableHandler._CreateTableMap = function( refCell )
{
var table = (refCell.nodeName == 'TABLE' ? refCell : refCell.parentNode.parentNode.parentNode ) ;
var aRows = table.rows ;
// Row and Column counters.
var r = -1 ;
var aMap = new Array() ;
for ( var i = 0 ; i < aRows.length ; i++ )
{
r++ ;
if ( !aMap[r] )
aMap[r] = new Array() ;
var c = -1 ;
for ( var j = 0 ; j < aRows[i].cells.length ; j++ )
{
var oCell = aRows[i].cells[j] ;
c++ ;
while ( aMap[r][c] )
c++ ;
var iColSpan = isNaN( oCell.colSpan ) ? 1 : oCell.colSpan ;
var iRowSpan = isNaN( oCell.rowSpan ) ? 1 : oCell.rowSpan ;
for ( var rs = 0 ; rs < iRowSpan ; rs++ )
{
if ( !aMap[r + rs] )
aMap[r + rs] = new Array() ;
for ( var cs = 0 ; cs < iColSpan ; cs++ )
{
aMap[r + rs][c + cs] = aRows[i].cells[j] ;
}
}
c += iColSpan - 1 ;
}
}
return aMap ;
}
// This function is the inverse of _CreateTableMap - it takes in a table map and converts it to an HTML table.
FCKTableHandler._InstallTableMap = function( tableMap, table )
{
// Workaround for #1917 : MSIE will always report a cell's rowSpan as 1 as long
// as the cell is not attached to a row. So we'll need an alternative attribute
// for storing the calculated rowSpan in IE.
var rowSpanAttr = FCKBrowserInfo.IsIE ? "_fckrowspan" : "rowSpan" ;
// Disconnect all the cells in tableMap from their parents, set all colSpan and rowSpan attributes to 1.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
if ( cell.parentNode )
cell.parentNode.removeChild( cell ) ;
cell.colSpan = cell[rowSpanAttr] = 1 ;
}
}
// Scan by rows and set colSpan.
var maxCol = 0 ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
if ( ! cell)
continue ;
if ( j > maxCol )
maxCol = j ;
if ( cell._colScanned === true )
continue ;
if ( tableMap[i][j-1] == cell )
cell.colSpan++ ;
if ( tableMap[i][j+1] != cell )
cell._colScanned = true ;
}
}
// Scan by columns and set rowSpan.
for ( var i = 0 ; i <= maxCol ; i++ )
{
for ( var j = 0 ; j < tableMap.length ; j++ )
{
if ( ! tableMap[j] )
continue ;
var cell = tableMap[j][i] ;
if ( ! cell || cell._rowScanned === true )
continue ;
if ( tableMap[j-1] && tableMap[j-1][i] == cell )
cell[rowSpanAttr]++ ;
if ( ! tableMap[j+1] || tableMap[j+1][i] != cell )
cell._rowScanned = true ;
}
}
// Clear all temporary flags.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++)
{
var cell = tableMap[i][j] ;
FCKDomTools.ClearElementJSProperty(cell, '_colScanned' ) ;
FCKDomTools.ClearElementJSProperty(cell, '_rowScanned' ) ;
}
}
// Insert physical rows and columns to the table.
for ( var i = 0 ; i < tableMap.length ; i++ )
{
var rowObj = FCK.EditorDocument.createElement( 'tr' ) ;
for ( var j = 0 ; j < tableMap[i].length ; )
{
var cell = tableMap[i][j] ;
if ( tableMap[i-1] && tableMap[i-1][j] == cell )
{
j += cell.colSpan ;
continue ;
}
rowObj.appendChild( cell ) ;
if ( rowSpanAttr != 'rowSpan' )
{
cell.rowSpan = cell[rowSpanAttr] ;
cell.removeAttribute( rowSpanAttr ) ;
}
j += cell.colSpan ;
if ( cell.colSpan == 1 )
cell.removeAttribute( 'colspan' ) ;
if ( cell.rowSpan == 1 )
cell.removeAttribute( 'rowspan' ) ;
}
if ( FCKBrowserInfo.IsIE )
{
table.rows[i].replaceNode( rowObj ) ;
}
else
{
table.rows[i].innerHTML = '' ;
FCKDomTools.MoveChildren( rowObj, table.rows[i] ) ;
}
}
}
FCKTableHandler._MoveCaretToCell = function ( refCell, toStart )
{
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToNodeContents( refCell ) ;
range.Collapse( toStart ) ;
range.Select() ;
}
FCKTableHandler.ClearRow = function( tr )
{
// Get the array of row's cells.
var aCells = tr.cells ;
// Replace the contents of each cell with "nothing".
for ( var i = 0 ; i < aCells.length ; i++ )
{
aCells[i].innerHTML = '' ;
if ( FCKBrowserInfo.IsGeckoLike )
FCKTools.AppendBogusBr( aCells[i] ) ;
}
}
FCKTableHandler.GetMergeRightTarget = function()
{
var cells = this.GetSelectedCells() ;
if ( cells.length != 1 )
return null ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var nextColIdx = colIdx + ( isNaN( refCell.colSpan ) ? 1 : refCell.colSpan ) ;
var nextCell = tableMap[rowIdx][nextColIdx] ;
if ( ! nextCell )
return null ;
// The two cells must have the same vertical geometry, otherwise merging does not make sense.
this._MarkCells( [refCell, nextCell], '_SizeTest' ) ;
var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ;
var nextGeometry = this._GetMarkerGeometry( tableMap, rowIdx, nextColIdx, '_SizeTest' ) ;
this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ;
if ( refGeometry.height != nextGeometry.height || refGeometry.y != nextGeometry.y )
return null ;
return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ;
}
FCKTableHandler.GetMergeDownTarget = function()
{
var cells = this.GetSelectedCells() ;
if ( cells.length != 1 )
return null ;
var refCell = cells[0] ;
var tableMap = this._CreateTableMap( refCell ) ;
var rowIdx = refCell.parentNode.rowIndex ;
var colIdx = this._GetCellIndexSpan( tableMap, rowIdx, refCell ) ;
var newRowIdx = rowIdx + ( isNaN( refCell.rowSpan ) ? 1 : refCell.rowSpan ) ;
if ( ! tableMap[newRowIdx] )
return null ;
var nextCell = tableMap[newRowIdx][colIdx] ;
if ( ! nextCell )
return null ;
// Check if the selected cells are both in the same table section (thead, tfoot or tbody).
if ( refCell.parentNode.parentNode != nextCell.parentNode.parentNode )
return null ;
// The two cells must have the same horizontal geometry, otherwise merging does not makes sense.
this._MarkCells( [refCell, nextCell], '_SizeTest' ) ;
var refGeometry = this._GetMarkerGeometry( tableMap, rowIdx, colIdx, '_SizeTest' ) ;
var nextGeometry = this._GetMarkerGeometry( tableMap, newRowIdx, colIdx, '_SizeTest' ) ;
this._UnmarkCells( [refCell, nextCell], '_SizeTest' ) ;
if ( refGeometry.width != nextGeometry.width || refGeometry.x != nextGeometry.x )
return null ;
return { 'refCell' : refCell, 'nextCell' : nextCell, 'tableMap' : tableMap } ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains browser detection information.
*/
var s = navigator.userAgent.toLowerCase() ;
var FCKBrowserInfo =
{
IsIE : /*@cc_on!@*/false,
IsIE7 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 7 ),
IsIE6 : /*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/ )[1], 10 ) >= 6 ),
IsSafari : s.Contains(' applewebkit/'), // Read "IsWebKit"
IsOpera : !!window.opera,
IsAIR : s.Contains(' adobeair/'),
IsMac : s.Contains('macintosh')
} ;
// Completes the browser info with further Gecko information.
(function( browserInfo )
{
browserInfo.IsGecko = ( navigator.product == 'Gecko' ) && !browserInfo.IsSafari && !browserInfo.IsOpera ;
browserInfo.IsGeckoLike = ( browserInfo.IsGecko || browserInfo.IsSafari || browserInfo.IsOpera ) ;
if ( browserInfo.IsGecko )
{
var geckoMatch = s.match( /rv:(\d+\.\d+)/ ) ;
var geckoVersion = geckoMatch && parseFloat( geckoMatch[1] ) ;
// Actually "10" refers to Gecko versions before Firefox 1.5, when
// Gecko 1.8 (build 20051111) has been released.
// Some browser (like Mozilla 1.7.13) may have a Gecko build greater
// than 20051111, so we must also check for the revision number not to
// be 1.7 (we are assuming that rv < 1.7 will not have build > 20051111).
if ( geckoVersion )
{
browserInfo.IsGecko10 = ( geckoVersion < 1.8 ) ;
browserInfo.IsGecko19 = ( geckoVersion > 1.8 ) ;
}
}
})(FCKBrowserInfo) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXHtml object, responsible for the XHTML operations.
* IE specific.
*/
FCKXHtml._GetMainXmlString = function()
{
return this.MainNode.xml ;
}
FCKXHtml._AppendAttributes = function( xmlNode, htmlNode, node, nodeName )
{
var aAttributes = htmlNode.attributes,
bHasStyle ;
for ( var n = 0 ; n < aAttributes.length ; n++ )
{
var oAttribute = aAttributes[n] ;
if ( oAttribute.specified )
{
var sAttName = oAttribute.nodeName.toLowerCase() ;
var sAttValue ;
// Ignore any attribute starting with "_fck".
if ( sAttName.StartsWith( '_fck' ) )
continue ;
// The following must be done because of a bug on IE regarding the style
// attribute. It returns "null" for the nodeValue.
else if ( sAttName == 'style' )
{
// Just mark it to do it later in this function.
bHasStyle = true ;
continue ;
}
// There are two cases when the oAttribute.nodeValue must be used:
// - for the "class" attribute
// - for events attributes (on IE only).
else if ( sAttName == 'class' )
{
sAttValue = oAttribute.nodeValue.replace( FCKRegexLib.FCK_Class, '' ) ;
if ( sAttValue.length == 0 )
continue ;
}
else if ( sAttName.indexOf('on') == 0 )
sAttValue = oAttribute.nodeValue ;
else if ( nodeName == 'body' && sAttName == 'contenteditable' )
continue ;
// XHTML doens't support attribute minimization like "CHECKED". It must be transformed to checked="checked".
else if ( oAttribute.nodeValue === true )
sAttValue = sAttName ;
else
{
// We must use getAttribute to get it exactly as it is defined.
// There are some rare cases that IE throws an error here, so we must try/catch.
try
{
sAttValue = htmlNode.getAttribute( sAttName, 2 ) ;
}
catch (e) {}
}
this._AppendAttribute( node, sAttName, sAttValue || oAttribute.nodeValue ) ;
}
}
// IE loses the style attribute in JavaScript-created elements tags. (#2390)
if ( bHasStyle || htmlNode.style.cssText.length > 0 )
{
var data = FCKTools.ProtectFormStyles( htmlNode ) ;
var sStyleValue = htmlNode.style.cssText.replace( FCKRegexLib.StyleProperties, FCKTools.ToLowerCase ) ;
FCKTools.RestoreFormStyles( htmlNode, data ) ;
this._AppendAttribute( node, 'style', sStyleValue ) ;
}
}
// On very rare cases, IE is loosing the "align" attribute for DIV. (right align and apply bulleted list)
FCKXHtml.TagProcessors['div'] = function( node, htmlNode )
{
if ( htmlNode.align.length > 0 )
FCKXHtml._AppendAttribute( node, 'align', htmlNode.align ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
// IE automatically changes <FONT> tags to <FONT size=+0>.
FCKXHtml.TagProcessors['font'] = function( node, htmlNode )
{
if ( node.attributes.length == 0 )
node = FCKXHtml.XML.createDocumentFragment() ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
FCKXHtml.TagProcessors['form'] = function( node, htmlNode )
{
if ( htmlNode.acceptCharset && htmlNode.acceptCharset.length > 0 && htmlNode.acceptCharset != 'UNKNOWN' )
FCKXHtml._AppendAttribute( node, 'accept-charset', htmlNode.acceptCharset ) ;
// IE has a bug and htmlNode.attributes['name'].specified=false if there is
// no element with id="name" inside the form (#360 and SF-BUG-1155726).
var nameAtt = htmlNode.attributes['name'] ;
if ( nameAtt && nameAtt.value.length > 0 )
FCKXHtml._AppendAttribute( node, 'name', nameAtt.value ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
// IE doens't see the value attribute as an attribute for the <INPUT> tag.
FCKXHtml.TagProcessors['input'] = function( node, htmlNode )
{
if ( htmlNode.name )
FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ;
if ( htmlNode.value && !node.attributes.getNamedItem( 'value' ) )
FCKXHtml._AppendAttribute( node, 'value', htmlNode.value ) ;
if ( !node.attributes.getNamedItem( 'type' ) )
FCKXHtml._AppendAttribute( node, 'type', 'text' ) ;
return node ;
}
FCKXHtml.TagProcessors['label'] = function( node, htmlNode )
{
if ( htmlNode.htmlFor.length > 0 )
FCKXHtml._AppendAttribute( node, 'for', htmlNode.htmlFor ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
// Fix behavior for IE, it doesn't read back the .name on newly created maps
FCKXHtml.TagProcessors['map'] = function( node, htmlNode )
{
if ( ! node.attributes.getNamedItem( 'name' ) )
{
var name = htmlNode.name ;
if ( name )
FCKXHtml._AppendAttribute( node, 'name', name ) ;
}
node = FCKXHtml._AppendChildNodes( node, htmlNode, true ) ;
return node ;
}
FCKXHtml.TagProcessors['meta'] = function( node, htmlNode )
{
var oHttpEquiv = node.attributes.getNamedItem( 'http-equiv' ) ;
if ( oHttpEquiv == null || oHttpEquiv.value.length == 0 )
{
// Get the http-equiv value from the outerHTML.
var sHttpEquiv = htmlNode.outerHTML.match( FCKRegexLib.MetaHttpEquiv ) ;
if ( sHttpEquiv )
{
sHttpEquiv = sHttpEquiv[1] ;
FCKXHtml._AppendAttribute( node, 'http-equiv', sHttpEquiv ) ;
}
}
return node ;
}
// IE ignores the "SELECTED" attribute so we must add it manually.
FCKXHtml.TagProcessors['option'] = function( node, htmlNode )
{
if ( htmlNode.selected && !node.attributes.getNamedItem( 'selected' ) )
FCKXHtml._AppendAttribute( node, 'selected', 'selected' ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
// IE doens't hold the name attribute as an attribute for the <TEXTAREA> and <SELECT> tags.
FCKXHtml.TagProcessors['textarea'] = FCKXHtml.TagProcessors['select'] = function( node, htmlNode )
{
if ( htmlNode.name )
FCKXHtml._AppendAttribute( node, 'name', htmlNode.name ) ;
node = FCKXHtml._AppendChildNodes( node, htmlNode ) ;
return node ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions to work with the DOM.
*/
var FCKDomTools =
{
/**
* Move all child nodes from one node to another.
*/
MoveChildren : function( source, target, toTargetStart )
{
if ( source == target )
return ;
var eChild ;
if ( toTargetStart )
{
while ( (eChild = source.lastChild) )
target.insertBefore( source.removeChild( eChild ), target.firstChild ) ;
}
else
{
while ( (eChild = source.firstChild) )
target.appendChild( source.removeChild( eChild ) ) ;
}
},
MoveNode : function( source, target, toTargetStart )
{
if ( toTargetStart )
target.insertBefore( FCKDomTools.RemoveNode( source ), target.firstChild ) ;
else
target.appendChild( FCKDomTools.RemoveNode( source ) ) ;
},
// Remove blank spaces from the beginning and the end of the contents of a node.
TrimNode : function( node )
{
this.LTrimNode( node ) ;
this.RTrimNode( node ) ;
},
LTrimNode : function( node )
{
var eChildNode ;
while ( (eChildNode = node.firstChild) )
{
if ( eChildNode.nodeType == 3 )
{
var sTrimmed = eChildNode.nodeValue.LTrim() ;
var iOriginalLength = eChildNode.nodeValue.length ;
if ( sTrimmed.length == 0 )
{
node.removeChild( eChildNode ) ;
continue ;
}
else if ( sTrimmed.length < iOriginalLength )
{
eChildNode.splitText( iOriginalLength - sTrimmed.length ) ;
node.removeChild( node.firstChild ) ;
}
}
break ;
}
},
RTrimNode : function( node )
{
var eChildNode ;
while ( (eChildNode = node.lastChild) )
{
if ( eChildNode.nodeType == 3 )
{
var sTrimmed = eChildNode.nodeValue.RTrim() ;
var iOriginalLength = eChildNode.nodeValue.length ;
if ( sTrimmed.length == 0 )
{
// If the trimmed text node is empty, just remove it.
// Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#81).
eChildNode.parentNode.removeChild( eChildNode ) ;
continue ;
}
else if ( sTrimmed.length < iOriginalLength )
{
// If the trimmed text length is less than the original
// length, strip all spaces from the end by splitting
// the text and removing the resulting useless node.
eChildNode.splitText( sTrimmed.length ) ;
// Use "node.lastChild.parentNode" instead of "node" to avoid IE bug (#81).
node.lastChild.parentNode.removeChild( node.lastChild ) ;
}
}
break ;
}
if ( !FCKBrowserInfo.IsIE && !FCKBrowserInfo.IsOpera )
{
eChildNode = node.lastChild ;
if ( eChildNode && eChildNode.nodeType == 1 && eChildNode.nodeName.toLowerCase() == 'br' )
{
// Use "eChildNode.parentNode" instead of "node" to avoid IE bug (#324).
eChildNode.parentNode.removeChild( eChildNode ) ;
}
}
},
RemoveNode : function( node, excludeChildren )
{
if ( excludeChildren )
{
// Move all children before the node.
var eChild ;
while ( (eChild = node.firstChild) )
node.parentNode.insertBefore( node.removeChild( eChild ), node ) ;
}
return node.parentNode.removeChild( node ) ;
},
GetFirstChild : function( node, childNames )
{
// If childNames is a string, transform it in a Array.
if ( typeof ( childNames ) == 'string' )
childNames = [ childNames ] ;
var eChild = node.firstChild ;
while( eChild )
{
if ( eChild.nodeType == 1 && eChild.tagName.Equals.apply( eChild.tagName, childNames ) )
return eChild ;
eChild = eChild.nextSibling ;
}
return null ;
},
GetLastChild : function( node, childNames )
{
// If childNames is a string, transform it in a Array.
if ( typeof ( childNames ) == 'string' )
childNames = [ childNames ] ;
var eChild = node.lastChild ;
while( eChild )
{
if ( eChild.nodeType == 1 && ( !childNames || eChild.tagName.Equals( childNames ) ) )
return eChild ;
eChild = eChild.previousSibling ;
}
return null ;
},
/*
* Gets the previous element (nodeType=1) in the source order. Returns
* "null" If no element is found.
* @param {Object} currentNode The node to start searching from.
* @param {Boolean} ignoreSpaceTextOnly Sets how text nodes will be
* handled. If set to "true", only white spaces text nodes
* will be ignored, while non white space text nodes will stop
* the search, returning null. If "false" or omitted, all
* text nodes are ignored.
* @param {string[]} stopSearchElements An array of element names that
* will cause the search to stop when found, returning null.
* May be omitted (or null).
* @param {string[]} ignoreElements An array of element names that
* must be ignored during the search.
*/
GetPreviousSourceElement : function( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements )
{
if ( !currentNode )
return null ;
if ( stopSearchElements && currentNode.nodeType == 1 && currentNode.nodeName.IEquals( stopSearchElements ) )
return null ;
if ( currentNode.previousSibling )
currentNode = currentNode.previousSibling ;
else
return this.GetPreviousSourceElement( currentNode.parentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
while ( currentNode )
{
if ( currentNode.nodeType == 1 )
{
if ( stopSearchElements && currentNode.nodeName.IEquals( stopSearchElements ) )
break ;
if ( !ignoreElements || !currentNode.nodeName.IEquals( ignoreElements ) )
return currentNode ;
}
else if ( ignoreSpaceTextOnly && currentNode.nodeType == 3 && currentNode.nodeValue.RTrim().length > 0 )
break ;
if ( currentNode.lastChild )
currentNode = currentNode.lastChild ;
else
return this.GetPreviousSourceElement( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
}
return null ;
},
/*
* Gets the next element (nodeType=1) in the source order. Returns
* "null" If no element is found.
* @param {Object} currentNode The node to start searching from.
* @param {Boolean} ignoreSpaceTextOnly Sets how text nodes will be
* handled. If set to "true", only white spaces text nodes
* will be ignored, while non white space text nodes will stop
* the search, returning null. If "false" or omitted, all
* text nodes are ignored.
* @param {string[]} stopSearchElements An array of element names that
* will cause the search to stop when found, returning null.
* May be omitted (or null).
* @param {string[]} ignoreElements An array of element names that
* must be ignored during the search.
*/
GetNextSourceElement : function( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements, startFromSibling )
{
while( ( currentNode = this.GetNextSourceNode( currentNode, startFromSibling ) ) ) // Only one "=".
{
if ( currentNode.nodeType == 1 )
{
if ( stopSearchElements && currentNode.nodeName.IEquals( stopSearchElements ) )
break ;
if ( ignoreElements && currentNode.nodeName.IEquals( ignoreElements ) )
return this.GetNextSourceElement( currentNode, ignoreSpaceTextOnly, stopSearchElements, ignoreElements ) ;
return currentNode ;
}
else if ( ignoreSpaceTextOnly && currentNode.nodeType == 3 && currentNode.nodeValue.RTrim().length > 0 )
break ;
}
return null ;
},
/*
* Get the next DOM node available in source order.
*/
GetNextSourceNode : function( currentNode, startFromSibling, nodeType, stopSearchNode )
{
if ( !currentNode )
return null ;
var node ;
if ( !startFromSibling && currentNode.firstChild )
node = currentNode.firstChild ;
else
{
if ( stopSearchNode && currentNode == stopSearchNode )
return null ;
node = currentNode.nextSibling ;
if ( !node && ( !stopSearchNode || stopSearchNode != currentNode.parentNode ) )
return this.GetNextSourceNode( currentNode.parentNode, true, nodeType, stopSearchNode ) ;
}
if ( nodeType && node && node.nodeType != nodeType )
return this.GetNextSourceNode( node, false, nodeType, stopSearchNode ) ;
return node ;
},
/*
* Get the next DOM node available in source order.
*/
GetPreviousSourceNode : function( currentNode, startFromSibling, nodeType, stopSearchNode )
{
if ( !currentNode )
return null ;
var node ;
if ( !startFromSibling && currentNode.lastChild )
node = currentNode.lastChild ;
else
{
if ( stopSearchNode && currentNode == stopSearchNode )
return null ;
node = currentNode.previousSibling ;
if ( !node && ( !stopSearchNode || stopSearchNode != currentNode.parentNode ) )
return this.GetPreviousSourceNode( currentNode.parentNode, true, nodeType, stopSearchNode ) ;
}
if ( nodeType && node && node.nodeType != nodeType )
return this.GetPreviousSourceNode( node, false, nodeType, stopSearchNode ) ;
return node ;
},
// Inserts a element after a existing one.
InsertAfterNode : function( existingNode, newNode )
{
return existingNode.parentNode.insertBefore( newNode, existingNode.nextSibling ) ;
},
GetParents : function( node )
{
var parents = new Array() ;
while ( node )
{
parents.unshift( node ) ;
node = node.parentNode ;
}
return parents ;
},
GetCommonParents : function( node1, node2 )
{
var p1 = this.GetParents( node1 ) ;
var p2 = this.GetParents( node2 ) ;
var retval = [] ;
for ( var i = 0 ; i < p1.length ; i++ )
{
if ( p1[i] == p2[i] )
retval.push( p1[i] ) ;
}
return retval ;
},
GetCommonParentNode : function( node1, node2, tagList )
{
var tagMap = {} ;
if ( ! tagList.pop )
tagList = [ tagList ] ;
while ( tagList.length > 0 )
tagMap[tagList.pop().toLowerCase()] = 1 ;
var commonParents = this.GetCommonParents( node1, node2 ) ;
var currentParent = null ;
while ( ( currentParent = commonParents.pop() ) )
{
if ( tagMap[currentParent.nodeName.toLowerCase()] )
return currentParent ;
}
return null ;
},
GetIndexOf : function( node )
{
var currentNode = node.parentNode ? node.parentNode.firstChild : null ;
var currentIndex = -1 ;
while ( currentNode )
{
currentIndex++ ;
if ( currentNode == node )
return currentIndex ;
currentNode = currentNode.nextSibling ;
}
return -1 ;
},
PaddingNode : null,
EnforcePaddingNode : function( doc, tagName )
{
// In IE it can happen when the page is reloaded that doc or doc.body is null, so exit here
try
{
if ( !doc || !doc.body )
return ;
}
catch (e)
{
return ;
}
this.CheckAndRemovePaddingNode( doc, tagName, true ) ;
try
{
if ( doc.body.lastChild && ( doc.body.lastChild.nodeType != 1
|| doc.body.lastChild.tagName.toLowerCase() == tagName.toLowerCase() ) )
return ;
}
catch (e)
{
return ;
}
var node = doc.createElement( tagName ) ;
if ( FCKBrowserInfo.IsGecko && FCKListsLib.NonEmptyBlockElements[ tagName ] )
FCKTools.AppendBogusBr( node ) ;
this.PaddingNode = node ;
if ( doc.body.childNodes.length == 1
&& doc.body.firstChild.nodeType == 1
&& doc.body.firstChild.tagName.toLowerCase() == 'br'
&& ( doc.body.firstChild.getAttribute( '_moz_dirty' ) != null
|| doc.body.firstChild.getAttribute( 'type' ) == '_moz' ) )
doc.body.replaceChild( node, doc.body.firstChild ) ;
else
doc.body.appendChild( node ) ;
},
CheckAndRemovePaddingNode : function( doc, tagName, dontRemove )
{
var paddingNode = this.PaddingNode ;
if ( ! paddingNode )
return ;
// If the padding node is changed, remove its status as a padding node.
try
{
if ( paddingNode.parentNode != doc.body
|| paddingNode.tagName.toLowerCase() != tagName
|| ( paddingNode.childNodes.length > 1 )
|| ( paddingNode.firstChild && paddingNode.firstChild.nodeValue != '\xa0'
&& String(paddingNode.firstChild.tagName).toLowerCase() != 'br' ) )
{
this.PaddingNode = null ;
return ;
}
}
catch (e)
{
this.PaddingNode = null ;
return ;
}
// Now we're sure the padding node exists, and it is unchanged, and it
// isn't the only node in doc.body, remove it.
if ( !dontRemove )
{
if ( paddingNode.parentNode.childNodes.length > 1 )
paddingNode.parentNode.removeChild( paddingNode ) ;
this.PaddingNode = null ;
}
},
HasAttribute : function( element, attributeName )
{
if ( element.hasAttribute )
return element.hasAttribute( attributeName ) ;
else
{
var att = element.attributes[ attributeName ] ;
return ( att != undefined && att.specified ) ;
}
},
/**
* Checks if an element has "specified" attributes.
*/
HasAttributes : function( element )
{
var attributes = element.attributes ;
for ( var i = 0 ; i < attributes.length ; i++ )
{
if ( FCKBrowserInfo.IsIE && attributes[i].nodeName == 'class' )
{
// IE has a strange bug. If calling removeAttribute('className'),
// the attributes collection will still contain the "class"
// attribute, which will be marked as "specified", even if the
// outerHTML of the element is not displaying the class attribute.
// Note : I was not able to reproduce it outside the editor,
// but I've faced it while working on the TC of #1391.
if ( element.className.length > 0 )
return true ;
}
else if ( attributes[i].specified )
return true ;
}
return false ;
},
/**
* Remove an attribute from an element.
*/
RemoveAttribute : function( element, attributeName )
{
if ( FCKBrowserInfo.IsIE && attributeName.toLowerCase() == 'class' )
attributeName = 'className' ;
return element.removeAttribute( attributeName, 0 ) ;
},
/**
* Removes an array of attributes from an element
*/
RemoveAttributes : function (element, aAttributes )
{
for ( var i = 0 ; i < aAttributes.length ; i++ )
this.RemoveAttribute( element, aAttributes[i] );
},
GetAttributeValue : function( element, att )
{
var attName = att ;
if ( typeof att == 'string' )
att = element.attributes[ att ] ;
else
attName = att.nodeName ;
if ( att && att.specified )
{
// IE returns "null" for the nodeValue of a "style" attribute.
if ( attName == 'style' )
return element.style.cssText ;
// There are two cases when the nodeValue must be used:
// - for the "class" attribute (all browsers).
// - for events attributes (IE only).
else if ( attName == 'class' || attName.indexOf('on') == 0 )
return att.nodeValue ;
else
{
// Use getAttribute to get its value exactly as it is
// defined.
return element.getAttribute( attName, 2 ) ;
}
}
return null ;
},
/**
* Checks whether one element contains the other.
*/
Contains : function( mainElement, otherElement )
{
// IE supports contains, but only for element nodes.
if ( mainElement.contains && otherElement.nodeType == 1 )
return mainElement.contains( otherElement ) ;
while ( ( otherElement = otherElement.parentNode ) ) // Only one "="
{
if ( otherElement == mainElement )
return true ;
}
return false ;
},
/**
* Breaks a parent element in the position of one of its contained elements.
* For example, in the following case:
* <b>This <i>is some<span /> sample</i> test text</b>
* If element = <span />, we have these results:
* <b>This <i>is some</i><span /><i> sample</i> test text</b> (If parent = <i>)
* <b>This <i>is some</i></b><span /><b><i> sample</i> test text</b> (If parent = <b>)
*/
BreakParent : function( element, parent, reusableRange )
{
var range = reusableRange || new FCKDomRange( FCKTools.GetElementWindow( element ) ) ;
// We'll be extracting part of this element, so let's use our
// range to get the correct piece.
range.SetStart( element, 4 ) ;
range.SetEnd( parent, 4 ) ;
// Extract it.
var docFrag = range.ExtractContents() ;
// Move the element outside the broken element.
range.InsertNode( element.parentNode.removeChild( element ) ) ;
// Re-insert the extracted piece after the element.
docFrag.InsertAfterNode( element ) ;
range.Release( !!reusableRange ) ;
},
/**
* Retrieves a uniquely identifiable tree address of a DOM tree node.
* The tree address returns is an array of integers, with each integer
* indicating a child index from a DOM tree node, starting from
* document.documentElement.
*
* For example, assuming <body> is the second child from <html> (<head>
* being the first), and we'd like to address the third child under the
* fourth child of body, the tree address returned would be:
* [1, 3, 2]
*
* The tree address cannot be used for finding back the DOM tree node once
* the DOM tree structure has been modified.
*/
GetNodeAddress : function( node, normalized )
{
var retval = [] ;
while ( node && node != FCKTools.GetElementDocument( node ).documentElement )
{
var parentNode = node.parentNode ;
var currentIndex = -1 ;
for( var i = 0 ; i < parentNode.childNodes.length ; i++ )
{
var candidate = parentNode.childNodes[i] ;
if ( normalized === true &&
candidate.nodeType == 3 &&
candidate.previousSibling &&
candidate.previousSibling.nodeType == 3 )
continue;
currentIndex++ ;
if ( parentNode.childNodes[i] == node )
break ;
}
retval.unshift( currentIndex ) ;
node = node.parentNode ;
}
return retval ;
},
/**
* The reverse transformation of FCKDomTools.GetNodeAddress(). This
* function returns the DOM node pointed to by its index address.
*/
GetNodeFromAddress : function( doc, addr, normalized )
{
var cursor = doc.documentElement ;
for ( var i = 0 ; i < addr.length ; i++ )
{
var target = addr[i] ;
if ( ! normalized )
{
cursor = cursor.childNodes[target] ;
continue ;
}
var currentIndex = -1 ;
for (var j = 0 ; j < cursor.childNodes.length ; j++ )
{
var candidate = cursor.childNodes[j] ;
if ( normalized === true &&
candidate.nodeType == 3 &&
candidate.previousSibling &&
candidate.previousSibling.nodeType == 3 )
continue ;
currentIndex++ ;
if ( currentIndex == target )
{
cursor = candidate ;
break ;
}
}
}
return cursor ;
},
CloneElement : function( element )
{
element = element.cloneNode( false ) ;
// The "id" attribute should never be cloned to avoid duplication.
element.removeAttribute( 'id', false ) ;
return element ;
},
ClearElementJSProperty : function( element, attrName )
{
if ( FCKBrowserInfo.IsIE )
element.removeAttribute( attrName ) ;
else
delete element[attrName] ;
},
SetElementMarker : function ( markerObj, element, attrName, value)
{
var id = String( parseInt( Math.random() * 0xffffffff, 10 ) ) ;
element._FCKMarkerId = id ;
element[attrName] = value ;
if ( ! markerObj[id] )
markerObj[id] = { 'element' : element, 'markers' : {} } ;
markerObj[id]['markers'][attrName] = value ;
},
ClearElementMarkers : function( markerObj, element, clearMarkerObj )
{
var id = element._FCKMarkerId ;
if ( ! id )
return ;
this.ClearElementJSProperty( element, '_FCKMarkerId' ) ;
for ( var j in markerObj[id]['markers'] )
this.ClearElementJSProperty( element, j ) ;
if ( clearMarkerObj )
delete markerObj[id] ;
},
ClearAllMarkers : function( markerObj )
{
for ( var i in markerObj )
this.ClearElementMarkers( markerObj, markerObj[i]['element'], true ) ;
},
/**
* Convert a DOM list tree into a data structure that is easier to
* manipulate. This operation should be non-intrusive in the sense that it
* does not change the DOM tree, with the exception that it may add some
* markers to the list item nodes when markerObj is specified.
*/
ListToArray : function( listNode, markerObj, baseArray, baseIndentLevel, grandparentNode )
{
if ( ! listNode.nodeName.IEquals( ['ul', 'ol'] ) )
return [] ;
if ( ! baseIndentLevel )
baseIndentLevel = 0 ;
if ( ! baseArray )
baseArray = [] ;
// Iterate over all list items to get their contents and look for inner lists.
for ( var i = 0 ; i < listNode.childNodes.length ; i++ )
{
var listItem = listNode.childNodes[i] ;
if ( ! listItem.nodeName.IEquals( 'li' ) )
continue ;
var itemObj = { 'parent' : listNode, 'indent' : baseIndentLevel, 'contents' : [] } ;
if ( ! grandparentNode )
{
itemObj.grandparent = listNode.parentNode ;
if ( itemObj.grandparent && itemObj.grandparent.nodeName.IEquals( 'li' ) )
itemObj.grandparent = itemObj.grandparent.parentNode ;
}
else
itemObj.grandparent = grandparentNode ;
if ( markerObj )
this.SetElementMarker( markerObj, listItem, '_FCK_ListArray_Index', baseArray.length ) ;
baseArray.push( itemObj ) ;
for ( var j = 0 ; j < listItem.childNodes.length ; j++ )
{
var child = listItem.childNodes[j] ;
if ( child.nodeName.IEquals( ['ul', 'ol'] ) )
// Note the recursion here, it pushes inner list items with
// +1 indentation in the correct order.
this.ListToArray( child, markerObj, baseArray, baseIndentLevel + 1, itemObj.grandparent ) ;
else
itemObj.contents.push( child ) ;
}
}
return baseArray ;
},
// Convert our internal representation of a list back to a DOM forest.
ArrayToList : function( listArray, markerObj, baseIndex )
{
if ( baseIndex == undefined )
baseIndex = 0 ;
if ( ! listArray || listArray.length < baseIndex + 1 )
return null ;
var doc = FCKTools.GetElementDocument( listArray[baseIndex].parent ) ;
var retval = doc.createDocumentFragment() ;
var rootNode = null ;
var currentIndex = baseIndex ;
var indentLevel = Math.max( listArray[baseIndex].indent, 0 ) ;
var currentListItem = null ;
while ( true )
{
var item = listArray[currentIndex] ;
if ( item.indent == indentLevel )
{
if ( ! rootNode || listArray[currentIndex].parent.nodeName != rootNode.nodeName )
{
rootNode = listArray[currentIndex].parent.cloneNode( false ) ;
retval.appendChild( rootNode ) ;
}
currentListItem = doc.createElement( 'li' ) ;
rootNode.appendChild( currentListItem ) ;
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.appendChild( item.contents[i].cloneNode( true ) ) ;
currentIndex++ ;
}
else if ( item.indent == Math.max( indentLevel, 0 ) + 1 )
{
var listData = this.ArrayToList( listArray, null, currentIndex ) ;
currentListItem.appendChild( listData.listNode ) ;
currentIndex = listData.nextIndex ;
}
else if ( item.indent == -1 && baseIndex == 0 && item.grandparent )
{
var currentListItem ;
if ( item.grandparent.nodeName.IEquals( ['ul', 'ol'] ) )
currentListItem = doc.createElement( 'li' ) ;
else
{
if ( FCKConfig.EnterMode.IEquals( ['div', 'p'] ) && ! item.grandparent.nodeName.IEquals( 'td' ) )
currentListItem = doc.createElement( FCKConfig.EnterMode ) ;
else
currentListItem = doc.createDocumentFragment() ;
}
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.appendChild( item.contents[i].cloneNode( true ) ) ;
if ( currentListItem.nodeType == 11 )
{
if ( currentListItem.lastChild &&
currentListItem.lastChild.getAttribute &&
currentListItem.lastChild.getAttribute( 'type' ) == '_moz' )
currentListItem.removeChild( currentListItem.lastChild );
currentListItem.appendChild( doc.createElement( 'br' ) ) ;
}
if ( currentListItem.nodeName.IEquals( FCKConfig.EnterMode ) && currentListItem.firstChild )
{
this.TrimNode( currentListItem ) ;
if ( FCKListsLib.BlockBoundaries[currentListItem.firstChild.nodeName.toLowerCase()] )
{
var tmp = doc.createDocumentFragment() ;
while ( currentListItem.firstChild )
tmp.appendChild( currentListItem.removeChild( currentListItem.firstChild ) ) ;
currentListItem = tmp ;
}
}
if ( FCKBrowserInfo.IsGeckoLike && currentListItem.nodeName.IEquals( ['div', 'p'] ) )
FCKTools.AppendBogusBr( currentListItem ) ;
retval.appendChild( currentListItem ) ;
rootNode = null ;
currentIndex++ ;
}
else
return null ;
if ( listArray.length <= currentIndex || Math.max( listArray[currentIndex].indent, 0 ) < indentLevel )
{
break ;
}
}
// Clear marker attributes for the new list tree made of cloned nodes, if any.
if ( markerObj )
{
var currentNode = retval.firstChild ;
while ( currentNode )
{
if ( currentNode.nodeType == 1 )
this.ClearElementMarkers( markerObj, currentNode ) ;
currentNode = this.GetNextSourceNode( currentNode ) ;
}
}
return { 'listNode' : retval, 'nextIndex' : currentIndex } ;
},
/**
* Get the next sibling node for a node. If "includeEmpties" is false,
* only element or non empty text nodes are returned.
*/
GetNextSibling : function( node, includeEmpties )
{
node = node.nextSibling ;
while ( node && !includeEmpties && node.nodeType != 1 && ( node.nodeType != 3 || node.nodeValue.length == 0 ) )
node = node.nextSibling ;
return node ;
},
/**
* Get the previous sibling node for a node. If "includeEmpties" is false,
* only element or non empty text nodes are returned.
*/
GetPreviousSibling : function( node, includeEmpties )
{
node = node.previousSibling ;
while ( node && !includeEmpties && node.nodeType != 1 && ( node.nodeType != 3 || node.nodeValue.length == 0 ) )
node = node.previousSibling ;
return node ;
},
/**
* Checks if an element has no "useful" content inside of it
* node tree. No "useful" content means empty text node or a signle empty
* inline node.
* elementCheckCallback may point to a function that returns a boolean
* indicating that a child element must be considered in the element check.
*/
CheckIsEmptyElement : function( element, elementCheckCallback )
{
var child = element.firstChild ;
var elementChild ;
while ( child )
{
if ( child.nodeType == 1 )
{
if ( elementChild || !FCKListsLib.InlineNonEmptyElements[ child.nodeName.toLowerCase() ] )
return false ;
if ( !elementCheckCallback || elementCheckCallback( child ) === true )
elementChild = child ;
}
else if ( child.nodeType == 3 && child.nodeValue.length > 0 )
return false ;
child = child.nextSibling ;
}
return elementChild ? this.CheckIsEmptyElement( elementChild, elementCheckCallback ) : true ;
},
SetElementStyles : function( element, styleDict )
{
var style = element.style ;
for ( var styleName in styleDict )
style[ styleName ] = styleDict[ styleName ] ;
},
SetOpacity : function( element, opacity )
{
if ( FCKBrowserInfo.IsIE )
{
opacity = Math.round( opacity * 100 ) ;
element.style.filter = ( opacity > 100 ? '' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')' ) ;
}
else
element.style.opacity = opacity ;
},
GetCurrentElementStyle : function( element, propertyName )
{
if ( FCKBrowserInfo.IsIE )
return element.currentStyle[ propertyName ] ;
else
return element.ownerDocument.defaultView.getComputedStyle( element, '' ).getPropertyValue( propertyName ) ;
},
GetPositionedAncestor : function( element )
{
var currentElement = element ;
while ( currentElement != FCKTools.GetElementDocument( currentElement ).documentElement )
{
if ( this.GetCurrentElementStyle( currentElement, 'position' ) != 'static' )
return currentElement ;
if ( currentElement == FCKTools.GetElementDocument( currentElement ).documentElement
&& currentWindow != w )
currentElement = currentWindow.frameElement ;
else
currentElement = currentElement.parentNode ;
}
return null ;
},
/**
* Current implementation for ScrollIntoView (due to #1462 and #2279). We
* don't have a complete implementation here, just the things that fit our
* needs.
*/
ScrollIntoView : function( element, alignTop )
{
// Get the element window.
var window = FCKTools.GetElementWindow( element ) ;
var windowHeight = FCKTools.GetViewPaneSize( window ).Height ;
// Starts the offset that will be scrolled with the negative value of
// the visible window height.
var offset = windowHeight * -1 ;
// Appends the height it we are about to align the bottoms.
if ( alignTop === false )
{
offset += element.offsetHeight || 0 ;
// Consider the margin in the scroll, which is ok for our current
// needs, but needs investigation if we will be using this function
// in other places.
offset += parseInt( this.GetCurrentElementStyle( element, 'marginBottom' ) || 0, 10 ) || 0 ;
}
// Appends the offsets for the entire element hierarchy.
var elementPosition = FCKTools.GetDocumentPosition( window, element ) ;
offset += elementPosition.y ;
// Scroll the window to the desired position, if not already visible.
var currentScroll = FCKTools.GetScrollPosition( window ).Y ;
if ( offset > 0 && ( offset > currentScroll || offset < currentScroll - windowHeight ) )
window.scrollTo( 0, offset ) ;
},
/**
* Check if the element can be edited inside the browser.
*/
CheckIsEditable : function( element )
{
// Get the element name.
var nodeName = element.nodeName.toLowerCase() ;
// Get the element DTD (defaults to span for unknown elements).
var childDTD = FCK.DTD[ nodeName ] || FCK.DTD.span ;
// In the DTD # == text node.
return ( childDTD['#'] && !FCKListsLib.NonEditableElements[ nodeName ] ) ;
},
GetSelectedDivContainers : function()
{
var currentBlocks = [] ;
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
var startNode = range.GetTouchedStartNode() ;
var endNode = range.GetTouchedEndNode() ;
var currentNode = startNode ;
if ( startNode == endNode )
{
while ( endNode.nodeType == 1 && endNode.lastChild )
endNode = endNode.lastChild ;
endNode = FCKDomTools.GetNextSourceNode( endNode ) ;
}
while ( currentNode && currentNode != endNode )
{
if ( currentNode.nodeType != 3 || !/^[ \t\n]*$/.test( currentNode.nodeValue ) )
{
var path = new FCKElementPath( currentNode ) ;
var blockLimit = path.BlockLimit ;
if ( blockLimit && blockLimit.nodeName.IEquals( 'div' ) && currentBlocks.IndexOf( blockLimit ) == -1 )
currentBlocks.push( blockLimit ) ;
}
currentNode = FCKDomTools.GetNextSourceNode( currentNode ) ;
}
return currentBlocks ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKURLParams object that is used to get all parameters
* passed by the URL QueryString (after the "?").
*/
// #### URLParams: holds all URL passed parameters (like ?Param1=Value1&Param2=Value2)
var FCKURLParams = new Object() ;
(function()
{
var aParams = document.location.search.substr(1).split('&') ;
for ( var i = 0 ; i < aParams.length ; i++ )
{
var aParam = aParams[i].split('=') ;
var sParamName = decodeURIComponent( aParam[0] ) ;
var sParamValue = decodeURIComponent( aParam[1] ) ;
FCKURLParams[ sParamName ] = sParamValue ;
}
})();
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This file define the HTML entities handled by the editor.
*/
var FCKXHtmlEntities = new Object() ;
FCKXHtmlEntities.Initialize = function()
{
if ( FCKXHtmlEntities.Entities )
return ;
var sChars = '' ;
var oEntities, e ;
if ( FCKConfig.ProcessHTMLEntities )
{
FCKXHtmlEntities.Entities = {
// Latin-1 Entities
' ':'nbsp',
'¡':'iexcl',
'¢':'cent',
'£':'pound',
'¤':'curren',
'¥':'yen',
'¦':'brvbar',
'§':'sect',
'¨':'uml',
'©':'copy',
'ª':'ordf',
'«':'laquo',
'¬':'not',
'':'shy',
'®':'reg',
'¯':'macr',
'°':'deg',
'±':'plusmn',
'²':'sup2',
'³':'sup3',
'´':'acute',
'µ':'micro',
'¶':'para',
'·':'middot',
'¸':'cedil',
'¹':'sup1',
'º':'ordm',
'»':'raquo',
'¼':'frac14',
'½':'frac12',
'¾':'frac34',
'¿':'iquest',
'×':'times',
'÷':'divide',
// Symbols
'ƒ':'fnof',
'•':'bull',
'…':'hellip',
'′':'prime',
'″':'Prime',
'‾':'oline',
'⁄':'frasl',
'℘':'weierp',
'ℑ':'image',
'ℜ':'real',
'™':'trade',
'ℵ':'alefsym',
'←':'larr',
'↑':'uarr',
'→':'rarr',
'↓':'darr',
'↔':'harr',
'↵':'crarr',
'⇐':'lArr',
'⇑':'uArr',
'⇒':'rArr',
'⇓':'dArr',
'⇔':'hArr',
'∀':'forall',
'∂':'part',
'∃':'exist',
'∅':'empty',
'∇':'nabla',
'∈':'isin',
'∉':'notin',
'∋':'ni',
'∏':'prod',
'∑':'sum',
'−':'minus',
'∗':'lowast',
'√':'radic',
'∝':'prop',
'∞':'infin',
'∠':'ang',
'∧':'and',
'∨':'or',
'∩':'cap',
'∪':'cup',
'∫':'int',
'∴':'there4',
'∼':'sim',
'≅':'cong',
'≈':'asymp',
'≠':'ne',
'≡':'equiv',
'≤':'le',
'≥':'ge',
'⊂':'sub',
'⊃':'sup',
'⊄':'nsub',
'⊆':'sube',
'⊇':'supe',
'⊕':'oplus',
'⊗':'otimes',
'⊥':'perp',
'⋅':'sdot',
'\u2308':'lceil',
'\u2309':'rceil',
'\u230a':'lfloor',
'\u230b':'rfloor',
'\u2329':'lang',
'\u232a':'rang',
'◊':'loz',
'♠':'spades',
'♣':'clubs',
'♥':'hearts',
'♦':'diams',
// Other Special Characters
'"':'quot',
// '&':'amp', // This entity is automatically handled by the XHTML parser.
// '<':'lt', // This entity is automatically handled by the XHTML parser.
'>':'gt', // Opera and Safari don't encode it in their implementation
'ˆ':'circ',
'˜':'tilde',
' ':'ensp',
' ':'emsp',
' ':'thinsp',
'':'zwnj',
'':'zwj',
'':'lrm',
'':'rlm',
'–':'ndash',
'—':'mdash',
'‘':'lsquo',
'’':'rsquo',
'‚':'sbquo',
'“':'ldquo',
'”':'rdquo',
'„':'bdquo',
'†':'dagger',
'‡':'Dagger',
'‰':'permil',
'‹':'lsaquo',
'›':'rsaquo',
'€':'euro'
} ;
// Process Base Entities.
for ( e in FCKXHtmlEntities.Entities )
sChars += e ;
// Include Latin Letters Entities.
if ( FCKConfig.IncludeLatinEntities )
{
oEntities = {
'À':'Agrave',
'Á':'Aacute',
'Â':'Acirc',
'Ã':'Atilde',
'Ä':'Auml',
'Å':'Aring',
'Æ':'AElig',
'Ç':'Ccedil',
'È':'Egrave',
'É':'Eacute',
'Ê':'Ecirc',
'Ë':'Euml',
'Ì':'Igrave',
'Í':'Iacute',
'Î':'Icirc',
'Ï':'Iuml',
'Ð':'ETH',
'Ñ':'Ntilde',
'Ò':'Ograve',
'Ó':'Oacute',
'Ô':'Ocirc',
'Õ':'Otilde',
'Ö':'Ouml',
'Ø':'Oslash',
'Ù':'Ugrave',
'Ú':'Uacute',
'Û':'Ucirc',
'Ü':'Uuml',
'Ý':'Yacute',
'Þ':'THORN',
'ß':'szlig',
'à':'agrave',
'á':'aacute',
'â':'acirc',
'ã':'atilde',
'ä':'auml',
'å':'aring',
'æ':'aelig',
'ç':'ccedil',
'è':'egrave',
'é':'eacute',
'ê':'ecirc',
'ë':'euml',
'ì':'igrave',
'í':'iacute',
'î':'icirc',
'ï':'iuml',
'ð':'eth',
'ñ':'ntilde',
'ò':'ograve',
'ó':'oacute',
'ô':'ocirc',
'õ':'otilde',
'ö':'ouml',
'ø':'oslash',
'ù':'ugrave',
'ú':'uacute',
'û':'ucirc',
'ü':'uuml',
'ý':'yacute',
'þ':'thorn',
'ÿ':'yuml',
'Œ':'OElig',
'œ':'oelig',
'Š':'Scaron',
'š':'scaron',
'Ÿ':'Yuml'
} ;
for ( e in oEntities )
{
FCKXHtmlEntities.Entities[ e ] = oEntities[ e ] ;
sChars += e ;
}
oEntities = null ;
}
// Include Greek Letters Entities.
if ( FCKConfig.IncludeGreekEntities )
{
oEntities = {
'Α':'Alpha',
'Β':'Beta',
'Γ':'Gamma',
'Δ':'Delta',
'Ε':'Epsilon',
'Ζ':'Zeta',
'Η':'Eta',
'Θ':'Theta',
'Ι':'Iota',
'Κ':'Kappa',
'Λ':'Lambda',
'Μ':'Mu',
'Ν':'Nu',
'Ξ':'Xi',
'Ο':'Omicron',
'Π':'Pi',
'Ρ':'Rho',
'Σ':'Sigma',
'Τ':'Tau',
'Υ':'Upsilon',
'Φ':'Phi',
'Χ':'Chi',
'Ψ':'Psi',
'Ω':'Omega',
'α':'alpha',
'β':'beta',
'γ':'gamma',
'δ':'delta',
'ε':'epsilon',
'ζ':'zeta',
'η':'eta',
'θ':'theta',
'ι':'iota',
'κ':'kappa',
'λ':'lambda',
'μ':'mu',
'ν':'nu',
'ξ':'xi',
'ο':'omicron',
'π':'pi',
'ρ':'rho',
'ς':'sigmaf',
'σ':'sigma',
'τ':'tau',
'υ':'upsilon',
'φ':'phi',
'χ':'chi',
'ψ':'psi',
'ω':'omega',
'\u03d1':'thetasym',
'\u03d2':'upsih',
'\u03d6':'piv'
} ;
for ( e in oEntities )
{
FCKXHtmlEntities.Entities[ e ] = oEntities[ e ] ;
sChars += e ;
}
oEntities = null ;
}
}
else
{
FCKXHtmlEntities.Entities = {
'>':'gt' // Opera and Safari don't encode it in their implementation
} ;
sChars = '>';
// Even if we are not processing the entities, we must render the
// correctly. As we don't want HTML entities, let's use its numeric
// representation ( ).
sChars += ' ' ;
}
// Create the Regex used to find entities in the text.
var sRegexPattern = '[' + sChars + ']' ;
if ( FCKConfig.ProcessNumericEntities )
sRegexPattern = '[^ -~]|' + sRegexPattern ;
var sAdditional = FCKConfig.AdditionalNumericEntities ;
if ( sAdditional && sAdditional.length > 0 )
sRegexPattern += '|' + FCKConfig.AdditionalNumericEntities ;
FCKXHtmlEntities.EntitiesRegex = new RegExp( sRegexPattern, 'g' ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Active selection functions. (IE specific implementation)
*/
// Get the selection type.
FCKSelection.GetType = function()
{
// It is possible that we can still get a text range object even when type=='None' is returned by IE.
// So we'd better check the object returned by createRange() rather than by looking at the type.
try
{
var ieType = FCKSelection.GetSelection().type ;
if ( ieType == 'Control' || ieType == 'Text' )
return ieType ;
if ( this.GetSelection().createRange().parentElement )
return 'Text' ;
}
catch(e)
{
// Nothing to do, it will return None properly.
}
return 'None' ;
} ;
// Retrieves the selected element (if any), just in the case that a single
// element (object like and image or a table) is selected.
FCKSelection.GetSelectedElement = function()
{
if ( this.GetType() == 'Control' )
{
var oRange = this.GetSelection().createRange() ;
if ( oRange && oRange.item )
return this.GetSelection().createRange().item(0) ;
}
return null ;
} ;
FCKSelection.GetParentElement = function()
{
switch ( this.GetType() )
{
case 'Control' :
var el = FCKSelection.GetSelectedElement() ;
return el ? el.parentElement : null ;
case 'None' :
return null ;
default :
return this.GetSelection().createRange().parentElement() ;
}
} ;
FCKSelection.GetBoundaryParentElement = function( startBoundary )
{
switch ( this.GetType() )
{
case 'Control' :
var el = FCKSelection.GetSelectedElement() ;
return el ? el.parentElement : null ;
case 'None' :
return null ;
default :
var doc = FCK.EditorDocument ;
var range = doc.selection.createRange() ;
range.collapse( startBoundary !== false ) ;
var el = range.parentElement() ;
// It may happen that range is comming from outside "doc", so we
// must check it (#1204).
return FCKTools.GetElementDocument( el ) == doc ? el : null ;
}
} ;
FCKSelection.SelectNode = function( node )
{
FCK.Focus() ;
this.GetSelection().empty() ;
var oRange ;
try
{
// Try to select the node as a control.
oRange = FCK.EditorDocument.body.createControlRange() ;
oRange.addElement( node ) ;
}
catch(e)
{
// If failed, select it as a text range.
oRange = FCK.EditorDocument.body.createTextRange() ;
oRange.moveToElementText( node ) ;
}
oRange.select() ;
} ;
FCKSelection.Collapse = function( toStart )
{
FCK.Focus() ;
if ( this.GetType() == 'Text' )
{
var oRange = this.GetSelection().createRange() ;
oRange.collapse( toStart == null || toStart === true ) ;
oRange.select() ;
}
} ;
// The "nodeTagName" parameter must be Upper Case.
FCKSelection.HasAncestorNode = function( nodeTagName )
{
var oContainer ;
if ( this.GetSelection().type == "Control" )
{
oContainer = this.GetSelectedElement() ;
}
else
{
var oRange = this.GetSelection().createRange() ;
oContainer = oRange.parentElement() ;
}
while ( oContainer )
{
if ( oContainer.nodeName.IEquals( nodeTagName ) ) return true ;
oContainer = oContainer.parentNode ;
}
return false ;
} ;
// The "nodeTagName" parameter must be UPPER CASE.
// It can be also an array of names
FCKSelection.MoveToAncestorNode = function( nodeTagName )
{
var oNode, oRange ;
if ( ! FCK.EditorDocument )
return null ;
if ( this.GetSelection().type == "Control" )
{
oRange = this.GetSelection().createRange() ;
for ( i = 0 ; i < oRange.length ; i++ )
{
if (oRange(i).parentNode)
{
oNode = oRange(i).parentNode ;
break ;
}
}
}
else
{
oRange = this.GetSelection().createRange() ;
oNode = oRange.parentElement() ;
}
while ( oNode && !oNode.nodeName.Equals( nodeTagName ) )
oNode = oNode.parentNode ;
return oNode ;
} ;
FCKSelection.Delete = function()
{
// Gets the actual selection.
var oSel = this.GetSelection() ;
// Deletes the actual selection contents.
if ( oSel.type.toLowerCase() != "none" )
{
oSel.clear() ;
}
return oSel ;
} ;
/**
* Returns the native selection object.
*/
FCKSelection.GetSelection = function()
{
this.Restore() ;
return FCK.EditorDocument.selection ;
}
FCKSelection.Save = function( lock )
{
var editorDocument = FCK.EditorDocument ;
if ( !editorDocument )
return ;
// Avoid saving again a selection while a dialog is open #2616
if ( this.locked )
return ;
this.locked = !!lock ;
var selection = editorDocument.selection ;
var range ;
if ( selection )
{
// The call might fail if the document doesn't have the focus (#1801),
// but we don't want to modify the current selection (#2495) with a call to FCK.Focus() ;
try {
range = selection.createRange() ;
}
catch(e) {}
// Ensure that the range comes from the editor document.
if ( range )
{
if ( range.parentElement && FCKTools.GetElementDocument( range.parentElement() ) != editorDocument )
range = null ;
else if ( range.item && FCKTools.GetElementDocument( range.item(0) )!= editorDocument )
range = null ;
}
}
this.SelectionData = range ;
}
FCKSelection._GetSelectionDocument = function( selection )
{
var range = selection.createRange() ;
if ( !range )
return null;
else if ( range.item )
return FCKTools.GetElementDocument( range.item( 0 ) ) ;
else
return FCKTools.GetElementDocument( range.parentElement() ) ;
}
FCKSelection.Restore = function()
{
if ( this.SelectionData )
{
FCK.IsSelectionChangeLocked = true ;
try
{
// Don't repeat the restore process if the editor document is already selected.
if ( String( this._GetSelectionDocument( FCK.EditorDocument.selection ).body.contentEditable ) == 'true' )
{
FCK.IsSelectionChangeLocked = false ;
return ;
}
this.SelectionData.select() ;
}
catch ( e ) {}
FCK.IsSelectionChangeLocked = false ;
}
}
FCKSelection.Release = function()
{
this.locked = false ;
delete this.SelectionData ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Handles styles in a give document.
*/
var FCKStyles = FCK.Styles =
{
_Callbacks : {},
_ObjectStyles : {},
ApplyStyle : function( style )
{
if ( typeof style == 'string' )
style = this.GetStyles()[ style ] ;
if ( style )
{
if ( style.GetType() == FCK_STYLE_OBJECT )
style.ApplyToObject( FCKSelection.GetSelectedElement() ) ;
else
style.ApplyToSelection( FCK.EditorWindow ) ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
},
RemoveStyle : function( style )
{
if ( typeof style == 'string' )
style = this.GetStyles()[ style ] ;
if ( style )
{
style.RemoveFromSelection( FCK.EditorWindow ) ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
}
},
/**
* Defines a callback function to be called when the current state of a
* specific style changes.
*/
AttachStyleStateChange : function( styleName, callback, callbackOwner )
{
var callbacks = this._Callbacks[ styleName ] ;
if ( !callbacks )
callbacks = this._Callbacks[ styleName ] = [] ;
callbacks.push( [ callback, callbackOwner ] ) ;
},
CheckSelectionChanges : function()
{
var startElement = FCKSelection.GetBoundaryParentElement( true ) ;
if ( !startElement )
return ;
// Walks the start node parents path, checking all styles that are being listened.
var path = new FCKElementPath( startElement ) ;
var styles = this.GetStyles() ;
for ( var styleName in styles )
{
var callbacks = this._Callbacks[ styleName ] ;
if ( callbacks )
{
var style = styles[ styleName ] ;
var state = style.CheckActive( path ) ;
if ( state != ( style._LastState || null ) )
{
style._LastState = state ;
for ( var i = 0 ; i < callbacks.length ; i++ )
{
var callback = callbacks[i][0] ;
var callbackOwner = callbacks[i][1] ;
callback.call( callbackOwner || window, styleName, state ) ;
}
}
}
}
},
CheckStyleInSelection : function( styleName )
{
return false ;
},
_GetRemoveFormatTagsRegex : function ()
{
var regex = new RegExp( '^(?:' + FCKConfig.RemoveFormatTags.replace( /,/g,'|' ) + ')$', 'i' ) ;
return (this._GetRemoveFormatTagsRegex = function()
{
return regex ;
})
&& regex ;
},
/**
* Remove all styles from the current selection.
* TODO:
* - This is almost a duplication of FCKStyle.RemoveFromRange. We should
* try to merge things.
*/
RemoveAll : function()
{
var range = new FCKDomRange( FCK.EditorWindow ) ;
range.MoveToSelection() ;
if ( range.CheckIsCollapsed() )
return ;
// Expand the range, if inside inline element boundaries.
range.Expand( 'inline_elements' ) ;
// Get the bookmark nodes.
// Bookmark the range so we can re-select it after processing.
var bookmark = range.CreateBookmark( true ) ;
// The style will be applied within the bookmark boundaries.
var startNode = range.GetBookmarkNode( bookmark, true ) ;
var endNode = range.GetBookmarkNode( bookmark, false ) ;
range.Release( true ) ;
var tagsRegex = this._GetRemoveFormatTagsRegex() ;
// We need to check the selection boundaries (bookmark spans) to break
// the code in a way that we can properly remove partially selected nodes.
// For example, removing a <b> style from
// <b>This is [some text</b> to show <b>the] problem</b>
// ... where [ and ] represent the selection, must result:
// <b>This is </b>[some text to show the]<b> problem</b>
// The strategy is simple, we just break the partial nodes before the
// removal logic, having something that could be represented this way:
// <b>This is </b>[<b>some text</b> to show <b>the</b>]<b> problem</b>
// Let's start checking the start boundary.
var path = new FCKElementPath( startNode ) ;
var pathElements = path.Elements ;
var pathElement ;
for ( var i = 1 ; i < pathElements.length ; i++ )
{
pathElement = pathElements[i] ;
if ( pathElement == path.Block || pathElement == path.BlockLimit )
break ;
// If this element can be removed (even partially).
if ( tagsRegex.test( pathElement.nodeName ) )
FCKDomTools.BreakParent( startNode, pathElement, range ) ;
}
// Now the end boundary.
path = new FCKElementPath( endNode ) ;
pathElements = path.Elements ;
for ( var i = 1 ; i < pathElements.length ; i++ )
{
pathElement = pathElements[i] ;
if ( pathElement == path.Block || pathElement == path.BlockLimit )
break ;
elementName = pathElement.nodeName.toLowerCase() ;
// If this element can be removed (even partially).
if ( tagsRegex.test( pathElement.nodeName ) )
FCKDomTools.BreakParent( endNode, pathElement, range ) ;
}
// Navigate through all nodes between the bookmarks.
var currentNode = FCKDomTools.GetNextSourceNode( startNode, true, 1 ) ;
while ( currentNode )
{
// If we have reached the end of the selection, stop looping.
if ( currentNode == endNode )
break ;
// Cache the next node to be processed. Do it now, because
// currentNode may be removed.
var nextNode = FCKDomTools.GetNextSourceNode( currentNode, false, 1 ) ;
// Remove elements nodes that match with this style rules.
if ( tagsRegex.test( currentNode.nodeName ) )
FCKDomTools.RemoveNode( currentNode, true ) ;
else
FCKDomTools.RemoveAttributes( currentNode, FCKConfig.RemoveAttributesArray );
currentNode = nextNode ;
}
range.SelectBookmark( bookmark ) ;
FCK.Events.FireEvent( 'OnSelectionChange' ) ;
},
GetStyle : function( styleName )
{
return this.GetStyles()[ styleName ] ;
},
GetStyles : function()
{
var styles = this._GetStyles ;
if ( !styles )
{
styles = this._GetStyles = FCKTools.Merge(
this._LoadStylesCore(),
this._LoadStylesCustom(),
this._LoadStylesXml() ) ;
}
return styles ;
},
CheckHasObjectStyle : function( elementName )
{
return !!this._ObjectStyles[ elementName ] ;
},
_LoadStylesCore : function()
{
var styles = {};
var styleDefs = FCKConfig.CoreStyles ;
for ( var styleName in styleDefs )
{
// Core styles are prefixed with _FCK_.
var style = styles[ '_FCK_' + styleName ] = new FCKStyle( styleDefs[ styleName ] ) ;
style.IsCore = true ;
}
return styles ;
},
_LoadStylesCustom : function()
{
var styles = {};
var styleDefs = FCKConfig.CustomStyles ;
if ( styleDefs )
{
for ( var styleName in styleDefs )
{
var style = styles[ styleName ] = new FCKStyle( styleDefs[ styleName ] ) ;
style.Name = styleName ;
}
}
return styles ;
},
_LoadStylesXml : function()
{
var styles = {};
var stylesXmlPath = FCKConfig.StylesXmlPath ;
if ( !stylesXmlPath || stylesXmlPath.length == 0 )
return styles ;
// Load the XML file into a FCKXml object.
var xml = new FCKXml() ;
xml.LoadUrl( stylesXmlPath ) ;
var stylesXmlObj = FCKXml.TransformToObject( xml.SelectSingleNode( 'Styles' ) ) ;
// Get the "Style" nodes defined in the XML file.
var styleNodes = stylesXmlObj.$Style ;
// Check that it did contain some valid nodes
if ( !styleNodes )
return styles ;
// Add each style to our "Styles" collection.
for ( var i = 0 ; i < styleNodes.length ; i++ )
{
var styleNode = styleNodes[i] ;
var element = ( styleNode.element || '' ).toLowerCase() ;
if ( element.length == 0 )
throw( 'The element name is required. Error loading "' + stylesXmlPath + '"' ) ;
var styleDef = {
Element : element,
Attributes : {},
Styles : {},
Overrides : []
} ;
// Get the attributes defined for the style (if any).
var attNodes = styleNode.$Attribute || [] ;
// Add the attributes to the style definition object.
for ( var j = 0 ; j < attNodes.length ; j++ )
{
styleDef.Attributes[ attNodes[j].name ] = attNodes[j].value ;
}
// Get the styles defined for the style (if any).
var cssStyleNodes = styleNode.$Style || [] ;
// Add the attributes to the style definition object.
for ( j = 0 ; j < cssStyleNodes.length ; j++ )
{
styleDef.Styles[ cssStyleNodes[j].name ] = cssStyleNodes[j].value ;
}
// Load override definitions.
var cssStyleOverrideNodes = styleNode.$Override ;
if ( cssStyleOverrideNodes )
{
for ( j = 0 ; j < cssStyleOverrideNodes.length ; j++ )
{
var overrideNode = cssStyleOverrideNodes[j] ;
var overrideDef =
{
Element : overrideNode.element
} ;
var overrideAttNode = overrideNode.$Attribute ;
if ( overrideAttNode )
{
overrideDef.Attributes = {} ;
for ( var k = 0 ; k < overrideAttNode.length ; k++ )
{
var overrideAttValue = overrideAttNode[k].value || null ;
if ( overrideAttValue )
{
// Check if the override attribute value is a regular expression.
var regexMatch = overrideAttValue && FCKRegexLib.RegExp.exec( overrideAttValue ) ;
if ( regexMatch )
overrideAttValue = new RegExp( regexMatch[1], regexMatch[2] || '' ) ;
}
overrideDef.Attributes[ overrideAttNode[k].name ] = overrideAttValue ;
}
}
styleDef.Overrides.push( overrideDef ) ;
}
}
var style = new FCKStyle( styleDef ) ;
style.Name = styleNode.name || element ;
if ( style.GetType() == FCK_STYLE_OBJECT )
this._ObjectStyles[ element ] = true ;
// Add the style to the "Styles" collection using it's name as the key.
styles[ style.Name ] = style ;
}
return styles ;
}
} ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Format the HTML.
*/
var FCKCodeFormatter = new Object() ;
FCKCodeFormatter.Init = function()
{
var oRegex = this.Regex = new Object() ;
// Regex for line breaks.
oRegex.BlocksOpener = /\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DL|DT|DD|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi ;
oRegex.BlocksCloser = /\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DL|DT|DD|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi ;
oRegex.NewLineTags = /\<(BR|HR)[^\>]*\>/gi ;
oRegex.MainTags = /\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi ;
oRegex.LineSplitter = /\s*\n+\s*/g ;
// Regex for indentation.
oRegex.IncreaseIndent = /^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL|DL)[ \/\>]/i ;
oRegex.DecreaseIndent = /^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL|DL)[ \>]/i ;
oRegex.FormatIndentatorRemove = new RegExp( '^' + FCKConfig.FormatIndentator ) ;
oRegex.ProtectedTags = /(<PRE[^>]*>)([\s\S]*?)(<\/PRE>)/gi ;
}
FCKCodeFormatter._ProtectData = function( outer, opener, data, closer )
{
return opener + '___FCKpd___' + ( FCKCodeFormatter.ProtectedData.push( data ) - 1 ) + closer ;
}
FCKCodeFormatter.Format = function( html )
{
if ( !this.Regex )
this.Init() ;
// Protected content that remain untouched during the
// process go in the following array.
FCKCodeFormatter.ProtectedData = new Array() ;
var sFormatted = html.replace( this.Regex.ProtectedTags, FCKCodeFormatter._ProtectData ) ;
// Line breaks.
sFormatted = sFormatted.replace( this.Regex.BlocksOpener, '\n$&' ) ;
sFormatted = sFormatted.replace( this.Regex.BlocksCloser, '$&\n' ) ;
sFormatted = sFormatted.replace( this.Regex.NewLineTags, '$&\n' ) ;
sFormatted = sFormatted.replace( this.Regex.MainTags, '\n$&\n' ) ;
// Indentation.
var sIndentation = '' ;
var asLines = sFormatted.split( this.Regex.LineSplitter ) ;
sFormatted = '' ;
for ( var i = 0 ; i < asLines.length ; i++ )
{
var sLine = asLines[i] ;
if ( sLine.length == 0 )
continue ;
if ( this.Regex.DecreaseIndent.test( sLine ) )
sIndentation = sIndentation.replace( this.Regex.FormatIndentatorRemove, '' ) ;
sFormatted += sIndentation + sLine + '\n' ;
if ( this.Regex.IncreaseIndent.test( sLine ) )
sIndentation += FCKConfig.FormatIndentator ;
}
// Now we put back the protected data.
for ( var j = 0 ; j < FCKCodeFormatter.ProtectedData.length ; j++ )
{
var oRegex = new RegExp( '___FCKpd___' + j ) ;
sFormatted = sFormatted.replace( oRegex, FCKCodeFormatter.ProtectedData[j].replace( /\$/g, '$$$$' ) ) ;
}
return sFormatted.Trim() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Utility functions. (IE version).
*/
FCKTools.CancelEvent = function( e )
{
return false ;
}
// Appends one or more CSS files to a document.
FCKTools._AppendStyleSheet = function( documentElement, cssFileUrl )
{
return documentElement.createStyleSheet( cssFileUrl ).owningElement ;
}
// Appends a CSS style string to a document.
FCKTools.AppendStyleString = function( documentElement, cssStyles )
{
if ( !cssStyles )
return null ;
var s = documentElement.createStyleSheet( "" ) ;
s.cssText = cssStyles ;
return s ;
}
// Removes all attributes and values from the element.
FCKTools.ClearElementAttributes = function( element )
{
element.clearAttributes() ;
}
FCKTools.GetAllChildrenIds = function( parentElement )
{
var aIds = new Array() ;
for ( var i = 0 ; i < parentElement.all.length ; i++ )
{
var sId = parentElement.all[i].id ;
if ( sId && sId.length > 0 )
aIds[ aIds.length ] = sId ;
}
return aIds ;
}
FCKTools.RemoveOuterTags = function( e )
{
e.insertAdjacentHTML( 'beforeBegin', e.innerHTML ) ;
e.parentNode.removeChild( e ) ;
}
FCKTools.CreateXmlObject = function( object )
{
var aObjs ;
switch ( object )
{
case 'XmlHttp' :
// Try the native XMLHttpRequest introduced with IE7.
if ( document.location.protocol != 'file:' )
try { return new XMLHttpRequest() ; } catch (e) {}
aObjs = [ 'MSXML2.XmlHttp', 'Microsoft.XmlHttp' ] ;
break ;
case 'DOMDocument' :
aObjs = [ 'MSXML2.DOMDocument', 'Microsoft.XmlDom' ] ;
break ;
}
for ( var i = 0 ; i < 2 ; i++ )
{
try { return new ActiveXObject( aObjs[i] ) ; }
catch (e)
{}
}
if ( FCKLang.NoActiveX )
{
alert( FCKLang.NoActiveX ) ;
FCKLang.NoActiveX = null ;
}
return null ;
}
FCKTools.DisableSelection = function( element )
{
element.unselectable = 'on' ;
var e, i = 0 ;
// The extra () is to avoid a warning with strict error checking. This is ok.
while ( (e = element.all[ i++ ]) )
{
switch ( e.tagName )
{
case 'IFRAME' :
case 'TEXTAREA' :
case 'INPUT' :
case 'SELECT' :
/* Ignore the above tags */
break ;
default :
e.unselectable = 'on' ;
}
}
}
FCKTools.GetScrollPosition = function( relativeWindow )
{
var oDoc = relativeWindow.document ;
// Try with the doc element.
var oPos = { X : oDoc.documentElement.scrollLeft, Y : oDoc.documentElement.scrollTop } ;
if ( oPos.X > 0 || oPos.Y > 0 )
return oPos ;
// If no scroll, try with the body.
return { X : oDoc.body.scrollLeft, Y : oDoc.body.scrollTop } ;
}
FCKTools.AddEventListener = function( sourceObject, eventName, listener )
{
sourceObject.attachEvent( 'on' + eventName, listener ) ;
}
FCKTools.RemoveEventListener = function( sourceObject, eventName, listener )
{
sourceObject.detachEvent( 'on' + eventName, listener ) ;
}
// Listeners attached with this function cannot be detached.
FCKTools.AddEventListenerEx = function( sourceObject, eventName, listener, paramsArray )
{
// Ok... this is a closures party, but is the only way to make it clean of memory leaks.
var o = new Object() ;
o.Source = sourceObject ;
o.Params = paramsArray || [] ; // Memory leak if we have DOM objects here.
o.Listener = function( ev )
{
return listener.apply( o.Source, [ ev ].concat( o.Params ) ) ;
}
if ( FCK.IECleanup )
FCK.IECleanup.AddItem( null, function() { o.Source = null ; o.Params = null ; } ) ;
sourceObject.attachEvent( 'on' + eventName, o.Listener ) ;
sourceObject = null ; // Memory leak cleaner (because of the above closure).
paramsArray = null ; // Memory leak cleaner (because of the above closure).
}
// Returns and object with the "Width" and "Height" properties.
FCKTools.GetViewPaneSize = function( win )
{
var oSizeSource ;
var oDoc = win.document.documentElement ;
if ( oDoc && oDoc.clientWidth ) // IE6 Strict Mode
oSizeSource = oDoc ;
else
oSizeSource = win.document.body ; // Other IEs
if ( oSizeSource )
return { Width : oSizeSource.clientWidth, Height : oSizeSource.clientHeight } ;
else
return { Width : 0, Height : 0 } ;
}
FCKTools.SaveStyles = function( element )
{
var data = FCKTools.ProtectFormStyles( element ) ;
var oSavedStyles = new Object() ;
if ( element.className.length > 0 )
{
oSavedStyles.Class = element.className ;
element.className = '' ;
}
var sInlineStyle = element.style.cssText ;
if ( sInlineStyle.length > 0 )
{
oSavedStyles.Inline = sInlineStyle ;
element.style.cssText = '' ;
}
FCKTools.RestoreFormStyles( element, data ) ;
return oSavedStyles ;
}
FCKTools.RestoreStyles = function( element, savedStyles )
{
var data = FCKTools.ProtectFormStyles( element ) ;
element.className = savedStyles.Class || '' ;
element.style.cssText = savedStyles.Inline || '' ;
FCKTools.RestoreFormStyles( element, data ) ;
}
FCKTools.RegisterDollarFunction = function( targetWindow )
{
targetWindow.$ = targetWindow.document.getElementById ;
}
FCKTools.AppendElement = function( target, elementName )
{
return target.appendChild( this.GetElementDocument( target ).createElement( elementName ) ) ;
}
// This function may be used by Regex replacements.
FCKTools.ToLowerCase = function( strValue )
{
return strValue.toLowerCase() ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Active selection functions. (Gecko specific implementation)
*/
// Get the selection type (like document.select.type in IE).
FCKSelection.GetType = function()
{
// By default set the type to "Text".
var type = 'Text' ;
// Check if the actual selection is a Control (IMG, TABLE, HR, etc...).
var sel ;
try { sel = this.GetSelection() ; } catch (e) {}
if ( sel && sel.rangeCount == 1 )
{
var range = sel.getRangeAt(0) ;
if ( range.startContainer == range.endContainer
&& ( range.endOffset - range.startOffset ) == 1
&& range.startContainer.nodeType == 1
&& FCKListsLib.StyleObjectElements[ range.startContainer.childNodes[ range.startOffset ].nodeName.toLowerCase() ] )
{
type = 'Control' ;
}
}
return type ;
}
// Retrieves the selected element (if any), just in the case that a single
// element (object like and image or a table) is selected.
FCKSelection.GetSelectedElement = function()
{
var selection = !!FCK.EditorWindow && this.GetSelection() ;
if ( !selection || selection.rangeCount < 1 )
return null ;
var range = selection.getRangeAt( 0 ) ;
if ( range.startContainer != range.endContainer || range.startContainer.nodeType != 1 || range.startOffset != range.endOffset - 1 )
return null ;
var node = range.startContainer.childNodes[ range.startOffset ] ;
if ( node.nodeType != 1 )
return null ;
return node ;
}
FCKSelection.GetParentElement = function()
{
if ( this.GetType() == 'Control' )
return FCKSelection.GetSelectedElement().parentNode ;
else
{
var oSel = this.GetSelection() ;
if ( oSel )
{
// if anchorNode == focusNode, see if the selection is text only or including nodes.
// if text only, return the parent node.
// if the selection includes DOM nodes, then the anchorNode is the nearest container.
if ( oSel.anchorNode && oSel.anchorNode == oSel.focusNode )
{
var oRange = oSel.getRangeAt( 0 ) ;
if ( oRange.collapsed || oRange.startContainer.nodeType == 3 )
return oSel.anchorNode.parentNode ;
else
return oSel.anchorNode ;
}
// looks like we're having a large selection here. To make the behavior same as IE's TextRange.parentElement(),
// we need to find the nearest ancestor node which encapsulates both the beginning and the end of the selection.
// TODO: A simpler logic can be found.
var anchorPath = new FCKElementPath( oSel.anchorNode ) ;
var focusPath = new FCKElementPath( oSel.focusNode ) ;
var deepPath = null ;
var shallowPath = null ;
if ( anchorPath.Elements.length > focusPath.Elements.length )
{
deepPath = anchorPath.Elements ;
shallowPath = focusPath.Elements ;
}
else
{
deepPath = focusPath.Elements ;
shallowPath = anchorPath.Elements ;
}
var deepPathBase = deepPath.length - shallowPath.length ;
for( var i = 0 ; i < shallowPath.length ; i++)
{
if ( deepPath[deepPathBase + i] == shallowPath[i])
return shallowPath[i];
}
return null ;
}
}
return null ;
}
FCKSelection.GetBoundaryParentElement = function( startBoundary )
{
if ( ! FCK.EditorWindow )
return null ;
if ( this.GetType() == 'Control' )
return FCKSelection.GetSelectedElement().parentNode ;
else
{
var oSel = this.GetSelection() ;
if ( oSel && oSel.rangeCount > 0 )
{
var range = oSel.getRangeAt( startBoundary ? 0 : ( oSel.rangeCount - 1 ) ) ;
var element = startBoundary ? range.startContainer : range.endContainer ;
return ( element.nodeType == 1 ? element : element.parentNode ) ;
}
}
return null ;
}
FCKSelection.SelectNode = function( element )
{
var oRange = FCK.EditorDocument.createRange() ;
oRange.selectNode( element ) ;
var oSel = this.GetSelection() ;
oSel.removeAllRanges() ;
oSel.addRange( oRange ) ;
}
FCKSelection.Collapse = function( toStart )
{
var oSel = this.GetSelection() ;
if ( toStart == null || toStart === true )
oSel.collapseToStart() ;
else
oSel.collapseToEnd() ;
}
// The "nodeTagName" parameter must be Upper Case.
FCKSelection.HasAncestorNode = function( nodeTagName )
{
var oContainer = this.GetSelectedElement() ;
if ( ! oContainer && FCK.EditorWindow )
{
try { oContainer = this.GetSelection().getRangeAt(0).startContainer ; }
catch(e){}
}
while ( oContainer )
{
if ( oContainer.nodeType == 1 && oContainer.nodeName.IEquals( nodeTagName ) ) return true ;
oContainer = oContainer.parentNode ;
}
return false ;
}
// The "nodeTagName" parameter must be Upper Case.
FCKSelection.MoveToAncestorNode = function( nodeTagName )
{
var oNode ;
var oContainer = this.GetSelectedElement() ;
if ( ! oContainer )
oContainer = this.GetSelection().getRangeAt(0).startContainer ;
while ( oContainer )
{
if ( oContainer.nodeName.IEquals( nodeTagName ) )
return oContainer ;
oContainer = oContainer.parentNode ;
}
return null ;
}
FCKSelection.Delete = function()
{
// Gets the actual selection.
var oSel = this.GetSelection() ;
// Deletes the actual selection contents.
for ( var i = 0 ; i < oSel.rangeCount ; i++ )
{
oSel.getRangeAt(i).deleteContents() ;
}
return oSel ;
}
/**
* Returns the native selection object.
*/
FCKSelection.GetSelection = function()
{
return FCK.EditorWindow.getSelection() ;
}
// The following are IE only features (we don't need then in other browsers
// currently).
FCKSelection.Save = function()
{}
FCKSelection.Restore = function()
{}
FCKSelection.Release = function()
{}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Active selection functions.
*/
var FCKSelection = FCK.Selection =
{
GetParentBlock : function()
{
var retval = this.GetParentElement() ;
while ( retval )
{
if ( FCKListsLib.BlockBoundaries[retval.nodeName.toLowerCase()] )
break ;
retval = retval.parentNode ;
}
return retval ;
},
ApplyStyle : function( styleDefinition )
{
FCKStyles.ApplyStyle( new FCKStyle( styleDefinition ) ) ;
}
} ;
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.